Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Password must have at least one non-alpha character [duplicate]

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
like image 798
cashmere Avatar asked Aug 21 '12 12:08

cashmere


People also ask

What is a non alpha character in a password?

English Lowercase characters (a-z) • Base Digits (0-9) • Non Alphanumeric Characters (e.g.,@,%,#,!)

What does Passwords must have at least one non alphanumeric character mean?

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.

How do you remove non alpha characters?

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.

What is a one non alphanumeric character?

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.


1 Answers

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])
like image 50
Ωmega Avatar answered Sep 19 '22 13:09

Ωmega