Validating a form in Masonite

90 Views Asked by At

I'm trying to use the validator engine in Masonite to validate form data. Each validator works by itself, but when I try and chain a bunch of validators together it doesn't work.

       errors = request.validate(
            validate.when(
                validate.exists(['title', 'body', 'lat', 'lon'])
            ).then(
                validate.string(['title', 'body']),
                # regex to validate a float
                validate.regex(['lat', 'lon'], pattern='[+-]?(?=\d*[.eE])(?=\.?\d)\d*\.?\d*(?:[eE][+-]?\d+)?')
            ))
       if errors:
            return response.redirect('/create-post').with_errors(errors)

The validator above allows me to submit an empty form (it shouldn't, but it doesn't seem to be performing the 'validate.exists' check), but if I enter data into each form field, the 'validate.regex' seems to work against the lat and lon data as it should.

I'm not quite sure what I'm doing wrong here?

1

There are 1 best solutions below

0
On BEST ANSWER

This does however work. Check the form with validate.required first, and then if there are no errors, check it with validate.regex.

errors = request.validate(
            validate.required(['title', 'body', 'lat', 'lon']))
        if not errors:
            errors = request.validate(
                validate.regex(['lat', 'lon'], pattern='[+-]?(?=\d*[.eE])(?=\.?\d)\d*\.?\d*(?:[eE][+-]?\d+)?'))