gdoron
gdoron

Reputation: 150293

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)

Upvotes: 1

Views: 3977

Answers (3)

tugberk
tugberk

Reputation: 58494

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;

Upvotes: 0

Sam Huggill
Sam Huggill

Reputation: 3126

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

Upvotes: 4

Related Questions