Scout APM is PHP application performance monitoring designed for developers. With tracing logic that ties issues back to the line of code causing them, you can pinpoint n+1 queries, memory leaks, and other abnormalities in real time so you can knock them out and get back to building a great product. Start your free 14-day trial today and get the performance insight you need in less than 4 minutes.

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

Original – by Freek Van der Herten – 2 minute read

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.

Stay up to date with all things Laravel, PHP, and JavaScript.

Follow me on Twitter. I regularly tweet out programming tips, and what I myself have learned in ongoing projects.

Every two weeks I send out a newsletter containing lots of interesting stuff for the modern PHP developer.

Expect quick tips & tricks, interesting tutorials, opinions and packages. Because I work with Laravel every day there is an emphasis on that framework.

Rest assured that I will only use your email address to send you the newsletter and will not use it for any other purposes.