0

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!

2
  • Show values you're testing your regex with Commented Apr 14, 2013 at 12:11
  • Edited, added input values Commented Apr 14, 2013 at 12:18

1 Answer 1

2

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:

[\]^_`
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer, it made email and password work, I've made an edit with the input values I use if you see anything in the name regex

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.