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

Try adding

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

Reference blog post


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?


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.


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; }