MVC: Override default ValidationMessage

前端 未结 8 2145
鱼传尺愫
鱼传尺愫 2020-12-13 15:05

In the world of MVC I have this view model...

public class MyViewModel{

[Required]
public string FirstName{ get; set; }    }

...and this s

8条回答
  •  佛祖请我去吃肉
    2020-12-13 15:55

    You can write your own attribute:

    public class MyRequiredAttribute : ValidationAttribute
    {
        MyRequiredAttribute() : base(() => "{0} blah blah blah blaaaaaah")
        {
    
        }
    
        public override bool IsValid(object value)
        {
            if (value == null)
            {
                return false;
            }
            string str = value as string;
            if (str != null)
            {
                return (str.Trim().Length != 0);
            }
            return true;
        }
    }
    

    This is copy of RequiredAttribute from Reflector with changed error message.

提交回复
热议问题