包含摘要和字段的多字段验证

时间:2017-10-16 16:28:18

标签: c# asp.net-mvc validation

我在asp.net MVC中,我正在尝试创建一个自定义ValidationAttribute,它以我的模型类为目标,强制执行一组字段为空或全部填充。如果它无效,我希望它返回表单顶部的验证摘要,并突出显示所有必填字段红色,字段本身没有验证消息......这是我现在的代码......

[AttributeUsage(AttributeTargets.Class)]
public class CourtSearchNameDOBValidator : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var searchData = (CourtSearchModel)value;

        if(validationContext == null)
        {
            return null;
        }

        var firstNameIsEmpty = string.IsNullOrWhiteSpace(searchData.FirstName);
        var lastNameIsEmpty = string.IsNullOrWhiteSpace(searchData.LastName);
        var dateOfBirthIsEmpty = searchData.DateOfBirth == null;

        var allFieldsAreEmpty = firstNameIsEmpty && lastNameIsEmpty && dateOfBirthIsEmpty ;

        // All fields must be filled in if any are filled
        if (!allFieldsAreEmpty)
        {
            if (firstNameIsEmpty || lastNameIsEmpty || dateOfBirthIsEmpty)
            {
                var validationResults = new ValidationResult("All name fields are required", new List<string>() { "FirstName", "LastName", "DateOfBirth" });
                return validationResults;
            }
        }

        return null;
    }
}

现在,只突出显示我的FirstName属性,并且该字段(此部分是预期的)上出现错误消息“所有名称字段都是必需的”。我不期待和混淆的是其他字段(LastName和DateOfBirth)也不高亮并显示验证消息的部分。我将它们包含在ValidationResult的memberNames属性中......

0 个答案:

没有答案