How to create a PHP validator.

When i started with web development the first language i touched was PHP, i started creating simple form data inputs with some fields like:

  • Name
  • Email
  • Phone number
  • etc.

And yes, they “work” but what happens when the users give us wrong data? and we dont want to use HTML’s validation tags because they are unsafe.

So i’ve decided to create my own Validator (no, not like Laravel validator).

So… lets start.

  • OOP
  • PHP 7.x

First of all we need a basic form with some fields (create your own or just copy it from below).

login.php (code)
login.php (view)

Let’s create our class helper Validator.php

Validator.php helper

Nice! so let’s work on our someAction.php file.

someAction.php file

Great! we only need to display those errors on login.php file adding some php script.

Displaying errors.

And thats how we created our own validator in PHP.

Happy coding!

Mexican webdev, father and son.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store