Tuesday, April 5, 2011

DataAnnotations - Disallow Numbers, or only allow given strings

Is it possible to use ASP.NET MVC 2's DataAnnotations to only allow characters (no number), or even provide a whitelist of allowed strings? Example?

From stackoverflow
  • Use the RegularExpressionAttribute.

    Something like

    [RegularExpression("^[a-zA-Z ]*$")]
    

    would match a-z upper and lower case and spaces.

    A white list would look something like

    [RegularExpression("white|list")]
    

    which should only allow "white" and "list"

    [RegularExpression("^\D*$")]
    

    \D represents non numeric characters so the above should allow a string with anything but 0-9.

    Regular expressions are tricky but there are some helpful testing tools online like: http://gskinner.com/RegExr/

  • Yes. Use " [RegularExpression]"

    This a great site on Regular expression http://www.regexlib.com/CheatSheet.aspx

0 comments:

Post a Comment