c# - 检查属性的默认值
问题描述
如果您使用过 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# - 如何从 .net core web api 项目中删除虚拟添加的角度文件
- twilio - 是否有可以使用 JS SDK 更新的属性的明确列表?
- angular - 我在这里有一个组件,我用于订阅和订阅后的方法并取消订阅订阅的方法,以避免内存泄漏
- xamarin - 错误 CS0115 , CS1061 与 Uno + Prism + Xamarin.forms
- python - 从数据解析器中解包嵌套字典
- python-3.x - Finding elements with selenium
- c# - 读取 Azure 密钥保管库会引发异常:System.ExecutionEngineException:“引发了‘System.ExecutionEngineException’类型的异常。”
- haskell - 通过haskell元编程提取用于跟踪/记录的上下文
- java - 覆盖 @Where JPA 注释
- arrays - 重新排列数组 A,以便在一对一比较时 A 赢得与数组 B 的最大比较次数