首页 > 解决方案 > 调用 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");
}

标签: c#validation

解决方案


首先,您需要使用变量来引用结果,然后检查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");
}

推荐阅读