All Projects → cangelis → simple-validator

cangelis / simple-validator

Licence: MIT license
Simple Validator is an awesome and easy to use validator for php

Programming Languages

PHP
23972 projects - #3 most used programming language

Projects that are alternatives of or similar to simple-validator

Stringformatter
Simple Text Formetter (Credit Card Number, Phone Number, Serial Number etc.) Can be used in all text inputs according to the format pattern. If desired, large minor character restrictions can be made in the format pattern.
Stars: ✭ 231 (+216.44%)
Mutual labels:  validator
gulp-html
Gulp plugin for HTML validation, using the official Nu Html Checker (v.Nu)
Stars: ✭ 70 (-4.11%)
Mutual labels:  validator
FilterInputJs
Tiny and Powerful Library for limit an entry (text box,input) as number,string or more...
Stars: ✭ 37 (-49.32%)
Mutual labels:  validator
rust-phonenumber
Library for parsing, formatting and validating international phone numbers.
Stars: ✭ 99 (+35.62%)
Mutual labels:  validator
cron-validate
A cron-expression validator for TypeScript/JavaScript projects.
Stars: ✭ 40 (-45.21%)
Mutual labels:  validator
kontrolio
Simple standalone data validation library inspired by Laravel and Symfony
Stars: ✭ 51 (-30.14%)
Mutual labels:  validator
Copper
A configuration file validator for Kubernetes.
Stars: ✭ 223 (+205.48%)
Mutual labels:  validator
Hammer
Simple, reliable FHIR validator
Stars: ✭ 27 (-63.01%)
Mutual labels:  validator
garn-validator
Create validations with ease
Stars: ✭ 42 (-42.47%)
Mutual labels:  validator
yii2-at-least-validator
Makes one or more attributes mandatory inside a set of attributes.
Stars: ✭ 28 (-61.64%)
Mutual labels:  validator
guice-validator
Guice javax.validation method validation integration
Stars: ✭ 35 (-52.05%)
Mutual labels:  validator
finspec-spec
Multi-protocol, machine-readable specifications for financial services
Stars: ✭ 18 (-75.34%)
Mutual labels:  validator
validation
Developer experience focused validator.
Stars: ✭ 15 (-79.45%)
Mutual labels:  validator
another-json-schema
Another JSON Schema validator, simple & flexible & intuitive.
Stars: ✭ 48 (-34.25%)
Mutual labels:  validator
fake-numbers
Generate fake, valid numbers. Check if a number is valid. Support a lot of different numbers: Credit card, EAN, ISBN, RTN, VIN, etc.
Stars: ✭ 51 (-30.14%)
Mutual labels:  validator
Clamav Validator
Laravel virus validator based on ClamAV anti-virus scanner
Stars: ✭ 224 (+206.85%)
Mutual labels:  validator
djburger
Framework for safe and maintainable web-projects.
Stars: ✭ 75 (+2.74%)
Mutual labels:  validator
valite
🔥 Concurrently execute your validators in a simple, practical and light validator engine.
Stars: ✭ 20 (-72.6%)
Mutual labels:  validator
hey-validator
Data validator
Stars: ✭ 14 (-80.82%)
Mutual labels:  validator
ATGValidator
iOS validation framework with form validation support
Stars: ✭ 51 (-30.14%)
Mutual labels:  validator

Simple Validator Documentation

Build Status

Validation is the process that checks for correctness, meaningfulness and security of the input data. SimpleValidator is a library that handles validation process easily.

Install

Including to your current composer.json

Add this line into require in your composer.json:

"simple-validator/simple-validator": "1.0.*"

and call

php composer.phar update

Installing directly

Download composer.phar and call

php composer.phar install

and use autoload.php to include the classes

require 'vendor/autoload.php'

A few examples:

<?php
$rules = [
    'name' => [
        'required',
        'alpha',
        'max_length(50)'
    ],
    'age' => [
        'required',
        'integer',
    ],
    'email' => [
        'required',
        'email'
    ],
    'password' => [
        'required',
        'equals(:password_verify)'
    ],
    'password_verify' => [
        'required'
    ]
];
$validation_result = SimpleValidator\Validator::validate($_POST, $rules);
if ($validation_result->isSuccess() == true) {
    echo "validation ok";
} else {
    echo "validation not ok";
    var_dump($validation_result->getErrors());
}

Custom Rules with anonymous functions

Anonymous functions make the custom validations easier to be implemented.

Example

