2

I was trying to get a user name validations where the following texts are valid,

  • Test
  • Test2
  • Tes2
  • Test123
  • 123Test
  • 1234
  • Test_56
  • test-6ty

But not the following

  • Tes (Min Length)
  • Test@123 (Special char)

I added following annotations in Model, though does't seem to be working for the correct texts too. Keep getting the error message.

[RegularExpression(@"^[a-zA-Z0-9\-_]$", ErrorMessage = "Only alphanumeric, hyphen and underscores are allowed for User name.")]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 4)]
6
  • Are you saying that ModelState is valid when you submit with either "Tes" or "Test@123"? Commented Oct 25, 2015 at 7:51
  • No the ErrorMessage will show fo even the correct once. Commented Oct 25, 2015 at 8:06
  • Which of the error messages? Commented Oct 25, 2015 at 8:08
  • The one for Regular Expression, "Only alphanumeric, hyphen and underscores are allowed for User name." Commented Oct 25, 2015 at 8:09
  • 2
    Your only allowing 1 character - use ^[a-zA-Z0-9\-_]*$ (or ^[a-zA-Z0-9\-_]{4, 100}$ to combine both as suggested in anubhava's answer Commented Oct 25, 2015 at 8:11

1 Answer 1

2

From your examples it looks like this regex can be suitable for you:

@"^[a-zA-Z0-9_-]{4,10}$"

{4,10} sets minimum length of input to 4 and max length to 10. Change it whatever limits you want to keep.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.