如何创建一个简单的,自定义规则使用jQuery验证插件(使用addMethod),不使用正则表达式?
例如,哪个函数创建的规则只在至少选中一组复选框中的一个时才生效?
如何创建一个简单的,自定义规则使用jQuery验证插件(使用addMethod),不使用正则表达式?
例如,哪个函数创建的规则只在至少选中一组复选框中的一个时才生效?
当前回答
你可以这样创建一个简单的规则:
jQuery.validator.addMethod("greaterThanZero", function(value, element) {
return this.optional(element) || (parseFloat(value) > 0);
}, "* Amount must be greater than zero");
然后像这样应用:
$('validatorElement').validate({
rules : {
amount : { greaterThanZero : true }
}
});
只需更改'addMethod'的内容来验证您的复选框。
其他回答
你可以这样创建一个简单的规则:
jQuery.validator.addMethod("greaterThanZero", function(value, element) {
return this.optional(element) || (parseFloat(value) > 0);
}, "* Amount must be greater than zero");
然后像这样应用:
$('validatorElement').validate({
rules : {
amount : { greaterThanZero : true }
}
});
只需更改'addMethod'的内容来验证您的复选框。
谢谢,成功了!
这是最终的代码:
$.validator.addMethod("greaterThanZero", function(value, element) {
var the_list_array = $("#some_form .super_item:checked");
return the_list_array.length > 0;
}, "* Please check at least one check box");
步骤1包含cdn like
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
2 .编码
$(document).ready(function(){
$("#submit").click(function () {
$('#myform').validate({ // initialize the plugin
rules: {
id: {
required: true,
email: true
},
password: {
required: true,
minlength: 1
}
},
messages: {
id: {
required: "Enter Email Id"
},
password: {
required: "Enter Email Password"
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
}):
});
$(document).ready(function(){
var response;
$.validator.addMethod(
"uniqueUserName",
function(value, element) {
$.ajax({
type: "POST",
url: "http://"+location.host+"/checkUser.php",
data: "checkUsername="+value,
dataType:"html",
success: function(msg)
{
//If username exists, set response to true
response = ( msg == 'true' ) ? true : false;
}
});
return response;
},
"Username is Already Taken"
);
$("#regFormPart1").validate({
username: {
required: true,
minlength: 8,
uniqueUserName: true
},
messages: {
username: {
required: "Username is required",
minlength: "Username must be at least 8 characters",
uniqueUserName: "This Username is taken already"
}
}
});
});
你可以像这样添加一个自定义规则:
$.validator.addMethod(
'booleanRequired',
function (value, element, requiredValue) {
return value === requiredValue;
},
'Please check your input.'
);
并将其添加为如下规则:
PhoneToggle: {
booleanRequired: 'on'
}