How Can I Use Data Annotations Attribute Classes to Fail Empty Strings in Forms?

前端 未结 4 2148
伪装坚强ぢ
伪装坚强ぢ 2020-12-09 02:10

I was trying to require a text input field in a form, which implies that there needs to be something in the form. However, adding a [Required] tag to my model w

4条回答
  •  天涯浪人
    2020-12-09 02:24

    I'd implement a new validation attribute like this and apply it to my model.

    public class RequiredNotEmptyAttribute : RequiredAttribute
    {
        public override bool IsValid(object value)
        {
            if(value is string) return !String.IsNullOrEmpty((string)value);
    
            return base.IsValid(value);
        }
    }
    

    This will only work on the server side (client side will still only check for null).

提交回复
热议问题