Mikayil Abdullayev
Mikayil Abdullayev

Reputation: 12367

How to prevent Fluent Validation from validating the model in certain condition

I have two submit buttons with different names on the form. In the controller I have a single HttpPost action method that I invoke when either of the two submit buttons are clicked. Here's the internals of the action method:

public ActionResult Save(Document model){
    if(Request["btnSave"]!=null){
       if (ModelState.IsValid){
         //go ahead and save the model to db
       }
    }else{//I don't need the model to be validated here
       //save the view values as template in cache
    }
}

So, when the button with name "btnSave" is clicked I need the model to be validated before saving it to db but if the other button is clicked, I don't need any validation as I just save the form values in the cache to later call them back. Obviously I don't need to validate anything in this case. I use Fluent Validation. My problem is I get warnings no matter which button I press. Can I control when FV should validate the model?

Upvotes: 5

Views: 5482

Answers (1)

Electrionics
Electrionics

Reputation: 6772

You can add property btnSave to your model:

public class Document
{
    public string btnSave {get; set;} // same name that button to correctly bind
}

And in your validator use conditional validation:

public class DocumentValidator : AbstractValidator<Document>
{
    public DocumentValidator()
    {
        When(model => model.btnSave != null, () =>
        {
            RuleFor(...); // move all your document rules here
        });

        // no rules will be executed, if another submit clicked
    }
}

Upvotes: 4

Related Questions