如何实现IValidatableObject?

时间:2015-05-25 07:59:29

标签: asp.net-mvc validation model-validation

我有3个文本框,主要的想法是,如果这些字段中的任何一个是空的,以获得一条错误消息,但我不知道如何使用此...任何帮助?

[Required]
public int? Day { get; set; }

[Required]
public int? Month { get; set; }

[Required]
public int? Year { get; set; }

public System.Collections.Generic.IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
    if (Day == null || Month == null || Year == null)
    {
        yield return new ValidationResult("*");
    }
}

1 个答案:

答案 0 :(得分:0)

试试这个,我希望以下答案可以帮到你。

继承ValidationAttribute

public class SingleMessageValidation : ValidationAttribute
{
    public override bool IsValid(object obj)
    {
        DateValidation app = obj as DateValidation;
        if (app.Day == null || app.Month == null || app.Year == null)
        {
            ErrorMessage = "In valid date enter all fields";
            return false;
        }
        return true;
    }
}

<强>模型

[SingleMessageValidation]
public class DateValidation
{
    public int? Day { get; set; }
    public int? Month { get; set; }
    public int? Year { get; set; }
}

查看

@model DateValidation

<h2>DateValidation</h2>
@using (Html.BeginForm())
{
    @Html.ValidationSummary()

    @:Day: @Html.TextBoxFor(x => x.Day)
    <br />
    @:Month: @Html.TextBoxFor(x => x.Month)
    <br />
    @:Year: @Html.TextBoxFor(x => x.Year)

    <input type="submit" value="Click" />
}