Skip to content

benjamintemitope/Simple-PHP-Validator

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

28 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Simple Validator File

Use for PHP Validation

Description

validate(array $_POST, array $fields, array $rules [,array $messages]) :array|bool

Validate Data

Parameters

  • $_POST Form Data
  • $fields Validation Fields
  • $rules Validation Rules
  • $messages (optional) Validation Messages

Return Values

array

Example

// validator
require_once __DIR__ . '/validator.php';

// data
$_POST['username'] = "j";
$_POST['email'] = "johndoe@example";
$_POST['password'] = "pass";
$_POST['remember_me'] = "";

// fields
$fields = ['username', 'email','password', 'remember_me'];

// rules
$rules = [
    'username' => [
        'required', 'min' => 3
    ],
    'email' => [
        'required', 'email'
    ],
    'password' => [
        'required', 'min' => 5, 'max' => 15
    ],
    'remember_me' => [
      'nullable'
    ]
];

// custom error messages
$messages = [
    'username' => [
        'required' => "Username is required.",
        'min' => "Username should be minimum of :min characters."
    ],
    'email' => [
        'required' => "Email is required.",
        'email' => "Provide a valid email address."
    ],
    'password' => [
        'required' => "Password is required.",
        'min' => "Password should be minimum of :min characters.",
        'max' => "Password should be maximum of :max characters."
    ]
];

$errors = validate($_POST, $fields, $rules, $messages);

if (!empty($errors)) {
    echo '<pre> '. print_r($errors, true ) .'</pre>';exit;
}

echo "No error found!.";

Run Server

php -S localhost:8000 -t src/

Now you can visit http://localhost:8000/ in your browser to view the output of this example.

Rules Available

Rule Usage
Required required
Email email
Minimum min => value
Maximum max => value
Alphabetic alpha
Alphanumeric alphanumeric
Array array
String string
Numeric numeric
Lowercase lower
Uppercase upper
Hexadecimal hexadec
Nullable nullable

Notes

  • When using the nullable rule, let it be the first rule assigned to the field.

  • numeric rule works effectively with string. Why?

About

A Simple Validator File

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Languages