Change the default error message for data type in mvc3
I'm developing in mvc 3 and have a little question. I want to change the default error message for invalid data type. let say I've a model with the prop Price, and I want his error message for input "aaa" will be "The only value you can enter here is a number".
what is the easiest way of doing 开发者_高级运维that? (I want to do it for all of my models)
You could use a Regular Expression data annotation on your model property, e.g.:
[RegularExpression(@"^[0-9\.]*$", ErrorMessage="The only value you can enter here is a number")]
public double Price { get; set; }
You should approach validation from a white list point of view - i.e. what should be allowed through, as opposed to a black list, which would be what is invalid.
More information here:
http://www.asp.net/mvc/tutorials/mvc-music-store-part-6
Hope this helps!
Sam
http://haacked.com/archive/2011/03/19/fixing-binding-to-decimals.aspx
Assuming that you are working with entity framework or Linq to SQL and your class name is Product. here is the example for that. create a partial class like below;
[MetadataType(typeof(Product.MetaData))]
public partial class Product {
private class MetaData {
[Required(ErrorMessage = "The only value you can enter here is a number")]
public decimal Price { get; set; }
}
}
you should add the following using statement in order to use dataanotations for validation;
using System.ComponentModel.DataAnnotations;
精彩评论