开发者

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

开发者 https://www.devze.com 2023-03-18 17:36 出处:网络
I have a model with a property defined like this: [Required(ErrorMessage=\"Please enter how many Stream Entries are displayed per page.\")]

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 Str开发者_如何学编程eamEntriesPerPage."

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


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


Try adding

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

Reference blog post


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.


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?


Try this:

[DataType(DataType.Currency, ErrorMessage ="......")]
public int YourProperty { get; set; }


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号