0

如果 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>
4

2 回答 2

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

于 2013-07-06T09:07:39.203 回答
0

你可以试试下面的..

$(文档).ready(函数() {

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

    }
});

});

于 2013-07-08T12:55:19.760 回答