Home > front end >  I need to create a regular expression to not allow entering the first digit 9
I need to create a regular expression to not allow entering the first digit 9

Time:04-30

enter image description here

I need help, I'm new to regular expressions.

I need to create a regular expression to not allow entering the first digit 9 and that does not have 000 in the middle

I want to make a pattern that does not allow the first number to be 9 and does not have 3 zeros in position 4,6 000

and vice versa.

That is, the correct SSN number would be: 123456000

but SSN would be wrong if you type: 923456789

or if you type: 123000789

or if you type: 923000789

etc.

I was able to progress to here:

  function ValidSSN()
{
    const indiaRegex = /^[\9] 000\d{3,6}$/gm;
    const inputText = document.getElementById("ssn_code").value;
    if(inputText.match(indiaRegex)) {
        alert("Not a valid SSN");    
         document.getElementById("ssn_code").value = "";
    } else {
        alert("Valid SSN");      
    }
}
  <input type='number' id="ssn_code" maxlength="9" name='ssn_code' onblur="ValidSSN()"/>

CodePudding user response:

Assuming that zeroes are allow in positions 4,5,and 6 as long as it isn't all three, you can use negative lookahead:

/^(?!9)(\d)\d\d(?!000)(\d\d\d)\d\d\d/$

let pattern = /^(?!9)(\d)\d\d(?!000)(\d\d\d)\d\d\d$/
let numbers = ["123456000", "346467784", "923456789", "123000789", "923000789"]

numbers.forEach( n => {
  console.log(n, pattern.test(n))
})
//extra test
console.log("123050789", pattern.test("123050789"))

CodePudding user response:

Try making regex that match your condition, instead of making one that doesn't. Because making one that matches your condition is easy, all you have to do is know the basics and proceed accordingly.

If your condition is that the input fails if there are three consecutive zeros from position 4 to 6(eg: 123000789) then use this: ^[0-8]\d{2}[1-9]{3}\d{3}$
Test here:https://regex101.com/r/q4nN5Y/1

This matches a SSN only if:

  • it does not start with 9
  • and does not have three consecutive 0 in positions from 4 to 6

If your condition is to fails if there is a zero in any of the position from 4 to 6(eg: 123406789, 123450089, 123050789) then use this: ^[0-8]\d{2}(?!0{3})\d{6}$ Test here: https://regex101.com/r/q4nN5Y/2

This matches a SSN only if:

  • it does not start with 9
  • and does not have a zero in any of the position from 4 to 6

Your regex:

/^[\9] 000\d{3,6}$/gm

[\9]    '\' is used to escape a char, so this says match literal '9' one or more time
000     match three zeroes
\d{3,6} match 3 to 6 digits

Clearly this is not what you want.
Use tools like regex101.com or regexer.com while making regex. They are really helpful.

  • Related