singular
singular

Reputation: 55

Validate user text

I am trying to validate a text field so that they must enter a seven character value. The first character must be alphanumeric and the next six must be numeric. I have no problem with validating the length, but not sure how to achieve the rest. Any help would be appreciated.

Upvotes: 0

Views: 81

Answers (3)

Ivan
Ivan

Reputation: 3655

Regular expressions...

if (myString.match(/^\w\d{6}$/))
  alert('Valid');

^ start of a string

\w any alphanumerical character + underscore (you can change it to [a-zA-Z0-9] for true alphanumeric)

\d any digit

{6} exactly 6 of them

$ end of a string

Upvotes: 1

Magic Lasso
Magic Lasso

Reputation: 1542

var regex = new RegExp('/^[a-zA-z]{1}[0-9]{6}$/') ;

Did you want to allow any spaces or special characters?

Whoops need to add in what Ivan said as I didnt realize you were unfamiliar with regular expressions.

Use

var regex = new RegExp('/^[a-zA-Z0-9]{1}[0-9]{6}$/') ;

if(myString.match(regex)){ "YOUR CODE" ; }

Thanks Ivan missed that alpha part.

Upvotes: 3

Dennis Traub
Dennis Traub

Reputation: 51654

Have a look at this: Regular Expressions with JavaScript

Upvotes: 1

Related Questions