简体   繁体   中英

regular expression alphanumeric characters - allowing hyphens and underscores

I need a Regular Expression for Javascript that checks if a password is correct only when

  • Has at least 1 number and 1 letter
  • Is still valid when it has an underscore and/or a hyphen
  • Must be 4-20 characters long.

Examples:

  1. test123 -> Valid
  2. test1 -> valid
  3. 1234 ->invalid
  4. test -> invalid
  5. test1_ -> valid
  6. test-2 -> valid

I tried using

var Reg = /^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z-_]{4,12}$/;

It works in PHP, but not in Javascript, any suggestions?

Put the hyphen at the end of the character class:

var Reg = /^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z_-]{4,20}$/;

You can also shorten that character class:

var Reg = /^(?=.*\d)(?=.*[A-Za-z])[\w-]{4,20}$/;

Also, you said 20 characters, not 12. Right?

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