2

I am working with ASP.NET MVC 5 application in which I want to add dataannotation validation for Name field.

That should accept any combination of number,character and under score only.

I tried by this but not working :

RegularExpression("([a-zA-Z0-9_ .&'-]+)", ErrorMessage = "Invalid.")]
stema
  • 80,307
  • 18
  • 92
  • 121
user3848036
  • 169
  • 1
  • 4
  • 14

2 Answers2

3

Try this regex written under the regexr.com site.

Criteria - alphanumeric,underscore and space.

http://regexr.com/3agii

([a-zA-Z0-9_\s]+)

Lari
  • 113
  • 2
  • 9
Karan
  • 2,788
  • 6
  • 46
  • 77
  • Karan but now my requirement has changed and now I want it for alphanumeric,underscore and space – user3848036 Feb 26 '15 at 11:08
  • 1
    As per Stack Overflow best practice - please enter the answer into here rather than relying on an external link thanks. – niico Sep 30 '16 at 13:39
-2

You are using a character class, that is the thing between the square brackets ([a-zA-Z0-9_ .&'-]). Within that square brackets you can define all characters that should be matched by this class. So, now it is easy: you allow characters you don't want to match.

Based on your "try" you could change this to

[a-zA-Z0-9_]

that seem to be the characters you want to match. But is it really what you need? Are that really the only characters that are possible for that field?

If yes then you are done.

If no, you probably want to add all characters of all languages. Luckily there is a Unicode property for that:

\p{L} All letter characters

There is another predefined group that could be useful for you:

\w matches any word character (The definition can also be found in the first link, includes the Unicode categories Ll,Lu,Lt,Lo,Lm,Nd,Pc, that is basically [a-zA-Z0-9_] but Unicode style with all letters and more connecting characters)

But still, if you want to match real names this will not cover all possible names. I have another answer on this topic here

stema
  • 80,307
  • 18
  • 92
  • 121