DEV Community

Cover image for How to create a PHP validator.
m1000
m1000

Posted on

How to create a PHP validator.

Ok…
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.

For this you must know the basics of:
*OOP
*PHP 7.x
First of all we need a basic form with some fields (create your own or just copy it from below).
Alt Text
Alt Text

Let’s create our class helper Validator.php

Alt Text

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

Alt Text

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

Alt Text
Alt Text

And thats how we created our own validator in PHP.
Happy coding!

Top comments (2)

Collapse
 
darkain profile image
Vincent Milum Jr

Just a note: you shouldn't use regex to validate email addresses. There are some assumptions made in that regex that'll prevent valid email addresses from working.

ex-parrot.com/~pdw/Mail-RFC822-Add...

This is especially true in PHP, which has the ability to validate common data types built in. There is no need to reinvent the wheel :)

php.net/manual/en/filter.examples....

Collapse
 
m1000 profile image
m1000

just after post did reslise that.
This is an old Code but thanks for reading