简体   繁体   中英

Validate DateTime with DataAnnotation

I'm developing and asp.net app and i'm using data annotations to validate my Input model. In this model, I have one field of type DateTime, and I'd like to know how could I customize the message when the user set an date value invalid.

My property in my model:

[Required(ErrorMessage = "Informe sua data de nascimento.")]
[MinAge(Idade = 18, ErrorMessage = "Você deve possuir no mínimo 18 anos para se cadastrar neste website.")]
public virtual DateTime DataNascimento { get; set; }

My model is thowing a message like this: "The value '45/64/5646' is not valid for DataNascimento."

If you could help me I appretiate!

PS: The messages of validators are in pt-br (because it'll be the language of the application)

Thanks a lot

I've already answered a similar question.

Check it out

In some cases MVC uses its own error messages. This is problematic for multiple language support.

I think what you need there is a regular expression that actually checks the format of the date time. (Note: I think this is the correct RegEx format.

[RegularExpression(@"^([0]?[1-9]|[1|2][0-9]|[3][0|1])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{2})$", ErrorMessage = "The date is invalid.")]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM