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?
Data Annotations are nothing but certain validations that we put in our models to validate the input from the user. ASP.NET MVC provides a unique feature in which we can validate the models using the Data Annotation attribute. Import the following namespace to use data annotations in the application.
We can easily add validation to our application by adding Data Annotations to our model classes. Data Annotations allow us to describe the rules we want applied to our model properties, and ASP.NET MVC will take care of enforcing them and displaying appropriate messages to our users.
DataAnnotations namespace includes the following validator attributes: Range – Enables you to validate whether the value of a property falls between a specified range of values. RegularExpression – Enables you to validate whether the value of a property matches a specified regular expression pattern.
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/
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With