Link to home
Start Free TrialLog in
Avatar of egoselfaxis
egoselfaxis

asked on

Need 2 different Regex functions

I need 2 different regex functions to apply to 2 different fields in a web form that I'm developing:

1) Phone number - need regex that only allows numbers, parentheses and hyphens, etc.
2) Quantity - need regex that requires that the value be numeric, and the number value should be at least 25 or greater.

Please advise.

Thanks!
- Yvan
ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
While the regex might work for you, you should also take a look at the validation plugins that are out there for phone numbers and restricting fields based on criteria such as only allowing numbers.

This is the standard for working with validating web forms (uses jQuery) http://jqueryvalidation.org/

As for the number issue, all you have to do is try to cast the value as a Number (on the keydown event) and check for isNaN:

<input type="text" value="" onkeydown="checkNumber(event)" />

function checkNumber(e) {
  if (isNaN(String.fromCharCode(e.keyCode))) {
    e.preventDefault();
  }
}

Open in new window


Just remember that any "validation" you do on the client must be repeated on the server as it is easy to bypass for someone that wants to (including any regex you use).
Avatar of egoselfaxis
egoselfaxis

ASKER

Thanks Ozo -- those worked great for me!  I just updated the phone number Regex so that it also allows for spaces:

<form method="post" action="">
Phone Number: <input required="required" type="text" name="phone" pattern="^[\d()\- ]*$" title="You must enter a valid Phone Number">
<br /><br />
Minimum Quantity: <input required="required" type="text" name="quantity" pattern="2[5-9]|[3-9]\d|[1-9]\d{2,}" title="You must specify a quantity of 25 or greater"><br /><br />
<input type="submit">
</form>

Open in new window