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?
Asked
Active
Viewed 2.3k times
3 Answers
44
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/

John Weisz
- 30,137
- 13
- 89
- 132

Marc Tidd
- 1,066
- 9
- 11
5
You can write your own validator that has better performance than a regular expression.
Here I wrote a whitelist validator for int properties:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace Utils
{
/// <summary>
/// Define an attribute that validate a property againts a white list
/// Note that currently it only supports int type
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
sealed public class WhiteListAttribute : ValidationAttribute
{
/// <summary>
/// The White List
/// </summary>
public IEnumerable<int> WhiteList
{
get;
}
/// <summary>
/// The only constructor
/// </summary>
/// <param name="whiteList"></param>
public WhiteListAttribute(params int[] whiteList)
{
WhiteList = new List<int>(whiteList);
}
/// <summary>
/// Validation occurs here
/// </summary>
/// <param name="value">Value to be validate</param>
/// <returns></returns>
public override bool IsValid(object value)
{
return WhiteList.Contains((int)value);
}
/// <summary>
/// Get the proper error message
/// </summary>
/// <param name="name">Name of the property that has error</param>
/// <returns></returns>
public override string FormatErrorMessage(string name)
{
return $"{name} must have one of these values: {String.Join(",", WhiteList)}";
}
}
}
Sample Use:
[WhiteList(2, 4, 5, 6)]
public int Number { get; set; }

HamedH
- 2,814
- 1
- 26
- 37
4
Yes. Use " [RegularExpression]"
This a great site on Regular expression http://www.regexlib.com/CheatSheet.aspx

VoodooChild
- 9,776
- 8
- 66
- 99