我正在尝试使用jQueryValidation插件进行表单验证。我已为该字段定义了自定义消息,并且我还有自定义方法验证。
它看起来总是显示自定义消息并忽略自定义验证错误消息。
代码
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.js"></script>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.js"></script>
<script type='text/javascript'>//<![CDATA[
$(document).ready(function() {
$.validator.addMethod("strlength", function (elemVal, element) {
if(elemVal.length > 5) {
return true;
} else {
return false;
}
}, 'Enter atleast 6 characters');
$("#sampleForm").validate({
messages: {
"firstname": "Please enter the firstname"
},
rules: {
"firstname": {
required: true,
strlength: true
}
}
});
});
//]]>
</script>
</head>
<body>
<form name="sampleForm" id="sampleForm" method="post" action="">
<p>
<label>Enter Firstname</label>
<input type="text" name="firstname" id="firstname" value=""/>
</p>
<p>
<input class="submit" type="submit" value="Submit">
</p>
</form>
</body>
</html>
答案 0 :(得分:1)
您需要为特定messages
定义validator
。将firstName
定义为object
,它将接受密钥作为validation
参数。
试试这个:
$(document).ready(function() {
$.validator.addMethod("strlength", function(elemVal, element) {
if (elemVal.length > 5) {
return true;
} else {
return false;
}
}, 'Enter atleast 6 characters');
console.info('testing');
$("#sampleForm").validate({
messages: {
"firstname": {
required: "Please enter the firstname"
}
},
rules: {
"firstname": {
required: true,
strlength: true
}
}
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.js"></script>
<form name="sampleForm" id="sampleForm" method="post" action="">
<p>
<label>Enter Firstname</label>
<input type="text" name="firstname" id="firstname" value="" />
</p>
<p>
<input class="submit" type="submit" value="Submit">
</p>
</form>
&#13;