Custom validation error message if user puts a non-numeric string in an int field

这一生的挚爱 提交于 2019-12-05 03:29:42
Cymen

If you're using standard annotations, you should be able to override the error message with something like this:

[MyAnnotation(...., ErrorMessage = "My error message")]
public int myInt { get; set; }

Or do you actually want to append to the default error message instead of replacing it (not clear in question)?

Update: Misread -- suggest this as the answer: How to change the ErrorMessage for int model validation in ASP.NET MVC? or better yet How to change 'data-val-number' message validation in MVC while it is generated by @Html helper

You can also inherit IValidatableObject in your model class. You can write down your required logic in the Validate method. Please find sample code below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace MvcApplication1.Models
{
    public class Alok : IValidatableObject
    {
        [Display(Name = "Property1")]
        [Required(AllowEmptyStrings = false, ErrorMessage = "Property1 is required.")]
        public int Property1 { get; set; }

        [Display(Name = "Property2")]
        [Required(AllowEmptyStrings = false, ErrorMessage = "Property2 is required.")]
        public int Property2 { get; set; }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            if (Property1 < Property2)
            {
                yield return new ValidationResult("Property 1 can't be less than Property 2.");
            }
        }
    }
}
Iridio

read this question. In the link that the OP suggest you will find the way to replace the deafult error string that use the framework, while in the answer you will find a linnk to the other resources in case you want to change all of them. Look also here. Hope it helps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!