jQuery Validate如果没有值,则忽略自定义验证规则 [英] jQuery Validate ignore custom validation rule if no value
问题描述
我正在使用jQuery Validator插件.一切工作正常,我想作最后的调整.我只是没有运气找到正确的组合.
I am using the jQuery Validator plugin. Everything is working perfectly, I would like to make a final tweak. I'm just not having luck finding the correct combination.
我有一个称为"phone"的文本输入.如果未输入任何值,则我想忽略所有规则-不理会输入内容.当前,如果我集中精力,然后集中精力(不输入值),则输入将得到验证,并且我的UI将使用有效的标记进行更新.可以,但是理想情况下,我想不考虑输入内容.仅在有值的情况下验证.我必须在自定义方法中返回true/false,否则始终无效.
I have a text input called "phone". If no value has been entered, I would like to ignore all rules - leaving the input alone. Currently, if I focus in, then focus out (without entering a value) the input is validated and my UI is updated with my valid markup. Which, is OK, but ideally, I'l like to leave the input alone. Only validate if there is a value. I have to return true/false in my custom method otherwise it's always invalid.
不确定我能做什么.谢谢您的时间!
Not sure what I can do. Thank you for your time!
HTML :
<input id="phone" name="phone" tabindex="7" placeholder="(###) ###-####" type="text" value="">
这是我的输入规则:
JavaScript
....
'phone': {
'required': {
'depends': function(element) {
return $('#textOptIn').is(':checked');
}
},
'hasValidPhoneNumber': true
},
....
这是我的自定义方法:
JavaScript
$.validator.addMethod('hasValidPhoneNumber', function(value, element) {
if (value === '' || value.replace(/ /g, '') === '(###)###-####')
{
return true;
}
else
{
return isValidPhoneNumber(value); //
}
}, messages.invalidPhoneNumber);
function isValidPhoneNumber(phoneNumber) {
var pattern = /^[(]{0,1}[0-9]{3}[)]{0,1}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1}[0-9]{4}$/;
return pattern.test(phoneNumber);
}
推荐答案
使用this.optional(element)
代替检查其是否为空.它只是使该字段成为可选字段.换句话说,如果您将其保留为空白,则根本不会对其进行评估.
Instead of checking if it's empty, use this.optional(element)
. It simply makes the field optional. In other words, if you leave it blank, it's not going to be evaluated at all.
$.validator.addMethod('hasValidPhoneNumber', function(value, element) {
if (this.optional(element) || value.replace(/ /g, '') === '(###)###-####') {
return true;
}
else {
return isValidPhoneNumber(value); //
}
}, messages.invalidPhoneNumber);
这篇关于jQuery Validate如果没有值,则忽略自定义验证规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!