1

For Asp.Net mvc model validation I'm trying to create a regex for the following requirement:

  • string length between 1-5 (including 1 and 5 limit)
  • non word characters are not allowed
  • underscore not allowed

I can write a regex witch matches the non word characters but not the inverse of my question.

Regex

Non word characters and underscore match:

([\W_])

String length between 1 and 5:

{1-5}

Asp.net mvc Code:

namespace x
{
    public class Model
    {
        [RegularExpression(@"")]
        public string AString {get;set;}
    }
}
0

1 Answer 1

2

You can use

^[^\W_]{1,5}$

Se the demo

The regex breakdown:

  • ^ - start of string
  • [^\W_]{1,5} - not a non-word character and not a _ 1 to 5 occurrences
  • $ - end of string.

The [^...] is a negated character class that matches any character that is not in the character class.

Also, when you want to limit string length with a regex, you need to use some boundaries. In this case, you can rely on the usual start/end-of-string anchors.

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.