I need a regular expression for a password. The password has to contain at least 8 characters. At least one character must be a number or a special character (not a letter).
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 8)]
[RegularExpression(@"(?=.*\W)?(?=.*\d)", ErrorMessage = "Error message")]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
I have a length validation, but I need help with a regular expression that checks if the password contains at least one number or special character.
Examples of valid passwords:
testtest85*
testtes*
testtes1
test1234*+
Examples of not valid passwords:
testtest
testabc
English Lowercase characters (a-z) • Base Digits (0-9) • Non Alphanumeric Characters (e.g.,@,%,#,!)
Non-Alphanumeric characters are except alphanumeric characters. space, percent sign, underscore, pipe, colon, semicolon, etc are non-alphanumeric characters. They can be also categorized as punctuation characters, symbol characters, etc.
To remove all non-alphanumeric characters from a string, call the replace() method, passing it a regular expression that matches all non-alphanumeric characters as the first parameter and an empty string as the second. The replace method returns a new string with all matches replaced.
Non-Alphanumeric characters are the other characters on your keyboard that aren't letters or numbers, e.g. commas, brackets, space, asterisk and so on. Any character that is not a number or letter (in upper or lower case) is non-alphanumeric.
Use regex pattern ^(?=.{8})(?=.*[^a-zA-Z])
Explanation:
^(?=.{8})(?=.*[^a-zA-Z])
│└──┬───┘└──────┬──────┘
│ │ │
│ │ └ string contains some non-letter character
│ │
│ └ string contains at least 8 characters
│
└ begining of line/string
If you want to limit also maximum length (let's say 16), then use regex pattern:
^(?=.{8,16}$)(?=.*[^a-zA-Z])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With