简体   繁体   中英

Regex for form field validation

I have a form which has a field of a special type.this needs validation. Conditions

  1. It must contain at least 1 letter.upper case and lower case both are allowed [mandatory]
  2. It can contain a number [optional]
  3. It can contain any 1 or all 3 of the following special characters hyphen (-), ampersand (&), period (.)[optional]
  4. Length minimum of 5 maximum of 100
  5. Can contain space between letters [optional]

I tried this pattern

/[a-zA-Z0-9]+|[\s]+|[\.]+|[\&]+|[\-]+/

But it doesn't give the expected output.

examples:

abcd xyz ->must pass test(letter must, 5<characters count<100,space optional)
abcdxyz  ->must pass test(letter must, 5<characters count<100,space optional)
abcd & ->must pass test
abcd1234 ->must pass test
abcd.xyz.12 ->must pass test
123456 ->must fail test(no letters found)
&&&&&&& ->must fail test(no letters found)
&&&--..& ->must fail test(no letters found)
123 abcd.xyz 777-& !$ ->must fail test(!$ are not allowed)

I can count the string length separately,but i need the regex for the rest part. I am using

str.match(/regex/)

If you can test length separately, this could do the job: ^(?:[a-zA-Z0-9 .&-]*)?[a-zA-Z]+(?:[a-zA-Z0-9 .&-]*)?$ . What makes it hard to count here is that {5,100} would test the number of occurences of a subpattern and not the total of letters it found.

explanation (in order):

  • start of string
  • can optionally find any number of letter/number and " .&-"
  • must found at least one letter
  • can optionally find any number of letter/number and " .&-"
  • end of string

example adapted from Regex101 code generator :

 const regex = /^(?:[a-zA-Z0-9 .&-]*)?[a-zA-Z]+(?:[a-zA-Z0-9 .&-]*)?$/; const strs = [ 'abcd xyz', 'abcdxyz', 'abcd &', 'abcd1234', 'abcd.xyz.12', '123456', '&&&&&&&', '&&&--..&', '123 abcd.xyz 777-& !$' ]; let m, i, l = strs.length; for(i = 0; i < l; i++){ if( (m = strs[i].match(regex)) ){ console.log('Found match: ', m); }else{ console.log('Doesn\\'t match: ', strs[i]); } }

NOTE : If you meant to use this for a password, rules like this are a bad idea and now officially discouraged

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