[英]how to write if condition in rules tag in jquery
任何机构都可以帮助我在 jquery 规则标签中编写 if 条件。请参阅下面的标签。
$("#submit-btn-id").on("click",function(){
var formValid = getValidator("#userRegistration", {
rules : {
firstname : "required",
lastname: "required",
password:"required",
gender:"required",
email:{
required:true,
email:true
},
phone:"required",
//select:"required",
select:{
required : true,
selectNone: true
},
if(("#selectid option:selected").val() == '3'){
dateOfJoining:"required",
idCardNumber:"required",
}
else if(("#selectid option:selected").val() == '3'){
code:"required",
creditLimit:"required",
depositAmont:"required",
idProofNumber:"required",
identyProof:"required",
"panNumber":{panNumber:true},
}
else if(("#selectid option:selected").val() == '4'){
AgentApicreditLimit:"required",
AgentApidepositAmont:"required",
AgentApinoOfIp:"required",
}
"AgentApipanNumber":{AgentApipanNumber:true}
}
});
从 JQuery 中,您可以添加一个函数来执行您的逻辑作为属性值。
方法 1:添加所有验证属性,根据您的逻辑,有些将具有真值,有些将具有假值。
这是来自jQuery Validation Plugin的示例。
$(".selector").validate({
rules: {
contact: {
required: true,
email: {
//Note here how they placed some logic into the function
depends: function(element) {
return $("#contactform_email:checked")
}
}
}
}
});
要与您的代码相关,您可以执行以下操作:
...
code: function (){
//your logic here.
//DON'T FORGET THE $
return $("#selectid option:selected").val()==3
},
creditLimit: function(){return $("#selectid option:selected").val() == '3'},
...
dateOfJoining: = function ()
{
//your logic goes here
if(("#selectid option:selected").val() == '3')
{
return "required"; //this will be the value of dateOfJoining
}
}
方法二:
正如 Archer 在评论中所建议的那样。 您可以在调用getValidator
之前构建您的getValidator
对象。 此外, getValidator
需要一个对象作为第二个参数。 在何处声明该对象并不重要。 因此,您可以在调用getValidator
之前准备该对象
例子:
$("#submit-btn-id").on("click",function(){
var valObject = {};//this will be the rules object
if(("#selectid option:selected").val() == '3'){
valObject ["dateOfJoining"] = "required" ;//we add attributes based on the logic
valObject ["idCardNumber"] = "required" ;// we add more
attributes
//here add more attributes as if they satisfy the condition.
}
//Add more conditions, more constrain as above to add more required attributes.
var rules = {"rules" : valObject } ; //assign all attributes that you've already defined to the rules object.
//And then call your validation
var formValid = getValidator("#userRegistration", rules );
};
两种方式都可以正常工作。 您只需要为您选择更简单的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.