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

前端 未结 4 2108
伪装坚强ぢ
伪装坚强ぢ 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:22

    After a lot of Googling and looking on Stackoverflow, I had nothing.

    I went to MSDN and looked at the System.ComponentModel.DataAnnotations Namespace.

    There I looked more closely at the Required attribute, and noticed the AllowEmptyStrings property. Setting this to false tells the attribute not to allow any empty strings, which I would have assumed was the default behavior, seeing as how the point of Required is to require that something be entered, and an empty string indicates that nothing was entered.

    This doesn't solve the problem though, as by default empty strings are coerced to null, which are not empty strings, and are therefore allowed. Once again this is absurd, as Required is supposed to test if something was entered, and null indicates nothing was entered. However, the AllowEmptyStrings page has a link to DisplayFormAttribute's Property ConvertEmptyStringsToNull. If you set this to false, then empty strings will remain empty strings, and then the required tag will not allow them.

    So, here's the fix:

    public class ColumnWidthMetaData {
        [DisplayName("Column Name")]
        [Required(AllowEmptyStrings=false)]
        [DisplayFormat(ConvertEmptyStringToNull=false)]
        public string ColName { get; set; }
    
        [DisplayName("Primary Key")]
        public int pKey { get; set; }
    
        [DisplayName("User Name")]
        [Required(AllowEmptyStrings=false)]
        [DisplayFormat(ConvertEmptyStringToNull=false)]
        public string UserName { get; set; }
    
        [DisplayName("Column Width")]
        [Required]
        public int Width { get; set; }
    }    
    
    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2020-12-09 02:34

    You can add a DefaultValueAttribute to the property that requires a default value (e.g. string.Empty for UserName)

    [DisplayName("User Name")]
    [System.ComponentModel.DefaultValue("")]
    public string UserName { get; set; }
    
    0 讨论(0)
  • 2020-12-09 02:37

    You could use [MinLength(1)]. See msdn docs here.

    0 讨论(0)
提交回复
热议问题