Reputation: 2366
I've copied a RegEx that's working in Javascript. But when I run it in C# it returns false. I'm not sure if it's my code iteslf that's incorrect or if it is the RegEx. This is my code.
bool isValid = true;
string nameInput = "Andreas Johansson";
string emailInput = "[email protected]";
string passwordInput = "abcABC123";
string namePattern = @"^[A-z]+(-[A-z]+)*$";
string emailPattern = @"^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$";
string passwordPattern = @"^(?=.*\d+)(?=.*[a-zA-Z])[0-9a-zA-Z!@#$%]{6,50}$";
Regex nameRegEx = new Regex(namePattern);
Regex emailRegEx = new Regex(emailPattern);
Regex passwordRegEx = new Regex(passwordPattern);
if (model.CreateFullName.Length < 3 || !nameRegEx.IsMatch(nameInput))
isValid = false;
if (model.CreateEmail.Length < 3 || !emailRegEx.IsMatch(emailInput))
isValid = false;
if (model.CreatePassword.Length < 3 || !passwordRegEx.IsMatch(passwordInput))
isValid = false;
Thankful for inputs!
Upvotes: 0
Views: 80
Reputation: 16296
You should remove boundary slashes from pattern definitions. They are required for regex objects in javascript not .NET. e.g.:
string namePattern = @"^[A-z]+(-[A-z]+)*$";
string emailPattern = @"^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$";
string passwordPattern = @"^(?=.*\d+)(?=.*[a-zA-Z])[0-9a-zA-Z!@#$%]{6,50}$";
UPDATE: you fixed them in your edit.
The name pattern still does not account for spaces in the input. Try following instead:
^[A-z]+([-\s][A-z]+)*$
Also note that [A-z]
is not a correct pattern for matching alphabet letters. Use [A-Za-z]
for matching ASCII alphabet letters, or \p{L}
for matching any unicode letter.
The problem for [A-z]
is that it matches these character too that reside after Z
and before a
:
[\]^_`
Upvotes: 2