我有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("*");
}
}
答案 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" />
}