简体   繁体   中英

validate text field using regular expression javaScript

I want to validate a text field to accept just text like this :

  • 1,2;2,3;1-3
  • 1-2;4;2,3;4;1-3
  • 12

I don't want the types like this :

  • ;1
  • ,1
  • -1
  • 1;;2
  • 1,,2
  • 1--2
  • 1-2-3
  • 1,2,3
  • 1,2-3

so I make this regular expression but it seems doesn't work like what I want

var reg = /^\d*(((?!.*--)(?!.*,,)(?!.*;;)(?!.*,;)(?!.*,-)(?!.*-;)(?!.*-,)(?!.*;,)(?!.*;-))[,-;])*\d$/

thanks for your help :)

You may use

/^\d+(?:(?:[-,;]\d+){3,})?$/

See the regex demo

Details

  • ^ - start of string
  • \\d+ - 1 or more digits
  • (?:(?:[-,;]\\d+){3,})? - 1 or 0 sequences of:
    • (?:[-,;]\\d+){3,} - 3 sequences of:
      • [-,;] - a - , , or ;
      • \\d+ - 1 or more digits
  • $ - end of string

 var ss = [ '1,2;2,3;1-3','1-2;4;2,3;4;1-3','12',';1',',1','-1','1;;2','1,,2','1--2','1-2-3','1,2,3','1,2-3',';1',',1','-1','1;;2','1,,2','1--2' ]; var rx = /^\\d+(?:(?:[-,;]\\d+){3,})?$/; for (var s of ss) { console.log(s, "=>", rx.test(s)); } 

NOTE: the [,-;] creates a range between , and ; and matches much more than just , , - or ; (see demo ).

you can simply use the regex

 function match(str){ return str.match(/^(?!.*([-,])\\d+\\1)(?!.*,\\d+-)\\d+(?:[-,;]\\d+)*$/) != null } console.log(match(';1')); console.log(match(',1')); console.log(match('1;;2')); console.log(match('1-3')); console.log(match('12')); console.log(match('1,2;2,3;1-3')); console.log(match('1-2;4;2,3;4;1-3')); console.log(match('1,2,3')); 

take a look at regex demo

Here's my attempt. Based on your examples I've assumed that semi-colons are used to separate 'ranges', where a 'range' can be a single number or a pair separated by either a comma or a hyphen.

 var re = /^\\d+([,\\-]\\d+)?(;\\d+([,\\-]\\d+)?)*$/; // Test cases [ '1', '1,2', '1-2', '1;2', '1,2;2,3;1-3', '1-2;4;2,3;4;1-3', '12', ';1', ',1', '-1', '1;;2', '1,,2', '1--2', '1-2-3', '1,2,3', '1,2-3' ].forEach(function(str) { console.log(re.test(str)); }); 

The first part, \\d+([,\\-]\\d+)? matches a 'range' and the second part (;\\d+([,\\-]\\d+)?)* allows further 'ranges' to be added, each starting with a semi-colon.

You can add in ?: to make the groups non-capturing if you like. That's probably a good idea but I wanted to keep my example as simple as I could so I've left them out.

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