c# - 调用 ValidationResult 方法时如何在消息框中显示验证结果?
问题描述
我有一个下面显示的方法,它检查通过的注册在注册列表中是否有效,如果 if 语句返回 true,则注册存在。
我正在使用下面的方法返回验证结果,具体取决于是否满足条件。我想做的是在调用该方法时在文本框中显示这些结果。我怎样才能做到这一点?
public static ValidationResult IsValidRegistration(string registration)
{
try
{
if (!Business.VehicleList.Any(x => x.Registration == registration))
{
return new ValidationResult(true, $"Vehicle created successfully");
}
}
catch
{
return new ValidationResult(false, $"Registration: {registration} already exists");
}
return new ValidationResult(false, $"Failed");
}
我想达到的目标:
if (Validation.IsValidVehicle(registration).IsValid)
{
MessageBox.Show("Success Message");
}
else
{
MessageBox.Show("Error Message");
}
解决方案
首先,您需要使用变量来引用结果,然后检查IsValid
属性并通过ErrorContent
以字符串形式访问属性来获取消息。
var result = Validation.IsValidVehicle(registration);
var message = result.ErrorContent as string;
if (result.IsValid)
{
MessageBox.Show("Success Message" + message);
}
else
{
MessageBox.Show("Error Message" + message);
}
有关ValidationResult 类的更多信息。
更新:根据您的评论,如果值registration
存在,您应该返回错误消息。
public static ValidationResult IsValidRegistration(string registration)
{
try
{
if (!Business.VehicleList.Any(x => x.Registration == registration))
{
return new ValidationResult(true, $"Vehicle created successfully");
}
return new ValidationResult(false, $"Registration: {registration} already exists");
}
catch
{
return new ValidationResult(false, $"Failed");
}
return new ValidationResult(false, $"Failed");
}
推荐阅读
- php - php在上传之前将字符串变量添加到文件名的开头
- visual-studio-code - 从 VSCode 中未聚焦的文件中获取文本
- html - 如何在shopify中的可变产品上添加带有价格的标签
- git - 从 TFVC 转换为 GIT 时的 SSIS .dtproj 问题
- ruby - 在不同的班级中使用一个班级(基本的oop理解)?
- bash - bash 中的正则表达式在 Bash 中使用运算符'=~' 的条件构造中不起作用
- http - 使用 Python 查找最终重定向的 url
- javascript - 行选择在使用 JS 的 Django 中不起作用
- jquery - 在一个项目中使用带有 jquery_ujs 的 rails-ujs?
- constraint-programming - 为什么这个两行更改会破坏这个 minizinc set-cover 程序?