Home > other >  Validate phone number start with 080, 081, 090, 070, 091
Validate phone number start with 080, 081, 090, 070, 091

Time:09-17

I want to validate the phone number Prefix and the number of digits.

The phone number would be 11 digits long (only numeric). The prefix must start with any of these prefixes: 080, 081, 090, 091, 070, and the max is 11 digits.

I placed a validation code to validate phone number digits using the below code in my javascript and it works fine.

**Phone number 11 digits validation code below;**
} else if (form.usercheck1.value.length<11 || 
   form.usercheck1.value.length>11) { alert("phone number should be 11 digits!");
}

But I need help to validate phone prifix. Any help would be appreciated.

my complete javascript code below;

/* myScript.js */
function check(form) /*function to check userid & password*/ {
  /*the following code checkes whether the entered userid and password are matching*/
  if (form.usercheck1.value == "1234" ||
    form.usercheck1.value == "12345")  {
      alert("An account already exist with this phone number! \nKindly login to proceed.") // displays error message
    } else if (form.usercheck1.value.length < 11 || form.usercheck1.value.length > 11) {
      alert("phone number should be 11 digits!");
    } else {
      window.location.replace('https://www.google.com')
      /*opens the target page while Id & password matches*/
    }
  }
}

CodePudding user response:

You can use this pattern: ^0([89][01]|70)\d{8}$

This checks for prefixes and a total of 11 digits.

Note: you said a maximum of 11 digits but when I read your code it seems you want exactly 11 digits, the above pattern work for exactly 11 digits. if you want to make it to a maximum of 11 digits you can use this: ^0([89][01]|70)\d{0,8}$

<!DOCTYPE html>
<html>
  <body>
  <form>
    <label for="phone_number">Phone number: </label>
    <input type="text" id="phone_number" name="phone_number" pattern="^0([89][01]|70)\d{8}$" title="Maximum length is 11 and Phone number must start with one of 080, 081, 090, 091 or 070 And must be all numeric">
    <input type="submit" value="Submit">
  </form>
  </body>
</html>

CodePudding user response:

Do you really need to use regex for this??

Which of these do you think is easier to understand?

/^0(?:[89][01]|70)/.test(input)
['080', '081', '090', '070', '091'].includes(input.substring(0,3))

Unless the list gets very long, and there's a clear pattern to it, I'd opt for not using a mysterious regex here.

  • Related