【问题标题】:How do you show validation result in messagebox when calling ValidationResult method?调用 ValidationResult 方法时如何在消息框中显示验证结果?
【发布时间】:2021-06-08 23:25:33
【问题描述】:

我有一个如下所示的方法,它检查通过的注册在注册列表中是否有效,如果 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


    【解决方案1】:

    首先,您需要使用一个变量来引用结果,然后检查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 Class的信息。

    更新: 根据您的评论,如果 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");
    }
    

    【讨论】:

    • 我面临的问题是,由于最后一个错误消息返回语句,无论错误是什么,它都只会返回错误。我该怎么做return new ValidationResult(false, $"Registration: {registration} already exists");
    • @MarkHunt 我已经更新了我的答案,请检查一下。
    猜你喜欢
    • 1970-01-01
    • 2021-07-05
    • 2011-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多