33

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?

quakkels
  • 11,676
  • 24
  • 92
  • 149

7 Answers7

25

Yes, you can use Data annotations extensions, mark your property as the following:

[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]
[DataAnnotationsExtensions.Integer(ErrorMessage = "Please enter a valid number.")]
public int StreamEntriesPerPage { get; set; }
Stefan Born
  • 720
  • 6
  • 14
Feras Kayyali
  • 623
  • 5
  • 5
10

Try adding

[RegularExpression("\\d+", ErrorMessage = "some message here")]

Reference blog post

Bala R
  • 107,317
  • 23
  • 199
  • 210
10

Much like Feras' suggestion, but without the external dependency:

using System;
using System.ComponentModel.DataAnnotations;

namespace MyDataAnnotations
{
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
    public class IntegerAttribute : DataTypeAttribute
    {
        public IntegerAttribute()
            : base("integer")
        {
        }

        public override string FormatErrorMessage(string name)
        {
            if (ErrorMessage == null && ErrorMessageResourceName == null)
            {
                ErrorMessage = "Enter an integer"; // default message
            }

            return base.FormatErrorMessage(name);
        }

        public override bool IsValid(object value)
        {
            if (value == null) return true;

            int retNum;

            return int.TryParse(Convert.ToString(value), out retNum);
        }
    }
}

Then you can decorate with an [Integer(ErrorMessage="...")] attribute.

Kieren Johnstone
  • 41,277
  • 16
  • 94
  • 144
  • This looks really cool. Do you have any resources I could browse to for information about inheriting from `DatatTypeAtribute`? – quakkels Jul 05 '11 at 20:12
  • 6
    This doesn't seem to do anything. I created the namespace and the class with the overrides. Then, I used the namespace on my model class and added `[Integer(ErrorMessage="Please enter a whole number.")]`. When I enter '20d' I still get "The value '20d' is not valid for StreamEntriesPerPage." – quakkels Jul 05 '11 at 20:30
  • It doesn't work for me either, if I use `int` as data type in my model (value of `value` is always `null`). Though if I use `string` instead of `int`, it works as expected, what could be wrong? – Gabrielius Feb 28 '16 at 17:40
6

I had the same problem, this solution resolved it:

  • Create App_GlobalResources folder for your project (right click to project -> Add -> Add ASP.NET folder -> App_GlobalResources).
  • Add a resx file in that folder. Say MyNewResource.resx.
  • Add resource key PropertyValueInvalid with the desired message format (e.g. "content {0} is invalid for field {1}"). If you want to change PropertyValueRequired too add it as well.
  • Add the code DefaultModelBinder.ResourceClassKey = "MyNewResource" to your Global.asax startup code.

from: How to change default validation error message in ASP.NET MVC?

Community
  • 1
  • 1
tarn
  • 352
  • 6
  • 6
1

Try this:

[DataType(DataType.Currency, ErrorMessage ="......")]
public int YourProperty { get; set; }
Thien
  • 19
  • 1
0

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

openshac
  • 4,966
  • 5
  • 46
  • 77
Per
  • 33
  • 7
0

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 :)

Vizel Leonid
  • 456
  • 7
  • 15