首页 > 解决方案 > 检查属性的默认值

问题描述

如果您使用过 asp.net,您会看到在验证模型时您可以这样做

if (ModelState.IsValid)

然后您可以自动验证模型。我正在尝试在 Windows 窗体中构建模型验证。我有这个来验证我的模型并且它正在工作,但是有一个问题。当我在文本框中输入文本并将其删除时,该值变为空,因此该值不再为空。当我使用反射时,如何以这种方式检查默认值

private void ValidateModel(TModel _model)
{
   foreach (PropertyInfo propInfo in _model.GetType().GetProperties())
   {
      if (propInfo.GetCustomAttribute(typeof(RequiredAttribute)) != null && propInfo.GetValue(_model) == null)
      {
       
        if(propInfo.GetValue(_model) == default)
        {
           InvalidProperty = propInfo.Name;
           Errors.Add($"The {propInfo.Name} field is required")
           IsValid = false;
           continue;
        }
       
      }
   }
}

考虑这个例子,一个用户传递了一个要存储到数据库的对象,你必须编写一个通用方法来验证它,无论输入的类型或输入的位置如何

public class User
{
    [Required]
    public string FirstName { get;  set; }
    [Required]
    public string LastName { get;  set; }
    [DataType(DataType.Date)]
    public string DOB { get;  set; }
    //......Other properries
}

然后你必须做类似的事情

var state = new ModelState(user);
if (state.IsValid)
{
    //Use error provider to show appropriate errors
}

标签: c#winformsvalidationtextboxuser-input

解决方案


推荐阅读