0

I have got two regular expression in my c# project, the one works the other doesnt.

Regex RX = new Regex("^[a-zA-Z0-9]{1,20}@[a-zA-Z0-9]{1,20}.[a-zA-Z]{2,3}$");
if (!RX.IsMatch(emailInput.Text))
{
    errorMessage = "Email is invalid!";
}

This one checks if the email is actually an email, I wanted to the the same for username. Where I check for username length and special characters.

new Regex(@"^(?=[A-Za-z0-9])(?!.*[._()\[\]-]{2})[A-Za-z0-9._()\[\]-]{3,15}$");
if (!RX.IsMatch(usernameInput.Text))
{
    errorMessage = "Username is invalid!";
}

Somehow everytime I run my project it returns username is invalid, which I dont understand. It doesnt matter what I type as username it always returns the errorMessage.

10
  • 3
    Some samples would be nice. Commented Apr 4, 2016 at 9:21
  • The username regex works. Commented Apr 4, 2016 at 9:25
  • Did you assign new Regex to RX? Commented Apr 4, 2016 at 9:25
  • 4
    Don't use regular expressions to check for email address validity. There are so many edge-cases. Most of the valid email addresses I (try to) use daily are flagged as invalid by your regular expression, and by so many others. Commented Apr 4, 2016 at 9:25
  • 1
    Possibly this is just for demo purposes, but you should not use that email regex in the real world. It will fail most valid email addresses. Commented Apr 4, 2016 at 9:26

2 Answers 2

2

Your regex is working, but I think you forgot to assign RX to your new regex.

new Regex(@"^(?=[A-Za-z0-9])(?!.*[._()\[\]-]{2})[A-Za-z0-9._()\[\]-]{3,15}$");

should be

RX = new Regex(@"^(?=[A-Za-z0-9])(?!.*[._()\[\]-]{2})[A-Za-z0-9._()\[\]-]{3,15}$");
Sign up to request clarification or add additional context in comments.

Comments

1

It seems, that you don't want creating Regex instance at all, let .Net do it for you:

if (!Regex.IsMatch(usernameInput.Text, 
                   @"^(?=[A-Za-z0-9])(?!.*[._()\[\]-]{2})[A-Za-z0-9._()\[\]-]{3,15}$")) {
  errorMessage = "Username is invalid!";
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.