[英]jQuery Validate Plugin - How to create a simple custom rule?
How do you create a simple, custom rule using the jQuery Validate plugin (using addMethod
) that doesn't use a regex?如何使用不使用正则表达式的 jQuery 验证插件(使用addMethod
)创建简单的自定义规则?
For example, what function would create a rule that validates only if at least one of a group of checkboxes is checked?例如,function 会创建一个规则,该规则仅在选中一组复选框中的至少一个时才进行验证?
You can create a simple rule by doing something like this:您可以通过执行以下操作来创建一个简单的规则:
jQuery.validator.addMethod("greaterThanZero", function(value, element) {
return this.optional(element) || (parseFloat(value) > 0);
}, "* Amount must be greater than zero");
And then applying this like so:然后像这样应用它:
$('validatorElement').validate({
rules : {
amount : { greaterThanZero : true }
}
});
Just change the contents of the 'addMethod' to validate your checkboxes.只需更改“addMethod”的内容即可验证您的复选框。
$(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"
}
}
});
});
// add a method. calls one built-in method, too.
jQuery.validator.addMethod("optdate", function(value, element) {
return jQuery.validator.methods['date'].call(
this,value,element
)||value==("0000/00/00");
}, "Please enter a valid date."
);
// connect it to a css class
jQuery.validator.addClassRules({
optdate : { optdate : true }
});
You are able to create a custom rule and attach it to an element using the data
attribute using the syntax data-rule-rulename="true";
您可以使用语法data-rule-rulename="true";
创建自定义规则并将其附加到使用data
属性的元素;
So to check if at least one of a group of checkboxes is checked:因此,要检查是否至少选中了一组复选框中的一个:
data-rule-oneormorechecked数据规则一或更多检查
<input type="checkbox" name="colours[]" value="red" data-rule-oneormorechecked="true" />
addMethod添加方法
$.validator.addMethod("oneormorechecked", function(value, element) {
return $('input[name="' + element.name + '"]:checked').length > 0;
}, "Atleast 1 must be selected");
And you can also override the message of a rule (ie: Atleast 1 must be selected) by using the syntax data-msg-rulename="my new message"
.您还可以使用语法data-msg-rulename="my new message"
覆盖规则的消息(即:必须选择至少 1 个) 。
NOTE笔记
If you use the data-rule-rulename
method then you will need to make sure the rule name is all lowercase.如果您使用data-rule-rulename
方法,则需要确保规则名称全部小写。 This is because the jQuery validation function dataRules
applies .toLowerCase()
to compare and the HTML5 spec does not allow uppercase.这是因为 jQuery 验证函数dataRules
应用.toLowerCase()
进行比较,而HTML5规范不允许大写。
Working Example工作示例
$.validator.addMethod("oneormorechecked", function(value, element) { return $('input[name="' + element.name + '"]:checked').length > 0; }, "Atleast 1 must be selected"); $('.validate').validate();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js"></script> <form class="validate"> red<input type="checkbox" name="colours[]" value="red" data-rule-oneormorechecked="true" data-msg-oneormorechecked="Check one or more!" /><br/> blue<input type="checkbox" name="colours[]" value="blue" /><br/> green<input type="checkbox" name="colours[]" value="green" /><br/> <input type="submit" value="submit"/> </form>
Thanks, it worked!谢谢,它奏效了!
Here's the final code:这是最终的代码:
$.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");
You can add a custom rule like this:您可以像这样添加自定义规则:
$.validator.addMethod(
'booleanRequired',
function (value, element, requiredValue) {
return value === requiredValue;
},
'Please check your input.'
);
And add it as a rule like this:并将其添加为这样的规则:
PhoneToggle: {
booleanRequired: 'on'
}
For this case: user signup form, user must choose a username that is not taken.对于这种情况:用户注册表单,用户必须选择未使用的用户名。
This means we have to create a customized validation rule, which will send async http request with remote server.这意味着我们必须创建一个自定义的验证规则,它将向远程服务器发送异步 http 请求。
<input name="user_name" type="text" >
$("form").validate({
rules: {
'user_name': {
// here jquery validate will start a GET request, to
// /interface/users/is_username_valid?user_name=<input_value>
// the response should be "raw text", with content "true" or "false" only
remote: '/interface/users/is_username_valid'
},
},
class Interface::UsersController < ActionController::Base
def is_username_valid
render :text => !User.exists?(:user_name => params[:user_name])
end
end
Step 1 Included the cdn like第 1 步包括类似的 CDN
<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>
Step 2 Code Like第 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
}
});
}):
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.