Question

I have a model that implement IValidatlableObject, and so custom error checking through Validate method.

When I create an object all is fine, but when I try to edit that object, I wan't to do that custom validation.

How can I know from wich action I'm calling the Validate method in order to no do the validation?

UPDATED: This is mi model:

public class Ingredient : IValidatableObject
{
    public int Id { get; set; }

    [Required(ErrorMessage = "Required!!")]
    public string Name { get; set; }

    public virtual List<Product> Products { get; set; }

    public Ingredient()
    {
        Products = new List<Product>();
    }

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        using (var uow = new UnitOfWork())
        {
            var ingredient = uow.IngredientRepository.Get(i => i.Name ==Name).FirstOrDefault();

            if (ingredient != null)
                yield return new ValidationResult("Duplicate!!!.", new[] { "Name" });
        }


    }
}

}

So When I create an Ingredient I want to validate ALL (Attributes + IValidatable) but when I edit an Ingrendient I only want to validate attributes (so I mean skip IValidatable) Any method to know, inside the IValidatable method, from where I'm calling Validate ?

Thanks!!!

Was it helpful?

Solution

Check primary key of model - whether it is not null :)

OTHER TIPS

The more "MVCish" correct way here is you actually have two classes, one for the Create method one for the edit. You can call off to a base class for any shared validation, anything then not shared wouldn't be checked here.

If you don't want to validate an object, don't call Model.IsValid (or Validate(), if you're doing it explicitly. Can't answer more than that without knowing more details about your problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top