ASP.net MVC - Custom attribute error message with nullable properties

前端 未结 3 1675
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-23 05:42

I am having a property in my View Model which can accept integer and nullable values:

    [Display(Name = \"Code Postal\")]
    public int? CodePostal { get; set         


        
3条回答
  •  误落风尘
    2021-01-23 06:24

    Alternative - rewrite resource strings

    The easiest way is to replace default validation resource strings. This other SO answer will help you with that.

    But you have to remember that these strings will them be used on all of your models not just particular property of some class.


    Note: According to Darin (and me not testing the code) I'm striking part of my answer. The simplified approach by changing resource strings still stands. I've done that myself and I know it works.

    Regular expression attribute

    Add an additional attribute to your property:

    [Display(Name = "Code Postal")]
    [RegularExpression("\d+", ErrorMessage = "I'm now all yours...")]
    public int? CodePostal { get; set; }
    

    Even though you set regular expression on a non-string property this should still work. If we look at validation code it's like this:

    public override bool IsValid(object value)
    {
        this.SetupRegex();
        string text = Convert.ToString(value, CultureInfo.CurrentCulture);
        if (string.IsNullOrEmpty(text))
        {
            return true;
        }
    
        Match match = this.Regex.Match(text);
        return match.Success && match.Index == 0 && match.Length == text.Length;
    }
    

    As we can see, this validator automatically converts the value to string. So if your value is a number it doesn't really matter because it will be converted to a string and validated by your regular expression.

提交回复
热议问题