spujaname
spujaname

Reputation: 33

Invalid regular expression error in RegExp

I am using RegExp for the validation of US phone number. For ReEmailFormat6 i am getting below error: enter image description here

but other expression running fine. I am not sure why I am this issue . Please find my code below:

    var reEmailFormat2 = new RegExp("(.)\1{7,}"); //match if phone number has same number repeated 8 or more times
var reEmailFormat3 = new RegExp("^0{1}[\d]{9}$"); //match if phone number has leading 0 with 9 digits after the 0
var reEmailFormat4 = new RegExp("1{1}[\d]{9}$"); //match if phone number has leading 1 with 9 digits after the 1
var reEmailFormat5 = new RegExp("/^[+]?(1\-|1\s|1|\d{3}\-|\d{3}\s|)?((\(\d{3}\))|\d{3})(\-|\s)?(\d{3})(\-|\s)?(\d{4})$/g");
var reEmailFormat6 = new RegExp("^(?:\+?1[-. ]?)?\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$");
debugger;

if (controlToValidate[0].value == "" || controlToValidate[0].value == controlToValidate.attr("placeholder")) {
    args.IsValid = false;
    controlToValidate.addClass("site-validation-field");
}
else if (controlToValidate[0].value == "") {
    args.IsValid = false;
    controlToValidate.addClass("site-validation-field");
}
else if ((reEmailFormat6.test(controlToValidate[0].value))) {
    debugger;
    args.IsValid = false;
    controlToValidate.addClass("site-validation-field");
}

Upvotes: 0

Views: 1716

Answers (1)

Pointy
Pointy

Reputation: 413702

Rewrite all of your regular expressions with regular expression literal syntax:

var reEmailFormat2 = /(.)\1{7,}/; //match if phone number has same number repeated 8 or more times
var reEmailFormat3 = /^0{1}[\d]{9}$/; //match if phone number has leading 0 with 9 digits after the 0
var reEmailFormat4 = /1{1}[\d]{9}$/; //match if phone number has leading 1 with 9 digits after the 1
var reEmailFormat5 = /^[+]?(1\-|1\s|1|\d{3}\-|\d{3}\s|)?((\(\d{3}\))|\d{3})(\-|\s)?(\d{3})(\-|\s)?(\d{4})$/g;
var reEmailFormat6 = /^(?:\+?1[-. ]?)?\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;

When you form your regular expressions as strings to pass to the RegExp() constructor, you have to take into account the fact that the string syntax in JavaScript also uses the backslash character as a meta-character. Thus if you don't double your backslash characters in the source string, the process of parsing it as a string will remove them.

Upvotes: 1

Related Questions