我正在尝试为表单设置一些自定义规则并使用前面提到的Jquery Validation Plugin,但我真的不知道修改给出的示例来完成我想要做的事情。
我想要做的是设置一个条件,在“country”输入中选择的选项会更改验证电话号码文本输入所需的位数。在我的例子中,我尝试设置一些内容,如果所选国家是加拿大,则电话输入所需的数字位数为10,否则所需数量为12。
在我注意到addMethod的文档之前,我尝试在一个小样本表单中插入自定义条件语句,如此...
<form id='myform'>
<select name="country" placeholder="country" id="country">
<option value="">Select a country</option>
<option value="Canada">Canada</option>
<option value="Elsewhere">Elsewhere</option>
</select>
<input type="text" name="phonenumber" id="phonenumber" placeholder="Phone Number">
<input type="submit" name="submit" id="submit">
</form>
<script>
$phoneDigits = 10;
$('#country').change(function(){
if($('#country').val() == 'Elsewhere'){
$phoneDigits = 12;
}else{
$phoneDigits = 10;
}
});
$("#myform").validate(
{
rules:
{
fullname:
{
required: true
},
email:
{
required: true,
email: true
},
country:
{
required: true,
},
phonenumber:
{
required: true,
minlength: $phoneDigits
}
},
messages:
{
fullname:
{
required: "Please enter your name"
},
email:
{
required: "Please enter your email address."
},
country:
{
required: "Please select a country."
},
phonenumber:
{
required: "Please enter your phone number."
}
}
});
</script>
这几乎可以工作,但$ phoneDigits变量在validate函数中不会改变。我接受任何可以改善这种逻辑的想法,以便它起作用,但除此之外,任何人都可以帮助我找到我的能力revise one of these examples into doing what I want instead?
答案 0 :(得分:1)
您可以使用$('$input').rules('add', options)
作为插件documentation
这是你的代码..
<form id='myform'>
<select name="country" placeholder="country" id="country">
<option value="">Select a country</option>
<option value="Canada">Canada</option>
<option value="Elsewhere">Elsewhere</option>
</select>
<input type="text" name="phonenumber" id="phonenumber" placeholder="Phone Number">
<input type="submit" name="submit" id="submit">
</form>
$("#myform").validate(
{
rules:
{
fullname:
{
required: true
},
email:
{
required: true,
email: true
},
country:
{
required: true,
},
phonenumber:
{
required: true
}
},
messages:
{
fullname:
{
required: "Please enter your name"
},
email:
{
required: "Please enter your email address."
},
country:
{
required: "Please select a country."
},
phonenumber:
{
required: "Please enter your phone number."
}
}
});
var obj = {minlength: 0,
messages: {
minlength: '')
}
};
$('#country').change(function(){
if($('#country').val() == 'Elsewhere'){
obj.minlength = 12;
obj.messages.minlength = 'Required at least 12 digit';
}else{
obj.minlength = 10;
obj.messages.minlength = 'Required at least 10 digit';
}
// And lastly...
$( "#phonenumber" ).rules( "add", obj);
});