Every two weeks I send out a newsletter containing lots of interesting stuff for the modern PHP developer. You can expect quick tips, links to interesting tutorials, opinions and packages. Want to learn the cool stuff? Then sign up now!

An easy way to validate front end forms using back end logic

Imagine you’re building an single page application that has a couple of forms. How are you going to validate those forms? Because we don’t want to refresh the page submitting the form as usual isn’t possible. Adding validation logic to the JavaScript side of things would just duplicate the validation logic already present on the server. Wouldn’t it be nice if we could validate our front end forms using back end logic?

A while ago Jeffrey Way published a lesson on Object-Oriented forms in the Vue 2.0 series that does just that. Because I wanted to use Jeffrey’s way of doing things in some real life projects I decided to put his code (and some extra niceties) in JavaScript package called spatie/form-backend-validation. Though it could work in other frameworks it is primarily built with a Laravel back end in mind.

To get started using the package it’s best to watch the aforementioned free video on Object-Oriented forms. That’ll explain the train of thought behind it. In short the package provides a Form class to submit all form values to the server. It will collect any errors the server sends back. Using a Vue component we can easily collect all values and display all errors. And this can all happen without having to refresh the page.

To help you understand it even better, we’ve created an example app in which the package is installed. These are the most important pieces:

If you set up the example app and hit it the / route of the app you’ll see a form for you to toy around with.

Hopefully this Form class can be of use in your projects as well. We’ve only made a couple of JavaScript packages before, but I can image a few more will pop up in the future.

Freek Van der Herten is a partner and developer at Spatie, an Antwerp based company that specializes in creating web apps with Laravel. After hours he writes about modern PHP and Laravel on this blog. When not coding he’s probably rehearsing with his kraut rock band.
  • All this stuff is very similar to the Laravel Spark code validation. Pretty cool if we can now export it and use it in any projects !