javascript表单验证刷新页面

时间:2011-01-28 06:10:09

标签: javascript validation forms client client-side

function subVal()
{
    if (document.forms['loginform'].name.value == '' || document.forms['loginform'].uid.value == '')
    {
        if (document.forms['loginform'].uid.value == '')
    {
        document.getElementById('afterpass').innerHTML = 'FORGOT PASSWORD';
    }
    if (document.forms['loginform'].name.value == '')
    {
        document.getElementById('aftername').innerHTML = 'FORGOT USERNAME';
    }
    }
    if (document.forms['loginform'].name.value != '' && document.forms['loginform'].uid.value != '')
    {
        document.forms['loginform'].submit();
    }
}

当我尝试验证时,它会执行它应该执行的操作(插入HTML)然后刷新。我怎么能阻止这个?

2 个答案:

答案 0 :(得分:1)

<script>
function subVal()
{ 

    if (document.getElementById('name').value == '' && document.getElementById('uid').value == '')
    {
        document.getElementById('aftername').innerHTML = 'FORGOT USERNAME';

        document.getElementById('afterpass').innerHTML = 'FORGOT PASSWORD';
            return false;
    }   
    else if ( document.getElementById('uid').value == '' )
        {
            document.getElementById('afterpass').innerHTML = 'FORGOT PASSWORD';
            return false;
        }
    else if (document.getElementById('name').value == '')
        { 
            document.getElementById('aftername').innerHTML = 'FORGOT USERNAME';
            return false;
        }
    else
  {
        document.forms['loginform'].submit();
    }
}


</script>

<form method='post' name='loginform'>
<input type='text' name='name' id="name" />
<div id='aftername'></div>
<input type='password' name='uid' id="uid" />
<div id='afterpass'></div>
<input type="button" value="Submit" onclick='subVal()'>
</form>

答案 1 :(得分:0)

function subVal()
{
    if (document.forms['loginform'].name.value == '' || document.forms['loginform'].uid.value == '')
    {
    if (document.forms['loginform'].uid.value == '')
    {
        document.getElementById('afterpass').innerHTML = 'FORGOT PASSWORD';
        return false;
    }
    if (document.forms['loginform'].name.value == '')
    {
        document.getElementById('aftername').innerHTML = 'FORGOT USERNAME';
        return false;
    }
    }
    if (document.forms['loginform'].name.value != '' && document.forms['loginform'].uid.value != '')
    {
        document.forms['loginform'].submit();
    }
}