Validating

Let’s learn to apply validation to the form fields.

While playing with the results of the application build so far, our hypothetical client notices something. If they enter an invalid price or forget to set up a product description, the application happily accepts the form and adds a line to the database. A missing description is embarrassing and a price of $0.00 costs them actual money, so they asked that we add validation to the application. No product should be allowed in the database if it has an empty title or description field, an invalid URL for the image, or an invalid price.

So where do we put the validation? The model layer is the gatekeeper between the world of code and the database. Nothing to do with our application comes out of the database or gets stored into the database that doesn’t first go through the model. This makes models an ideal place to put validations. It doesn’t matter whether the data comes from a form or from some programmatic manipulation in our application. If a model checks it before writing to the database, the database will be protected from bad data. ...

Form with multiple fields

Get hands-on with 1400+ tech skills courses.