DataAnnotations for jquery validation - Display error from one field on another field

430 Views Asked by At

If I have a class like this:

class Sausage
{
    [Required]
    public string Location {get;set;}

    [Required]
    public decimal Lat {get;set;}

    [Required]
    public decimal Lng {get;set;}
}

If Sausage.Lat or Sausage.Lng is not filled out, I would like to populate an error message onto Sausage.Location instead... Is there an easy way of doing this?

The code might look like this:

class Sausage
{
    [Required]
    public string Location {get;set;}

    [Required]        
    [ErrorFor(Location, "The Location must be filled out")]
    public decimal Lat {get;set;}

    [Required]
    [ErrorFor(Location, "The Location must be filled out")]
    public decimal Lng {get;set;}
}
1

There are 1 best solutions below

4
On

I've implemented the IValidatableObject interface previously to help with this.

There are other ways like creating custom validation attributes but I find this more easy for me:

public class Sausage : IValidatableObject
{

    public string Location { get; set; }

    [Required]
    public decimal Lat { get; set; }

    [Required]
    public decimal Lng { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (Lat == decimal.Zero || Lng == decimal.Zero)
        {
            yield return new ValidationResult("Please ensure both Lng & Lat is filled in", new[] { "Location" });
        }
    }
}