jQuery验证插件如何创建一个简单的自定义规则?

如何创建一个简单的,自定义规则使用jQuery验证插件(使用addMethod),不使用正则表达式?

例如,哪个函数创建的规则只在至少选中一组复选框中的一个时才生效?

355389 次浏览

你可以这样创建一个简单的规则:

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");
$(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 }
});

自定义规则和数据属性

你可以创建一个自定义规则,并使用语法data-rule-rulename="true";使用data属性将其附加到元素上

因此,要检查一组复选框中是否至少有一个被选中:

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");

你也可以通过使用语法data-msg-rulename="my new message"来覆盖规则(即:必须选择至少1个)的消息。

请注意

如果你使用data-rule-rulename方法,那么你需要确保规则名都是小写的。这是因为jQuery验证函数dataRules应用.toLowerCase()进行比较,而HTML5 <强> < /强>规范不允许大写。

工作示例

.
$.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>

你可以像这样添加一个自定义规则:

$.validator.addMethod(
'booleanRequired',
function (value, element, requiredValue) {
return value === requiredValue;
},
'Please check your input.'
);

并将其添加为如下规则:

PhoneToggle: {
booleanRequired: 'on'
}

对于这种情况:用户注册表单,用户必须选择一个未采取的用户名。

这意味着我们必须创建一个自定义的验证规则,该规则将向远程服务器发送异步http请求。

  1. 在你的html中创建一个input元素:
<input name="user_name" type="text" >
  1. 声明表单验证规则:
  $("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'
},
},
  1. 远程代码应该像这样:
class Interface::UsersController < ActionController::Base
def is_username_valid
render :text => !User.exists?(:user_name => params[:user_name])
end
end

步骤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 Code Like

  $(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
}
});
}):
});