32

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,396
  • 24
  • 89
  • 148

6 Answers6

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
  • 710
  • 6
  • 14
Feras Kayyali
  • 603
  • 5
  • 5
10

Try adding

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

Reference blog post

Bala R
  • 104,615
  • 23
  • 192
  • 207
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
  • 40,197
  • 14
  • 86
  • 141
  • 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
  • 302
  • 6
  • 5
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,657
  • 5
  • 43
  • 71
Per
  • 33
  • 7