popolo - code simple..

popolo - code simple..

Handling validation form errors in Masonite Project

Handling validation form errors in Masonite Project

Theodoros Kafantaris's photo
Theodoros Kafantaris
·May 9, 2022·

2 min read

In this article, we will see the two possible ways of handling the validation form errors in Masonite Project.

First of all, we need to prepare our controller with the validation part and share possible errors to the views.

In the following example we will use the store method that before storing data to the DB is validating the request. The validation rule is simply for both name and details to have value. If not then the errors are collected in errors variable and passed to the view products/create with function with_errors(errors).

def store(self, request: Request, response: Response, validate: Validator):

        errors = request.validate(
            validate.required(['name', 'details']),
        )
        if errors:
            return response.redirect('/products/create').with_errors(errors)

        Product.create(
            name=request.input('name'),
            details=request.input('details'),

        )
        return response.redirect('/products')

Now we are ready to go to the relevant view, in our case this is /products/create and display the errors. We have 2 options:

  1. We can easily display our errors in our views with a snippet like this in the top of our page:
@if not errors.empty():
    <div class="alert alert-danger">
        <ul>
            @for error in errors.messages():
            <div class="text-danger"> 
                    <li>{{ error }}</li>
            </div>
            @endfor   
        </ul>
    </div>
@endif

image.png

  1. We can display the error message below the html input that validation is failing.
<div class="col-xs-12 col-sm-12 col-md-12">
     <div class="form-group">
          <strong>Name:</strong>
          <input type="text" name="name" class="form-control" placeholder="Name">
     </div>
@if errors.has('name')
     <div class="text-danger"> 
        <code>{{ errors.get('name')[0] }}</code>
     </div>
@endif
</div>

image.png

 
Share this