JQuery custom validation: phone number starting with 6

I have a form in which you must enter your phone number and other fields.

I validate the form using jQuery Validate.

To check the phone number, follow these steps:

rules: {
    phone: {
    required: true,
        minlength: 9,
        number:true
    },..

But I also need to check that the phone starts at 6.

How can i do this?

+3
source share
3 answers

You can add a custom validator

jQuery.validator.addMethod("phoneStartingWith6", function(phone_number, element) {
    phone_number = phone_number.replace(/\s+/g, ""); 
    return this.optional(element) || phone_number.match(/^6\d{8,}$/);
}, "Phone number should start with 6");

and use it as follows:

rules: {
    phone: {
        required: true,
        minlength: 9,
        phoneEnding6: true
    },..

You need to edit the regex inside phone_number.matchto suit your requirements.

+7
source

I think you need to add a custom validator.

$.validator.addMethod("phoneNumber", function(uid, element) {
    return (this.optional(element) || uid.match(phone number regex));
}
+2

You can also try the simple Javascript function

"Hello World!".startsWith("He"); //true

Note. This comment / code is for those not using jquery validation.

0
source

Source: https://habr.com/ru/post/1781241/


All Articles