2

Everything is working fine except regular expression i have tried every solution but every time else block executes even when input is valid.

I want To use regExp to validate valid Phone Number

var inputValidation = function () {
this.validation = function (para1) {
    var input = $(document).find('[data-input-validation = ' + para1 + ']');
    input.each(function () {
        $(this).keyup(function(){
            var value = $(this).val();
            var validate = new inputValidation();
            validate.validater('phoneNumber',value);

        });
    });
};

this.validater = function(param1,param2) {
    switch (param1) {
        case 'phoneNumber':
            var mobileNumber = new RegExp('/[0-9-()+]{3,20}/');
            if(mobileNumber.test(param2)){
                alert('valid');
            }
            else {
                alert('false');
            }
            break;
        }
    }
};

var validate = new inputValidation();
validate.validation('search');
1

2 Answers 2

3

You are mixing both the string regex notation and the literal regex notation. Choose only one of:

new RegExp('ab+c');
new RegExp(/ab+c/);

in your case maybe something like this instead:

var mobileNumber = new RegExp(/[0-9-()+]{3,20}/);
Sign up to request clarification or add additional context in comments.

8 Comments

can you please edit my code that will help me better
one more thing when i input special character with number it says valid. so can u help me out please
did you escape the dash? \- (i agree with Michael on this one, you should either escape dashes inside char classes, or put it first or last)
yes i did here it is RegExp(/[0-9\-()+]{3,20}/); but same i result (false as out put):p
It looks like the second '-' in the character class [] was actually accepted as literal and only the first occurence seems to be have been taken as a range operator. Don't know whether this is some peculiarity of the browser, but I would not rely on it to work everywhere.
|
1

The dash in the expression needs to be escaped. Instead of:

/[0-9-()+]{3,20}/

do:

/[0-9\-()+]{3,20}/.

As you have it, it's trying to do a range of characters from '9' to '(' which it can't understand.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.