This article mainly introduces how to use jquery. the validate custom method implements the logic verification of the & quot; mobile phone number or fixed phone number & quot;, which solves the verification problem that at least one mobile phone number or fixed phone number is entered, I would like to share with you the following requirement during recent project development: "Enter at least one mobile phone number or fixed phone number", as shown in:
The jquery. validate. js verification component used by the project. Currently, the component does not support the "or" logic verification, So you define
jQuery.validator.addMethod ("phone", function (value, element) {
var mobile = $ ("# mobile"). val (); // Mobile number
var telephone = $ ("# telephone"). val (); // Landline
var mobileRule = / ^ (13 [0-9] | 14 [5 | 7] | 15 [0 | 1 | 2 | 3 | 5 | 6 | 7 | 8 | 9] | 18 [0-9] | 170) \ d {8} $ /;
var telephoneRule = / ^ \ d {3,4}-? \ d {7,9} $ /;
// left blank
if (isEmpty (mobile) && isEmpty (telephone)) {
// Custom error prompt
$ ("# receivingMobile_tip"). addClass ("errorHint"). text ("Please fill in the landline or mobile phone number");
return false;
}
var mobilePass = false;
var telephonePass = false;
// The mobile phone is filled, the fixed phone is not filled
if (! isEmpty (mobile) && isEmpty (telephone)) {
if (! mobileRule.test (mobile)) {
// Custom error prompt
$ ("# receivingMobilePhone_tip"). removeClass ("successHint"). addClass ("errorHint"). text ("Wrong phone number format");
return false;
} else {
mobilePass = true;
}
}
// Mobile phone is not filled, fixed phone is filled
if (isEmpty (mobile) &&! isEmpty (telephone)) {
if (! telephoneRule.test (telephone)) {
// Custom error prompt
$ ("# receivingTelephone_tip"). removeClass ("successHint"). addClass ("errorHint"). text ("Wrong fixed telephone format");
return false;
} else {
telephonePass = true;
}
}
if (mobilePass || telephonePass) {
// Customize success prompt
$ ("# receivingTelephone_tip"). removeClass ("errorHint"). addClass ("successHint"). text ('');
return true;
} else {
return false;
}
}, "ignore");
Supplement the isEmpty function:
// Empty string judgment
function isEmpty (v, allowBlank) {
return v === null || v === undefined || (! allowBlank? v === "": false);
}
Handle validate errorPlacement:
errorPlacement: function (error, element) {
// Ignore the error message of the custom method
if (error.text () == "ignore") {
return;
}
}
Used in rules
rules: {
telephone: {
phone: []
},
mobile: {
phone: []
}
}