Data Annotations for validation, at least one required field?

前端 未结 4 1371
我在风中等你
我在风中等你 2020-12-03 00:52

If I have a search object with a list of fields, can I, using the System.ComponentModel.DataAnnotations namespace, set it up to validate that at least one of the fields in t

4条回答
  •  囚心锁ツ
    2020-12-03 01:35

    This question is pretty old, but as of .NET 3.5 (I believe), IValidatableObject can help with tricky validation situations. You can implement it to validate arbitrary business rules. In this case, something like:

    public IEnumerable Validate(ValidationContext validationContext)
    {
        if (string.IsNullOrWhiteSpace(FieldOne) && string.IsNullOrWhiteSpace(FieldTwo))
            yield return new ValidationResult("Must provide value for either FieldOne or FieldTwo.", new string[] { "FieldOne", "FieldTwo" });
    }
    

提交回复
热议问题