简体   繁体   中英

Validate input format using javascript Regex

I am having 3 input boxes in my webform and I want to validate all fields using javascript regex while submitting form.

Format for my fields are as follows:

NNNN.NN.NNNN (i.e. 1234.56.7890) 

NNN.N (i.e. 123.4) 

NNNNNNN-NNN (i.e. 1234567-890)

where N is number or digit only.

Any help would be appreciated.

The \\d matches a digit from 0 to 9. Using {4} matches it 4 times.

You could use ^\\d{4}\\.\\d{2}\\.\\d{4}$

Explanation

  • From the beginning of the string ^
  • Match a digit 4 times \\d{4}
  • Match a dot \\.
  • Match a digit 2 times \\d{2}
  • Match a dot \\.
  • Match a digit 4 times \\d{4}
  • The end of the string $

For the other two you could use a setup like that.

For NNN.N you could use:

^\\d{3}\\.\\d$

For NNNNNNN-NNN you could use:

^\\d{7}-\\d{3}$

Regex : \\d{4}\\.\\d{2}\\.\\d{4}|\\d{3}\\.\\d{1}|\\d{7}-\\d{3}

\\d matches a digit (equal to [0-9])

{n} Matches exactly n times

| or

Regex demo

You've got a jQuery tag, so I recommend the Masked Inputs plugin

 $('.type1').mask('9999.99.9999'); $('.type2').mask('999.9'); $('.type3').mask('9999999-999'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.maskedinput/1.4.1/jquery.maskedinput.js"></script> <label>NNNN.NN.NNNN <input class=type1></label><br> <label>NNN.N <input class=type2></lable><br> <label>NNNNNNN-NNN <input class=type3></label> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM