我已经尝试使用JQuery多次使用自定义消息来验证错误,但是我仍然对自己在哪里出错感到困惑。我曾尝试使用普通的验证消息,但是当我尝试使用自定义消息时,它显示了我一个错误。
下面是到目前为止我尝试过的示例代码,执行起来并不成功。
<form id="myform">
<tr>
<td class="alpha">username</td>
<td>
<input type="username" type="text" value="">
</td>
</tr>
<br/>
<tr>
<td class="alpha">postcode</td>
<td>
<input type="postcode" type="text" value="">
</td>
</tr>
<input type="submit" />
</form>
$.validator.setDefaults({
submitHandler: function() {
alert("submitted!");
}
});
$document.ready(function() {
$("#myform").validate({
rules: {
password: "required",
postcode: {
required: true,
minlength: 3
}
},
messages: {
username: {
required: "*Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
postcode: {
required: "Field PostCode is required",
minlength: "Field PostCode must contain at least 3 characters"
}
}
});
});
答案 0 :(得分:1)
按照书面规定,您的代码也无法使用默认消息。
请阅读我在代码中的评论...
rules: {
password: "required", // <- input with name="password" (where is "password"?)
postcode: { // <- input with name="postcode"
required: true,
minlength: 3
}
},
messages: {
username: { // <- input with name="username"
required: "*Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
postcode: { // <- input with name="postcode"
required: "Field PostCode is required",
minlength: "Field PostCode must contain at least 3 characters"
}
}
rules
和messages
对象的参数由输入元素的name
属性键入。您的输入元素不包含任何name
属性。插件要求所有表单输入都包含唯一的name
,如果没有这些插件,插件将无法使用。
您的type
属性值无效。没有type="username"
和type="postcode"
这样的东西;并且您错误地在每个输入type
<input type="username" type="text" value="">
属性
对于您而言,您甚至没有尝试为username
字段定义任何规则。在password
对象中只有postcode
和rules
。
修复无效的HTML标记和JavaScript ...
type
属性。name
属性。name
和rules
对象中的messages
属性。