Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Require one field or another

Basically what I'm trying to figure out is how to require at least one of two fields to be filled out in a View.

In my View, I have two text fields called ISBN and ISBN13. It doesn't matter which one the user fills in as long as one of them gets filled in.

I'm not sure what to do here expect to look into writing a custom validator so I thought I would ask first. I would have included some code but since it's just two simple fields I thought this explanation would be better.

like image 995
Christopher Johnson Avatar asked Nov 29 '22 09:11

Christopher Johnson


1 Answers

You may do a manual validation in your controller action. The AddModelError method will help you use the validation stack.

[HttpPost]
public ActionResult Edit(EditModel model)
{
    if (string.IsNullOrEmpty(model.ISBN) && string.IsNullOrEmpty(model.ISBN13))
    {
        var validationMessage = "Please provide ISBN or ISBN13.";
        this.ModelState.AddModelError("ISBN", validationMessage);
        this.ModelState.AddModelError("ISBN13", validationMessage);
    }

    if (!string.IsNullOrEmpty(model.ISBN) && !string.IsNullOrEmpty(model.ISBN13))
    {
        var validationMessage = "Please provide either the ISBN or the ISBN13.";
        this.ModelState.AddModelError("ISBN", validationMessage);
        this.ModelState.AddModelError("ISBN13", validationMessage);
    }

    if (this.ModelState.IsValid)
    {
        // do something with the model
    }

    return this.View(model);
}

Some may say that it is not the responsibility of the controller to do the validation of the query. I think that the controller's responsibility is to adapt the web request into a domain request. Therefore, the controller can have validation logic. If you do not have a domain/business layer, this consideration has no sense.

like image 97
SandRock Avatar answered Dec 06 '22 05:12

SandRock