Lars Kroeze
Lars Kroeze

Reputation: 13

c# regular expression always returns errors

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.

Upvotes: 0

Views: 101

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186688

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!";
}

Upvotes: 1

Quentin Roger
Quentin Roger

Reputation: 6538

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}$");

Upvotes: 2

Related Questions