-6

I would like to set up validation regex on one of my text fields. A sample input looks like:

1364-lqap-10926

The validation formula is 4 digits, dash, 4 letters, dash, 5 digits (total length validation = 15).

I have tried with \d{4})-([a-z]*[a-z])-\d{5}, but unwanted values get matched, too.

Could you please suggest how to fix the regex?

Alan Moore
  • 68,531
  • 11
  • 88
  • 149
Datta Sai
  • 11
  • 1
  • 4

3 Answers3

1

RegEx:

/[0-9]{4}-[a-z]{4}-[0-9]{5}/

[0-9]{4}: Matches four numbers \-: Matches - [a-z]{4}: Matches four alphabets from range a to z

Tushar
  • 78,625
  • 15
  • 134
  • 154
1

The regex you are asking is pretty trivial and you should learn regexes by analyzing this one.

The regex following your behaviour is:

'/\d{4}-[a-zA-Z]{4}-\d{5}/'

Explanations:

4 Numeric

\d{4}

means that you want exactly 4 occurences of "\d" which is a number

4 Alpha

As num is not included in alpha, then you'll search for any occurence of letters that are exactly 4:

[a-zA-Z]{4}

5 Numeric

Same as 4 numbers but with a 5 instead of a 4 in the brackets (\d{5})

Answers_Seeker
  • 468
  • 4
  • 11
  • Thank @Tushar /[0-9]{4}-[a-z]{4}-[0-9]{5}/ itz working but last number lmit up tp 6 also taking ,,,why? – Datta Sai Apr 28 '15 at 10:17
1

You need to check for anchors (^ and $ forcing the check at the beginning and end of the string) as well, not just the patterns.

^\d{4}-[a-z]{4}-\d{5}$

Use with i option to ignore letter case.

See demo

Sample code:

var re = /^\d{4}-[a-z]{4}-\d{5}$/i; 
var str = '1234-abcd-12345';
     
if (re.test(str)) {
   alert("found");
}
Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397