In my model I have a particular field that is annotated in the following manner:
[DataType(System.ComponentModel.DataAnnotations.DataType.Text)]
[RegularExpression("[0-9]{1,10}", ErrorMessage = "The stated Attempt Id is invalid!")]
public long? AttemptId { get; set; }
When I enter incorrect data in the Attempt ID it is giving me the following error message in the Model State:
The value 'cbcbxcb' is not valid for AttemptId.
I have other field with similar error messages but they’re of type string instead of long? and the correct error message is being displayed in those cases when an invalid value is given. Why isn’t the message for the ‘long?’ being used? I’m displaying my errors using the folowing literal tag in the page.
<%: Html.TValidationSummary() %>
EDIT: I have attempted to change the validation in the model to the following:
[Required(ErrorMessage="The stated Attempt Id is invalid!", AllowEmptyStrings=true)]
This however is still incorrect. Firstly, I need to allow the field to be left empty, and when I do it’s giving me the ‘The stated Attempt Id is invalid!’ error message. Secondly when I do enter invalid data in the field it’s reverting back to its old bad error message.
The RegularExpression validation attribute only works with string types. To get a custom error message, use the Required validation attribute instead and put your own custom error message in.
If your model parameter isn’t mandatory, you could perform the validation within the controller and add your own custom message using the ModelState.AddModelError method – this is a bit of a hack, though.