javascript如何在不使用警报的情况下创建验证错误消息

时间:2012-12-03 18:58:53

标签: javascript validation

我希望在用户名字段下显示一个简单的表单验证错误消息。

我似乎无法弄明白。

<form name ="myform" onsubmit="validation()">
     Username: <input type ="text" name="username" /><br />              
     <input type ="submit" value="submit" />
      <div id ="errors">
      </div>
</form>

这是我的验证脚本:

function validation(){ 
    if(document.myform.username.value == ""){   //checking if the form is empty
         document.getElementById('errors').innerHTML="*Please enter a username*";
                //displaying a message if the form is empty
    }

3 个答案:

答案 0 :(得分:12)

您需要停止提交错误:

HTML

<form name ="myform" onsubmit="return validation();"> 

JS

if (document.myform.username.value == "") {
     document.getElementById('errors').innerHTML="*Please enter a username*";
     return false;
}

答案 1 :(得分:2)

的JavaScript

<script language="javascript">
        var flag=0;
        function username()
        {
            user=loginform.username.value;
            if(user=="")
            {
                document.getElementById("error0").innerHTML="Enter UserID";
                flag=1;
            }
        }   
        function password()
        {
            pass=loginform.password.value;
            if(pass=="")
            {
                document.getElementById("error1").innerHTML="Enter password";   
                flag=1;
            }
        }

        function check(form)
        {
            flag=0;
            username();
            password();
            if(flag==1)
                return false;
            else
                return true;
        }

    </script>

HTML

<form name="loginform" action="Login" method="post" class="form-signin" onSubmit="return check(this)">



                    <div id="error0"></div>
                    <input type="text" id="inputEmail" name="username" placeholder="UserID" onBlur="username()">
               controls">
                    <div id="error1"></div>
                    <input type="password" id="inputPassword" name="password" placeholder="Password" onBlur="password()" onclick="make_blank()">

                    <button type="submit" class="btn">Sign in</button>
                </div>
            </div>
        </form>

答案 2 :(得分:0)

我强烈建议你开始使用jQuery。您的代码如下:

$(function() {
    $('form[name="myform"]').submit(function(e) {
        var username = $('form[name="myform"] input[name="username"]').val();
        if ( username == '') {
            e.preventDefault();
            $('#errors').text('*Please enter a username*');
        }
    });
});