$rules = [
    'id' => [
        'required',
        'integer',
        'post_exists' => function($input) {
            $query = mysqli_query("SELECT * FROM post WHERE id = " . $input);
            if (mysqli_num_rows($query) == 0)
                return false;
            return true;
        },
        'between(5,15)' => function($input, $param1, $param2) {
            if (($input > $param1) && ($input < $param2))
                return true;
            return false;
        }
    ]
];

and you need to add an error text for your rule to the error file (default: errors/en.php).

'post_exists' => "Post does not exist"

or add a custom error text for that rule

$validation_result->customErrors([
    'post_exists' => 'Post does not exist'
]);

Another example to understand scoping issue

// my local variable
$var_to_compare = "1234";
$rules = [
    'password' => [
        'required',
        'integer',
        // pass my local variable to anonymous function
        'is_match' => function($input) use (&$var_to_compare) {
            if ($var_to_compare == $input)
                return true;
            return false;
        }
    ]
];

Custom Validators

You can assume SimpleValidator as a tool or an interface to create a validator for yourself.

Custom validators can have their own rules, own error files or default language definitions. In addition, you can override default rules in your custom validator.

class MyValidator extends \SimpleValidator\Validator {

    // methods have to be static !!!
    protected static function is_awesome($input) {
        if ($input == "awesome")
            return true;
        return false;
    }

    // overriding a default rule (url)
    protected static function url($input) {
        return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $input);
    }

    // set default language for your validator
    // if you don't override this method, the default language is "en"
    protected function getDefaultLang() {
        return getMyApplicationsDefaultLanguage();
    }

    // defining error files for your validator
    // in this example your files should live in "{class_path}/errors/{language}/validator.php
    protected function getErrorFilePath($lang) {
        return __DIR__ . "/errors/" . $lang . "/validator.php";
    }

}

Create an error file:

return [
    'is_awesome' => 'the :attribute is not awesome'
    // error text for url is already defined in default error text file you don't have to define it here, but optionally you can
];

And then, call the validate method.

$rules = [
    'website' => [
        'is_awesome',
        'url'
    ]
];
$validation_result = MyValidator::validate($_POST, $rules);

Custom Rule parameters

A rule can have multiple parameters. An example:

$rule = [
    'id' => [
        'rule1(:input1,:input2,2,5,:input3)' => function($input, $input1, $input2, $value1, $value2, $input3) {
            // validation here
        }
    ],
    // and so on..
];

Custom Error messages

Using Error file

Custom rules provides localization for the error messages. Create a new file under errors folder, example: errors/es.php and call getErrors() method using:

$validation_result->getErrors('es');

Using customErrors method

You can add custom errors using customErrors method.

Examples:

$validation_result->customErrors([
    // input_name.rule => error text
    'website.required' => 'We need to know your web site',
    // rule => error text
    'required' => ':attribute field is required',
    'name.alpha' => 'Name field must contain alphabetical characters',
    'email_addr.email' => 'Email should be valid',
    'email_addr.min_length' => 'Hey! Email is shorter than :params(0)',
    'min_length' => ':attribute must be longer than :params(0)'
]);

Naming Inputs

$naming => [
    'name' => 'Name',
    'url' => 'Web Site',
    'password' => 'Password',
    'password_verify' => 'Password Verification'
];
$validation_result = SimpleValidator\Validator::validate($_POST, $rules, $naming);

Output sample:

  • Name field is required -instead of "name field is required"-
  • Web Site field is required -instead of "url field is required"-
  • Password field should be same as Password Verification -equals(:password_verify) rule-

More

You can explicitly check out the validations using has method that might be useful for Unit Testing purposes.

// All return boolean
$validation_result->has('email');
$validation_result->has('email','required');
$validation_result->has('password','equals');

Default validations

Rule Parameter Description Example
required No Returns FALSE if the input is empty
numeric No Returns FALSE if the input is not numeric
email No Returns FALSE if the input is not a valid email address
integer No Returns FALSE if the input is not an integer value
float No Returns FALSE if the input is not a float value
alpha No Returns FALSE if the input contains non-alphabetical characters
alpha_numeric No Returns FALSE if the input contains non-alphabetical and numeric characters
ip No Returns FALSE if the input is not a valid IP (IPv6 supported)
url No Returns FALSE if the input is not a valid URL
max_length Yes Returns FALSE if the input is longer than the parameter max_length(10)
min_length Yes Returns FALSE if the input is shorter than the parameter min_length(10)
exact_length Yes Returns FALSE if the input is not exactly parameter value long exact_length(10)
equals Yes Returns FALSE if the input is not same as the parameter equals(:password_verify) or equals(foo)
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].