How to ignore validation annotation if field is bl

2019-09-15 18:08发布

问题:

I have these classes:

Class Parent
{
   [Required]
   String Name ;

   Child child ;
}

Class Child
{
   [Required]
   Child FirstName ;
   [Required]
   Child LastName ;
}

I have a form showing the Parent entity fields including the Childs's. With my configuration the child's FistName and LastName are required and if left blank causes validation to fail.

What I need is have validation pass if both the child's FirstName and LastName are submitted blank. If either FirstName or LastName is submitted then the other is required and validation should fail.

How can I achieve this?

回答1:

I would implement your own validation method on the model. Your model would end up looking something like this:

public class Child : IValidatableObject {
   public string FirstName {get; set;}
   public string LastName {get; set;}

   public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
       if ((string.IsNullOrEmpty(this.FirstName) && !string.IsNullOrEmpty(this.LastName)) || (!string.IsNullOrEmpty(this.FirstName) && string.IsNullOrEmpty(this.LastName))) {
           yield return new ValidationResult("You must supply both first name and last name or neither of them");
       }
   }
}


回答2:

just change your annotation to:

[Required(AllowEmptyString=true)]

This will allow the empty string to pass validation. You can then do additional validation on the server if required.

This link should help:

RequiredAttribute.AllowEmptyStrings Property