2

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!!!

Tekno
  • 193
  • 1
  • 1
  • 11

3 Answers3

2

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

Aleksej Vasinov
  • 2,662
  • 28
  • 29
  • I didn't think in it but yes, that could be a nice solution!!!. So I think there's no way to know action/controller inside Validate method – Tekno Mar 12 '12 at 20:21
2

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.

Adam Tuliper
  • 29,982
  • 4
  • 53
  • 71
  • But it will be a bit ugly! Two identical classes only for validation. Not much DRY and not manteinable. I think this is the time when you have to choose between pure MVC or lessMVC-but easier for maintain- – Tekno Mar 12 '12 at 20:41
  • This does not violate DRY. DRY applies to logic duplication , not view models. This is the MVC standard. If you are that concerned about it in viewmodel then both inherit from a single source for shared props bit what are you really saving here - create and edit methods serve two separate purposes and you'll find the more complex the app gets the more separate view models can help. – Adam Tuliper Mar 13 '12 at 23:00
0

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.

bhamlin
  • 5,177
  • 1
  • 22
  • 17