如果字段在jquery validate中保留空白或默认值,如何显示错误消息

时间:2013-07-06 09:00:54

标签: jquery validation jquery-validate

如果任何字段在jquery validate中保留空白或默认值,我想显示错误消息。当字段留空时,我的以下代码有效。但是如果我将字段保留为默认值,它就不起作用。拜托,任何人都可以帮我解决这个问题。谢谢

<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="UTF-8">
<title>jQuery Validation Plugin</title>
<script type="text/javascript" src="jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="validation.js"></script>
<script type="text/javascript">
$(document).ready(function () {

    $('#myform').validate({
        rules: {
            name: {
    required: function() {return ($("#name").val()== "Name" || $("#name").val()== "");}
            },
            password: {
                required: function() {return ($("#password").val()== "Password" || $("#password").val()== "");}
            }
        },
        messages: {
            name: {
                required: "Name required"
                            },
            password: {
                required: "Password required"
            }
        }

    });

});
</script>
<style type="text/css">
#myform input.error {
border:1px solid red;
}
</style>
</head>
<body>
<form id="myform" method="post" action="#">
    <input type="text" name="name" id="name" value="Name"/>
    <br/>
    <input type="text" name="password" value="Password"  id="password"/>
    <br/>
    <input type="submit" />
</form>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

您通常应该使用占位符HTML5属性:

<form id="myform" method="post" action="#">
    <input type="text" name="name" id="name" placeholder="Name"/>
    <br/>
    <input type="text" name="password" placeholder="Password"  id="password"/>
    <br/>
    <input type="submit" />
</form>

对于不支持此属性的旧浏览器,请使用polyfill作为此属:https://github.com/mathiasbynens/jquery-placeholder

答案 1 :(得分:0)

你可以试试以下......

$(document).ready(function(){

$('#myform').validate({
    rules:
    {
        name: { required: true },
        password: { required: true }

    }
});

});