How to change the ErrorMessage for int model validation in ASP.NET MVC?

Viewed 67931

I have a model with a property defined like this:

    [Required(ErrorMessage="Please enter how many Stream Entries are displayed per page.")]
    [Range(0,250, ErrorMessage="Please enter a number between 0 and 250.")]
    [Column]
    public int StreamEntriesPerPage { get; set; }

This works unless the user enters something like "100q". Then a rather ugly error is displayed that says "The value '100q' is not valid for StreamEntriesPerPage."

Is there an attribute I can use to override the default error message when input is not an int?

7 Answers

ErrorMessage didn't work with Range-attribute for me. I ended up using a RegularExpression-attribute.

Instead of:

[Range(0, 9, ErrorMessage = "...")]
public int SomeProperty { get; set; }

I used:

[RegularExpression("^[0-9]$", ErrorMessage = "..."]
public int SomeProperty { get; set; }

You can find regexp patterns for other ranges etc at: https://www.regular-expressions.info/numericranges.html

I think everyone who was looking for an answer to this question has already found it, but I'll still leave the solution for new seekers. I've been tinkering with this problem for a while too. I eventually figured out that the asp.net validator uses the jQuery validator. That is why I created a separate JavaScript file in which I wrote this code:

function SetNumberMessage() {
    jQuery.extend(jQuery.validator.messages, {
        number: "Значение должно быть числом!"
    });
}

window.onload = SetNumberMessage;

My goal was to translate the validation message, so I override the value for 'number' in the jQuery validator. After that, in the desired Blazor page, I only had to refer to the JavaScript file like this:

<script src = "~/js/SetNumberValidationScript.js"></script>

Answer about which values can be overridden: jQuery validation: change default error message

I hope this helps someone :)

Related