mac3201
mac3201

Reputation: 85

Alert user if input contains consecutive digits or characters

I have the following Javascript:

else if(serialNumber == (/([0-9a-zA-Z\_\\])\1{3,}/)){
            alert('Serial Number cannot have a single digit or character repeat more than 3 times consecutively.');

I ran the regular expression through http://regex101.com/r/dH3gQ0 and it is running like it should. I am not sure what I am missing in the code. What is happening is nothing. I put in a serial number with more than 3 consecutive numbers and the alert does not appear.

Upvotes: 0

Views: 928

Answers (4)

user3071008
user3071008

Reputation:

You are using the == operator, this checks if serialNumber is the same object as the regex
/([0-9a-zA-Z\_\\])\1{3,}/, which is always false, what you instead should do is use RegExp.prototype.test().

else if ( /([0-9a-zA-Z\_\\])\1{3,}/.test(serialNumber) ) {
            alert('Serial Number cannot have a single digit or character repeat more than 3 times consecutively.');

Upvotes: 0

erosman
erosman

Reputation: 7721

Here is an example ...

If the allowed characters are [A-Za-z0-9_] then you can use \w

// true if 4 consecutive characters are entered    
if( /(\w)\1{3}/.test(serialNumber)){ 
  // your code/alert
}

If the allowed characters include additional backslash then

// true if 4 consecutive characters are entered    
if( /([\w\\])\1{3}/.test(serialNumber)){ 
  // your code/alert
}

Finally, above are case-sensitive so 'aaAAaa' would not result in an alert. If you want a case-insensitive version then:

// true if 4 consecutive characters are entered    
if( /([\w\\])\1{3}/i.test(serialNumber)){ 
  // your code/alert
}

Good luck :)

Upvotes: 0

André Teixeira
André Teixeira

Reputation: 2562

You should test it like:

var serialNumber ='TESTSERIAL9';
var reg= /([0-9a-zA-Z\_\\])\1{3,}/;
console.log(reg.test(serialNumber));

Regards

Upvotes: 0

tenub
tenub

Reputation: 3446

You need to actually test the expression to the string like so:

if(serialNumber.match(/([0-9a-zA-Z\_\\])\1{3,}/) !== null)

or more semantically correct:

if(/([0-9a-zA-Z\_\\])\1{3,}/.test(serialNumber))

Upvotes: 1

Related Questions