All Projects → CSenshi → Validator

CSenshi / Validator

Licence: MIT License
Easy-to-use, Highly Configurable Python Data Validator. Inspired by Laravel Validator

Programming Languages

python
139335 projects - #7 most used programming language

Labels

Projects that are alternatives of or similar to Validator

crystal-validator
💎 Data validation module for Crystal lang
Stars: ✭ 23 (-43.9%)
Mutual labels:  validator
Saudi-ID-Validator
Saudi-ID-Validator (Swift, Kotlin, Java, Go, JS, Python, TypeScript, PHP, Scala, ruby, c#, vb, SQL)
Stars: ✭ 53 (+29.27%)
Mutual labels:  validator
pyvaru
Rule based data validation library for python 3.
Stars: ✭ 17 (-58.54%)
Mutual labels:  validator
persianize-node
Persianize is set of nodejs tools for validating and converting data to correct Persian.
Stars: ✭ 13 (-68.29%)
Mutual labels:  validator
UE4-BUIValidator
UE4 UI Texture Validator Plugin
Stars: ✭ 48 (+17.07%)
Mutual labels:  validator
node-input-validator
Validation library for node.js
Stars: ✭ 74 (+80.49%)
Mutual labels:  validator
schema
SpaceAPI JSON schema files.
Stars: ✭ 20 (-51.22%)
Mutual labels:  validator
notional
Full Documentation of Notional's systems
Stars: ✭ 31 (-24.39%)
Mutual labels:  validator
validation
A validation library for PHP that uses the notification pattern
Stars: ✭ 27 (-34.15%)
Mutual labels:  validator
amazon-ecs-exec-checker
🚀 Pre-flight checks for ECS Exec
Stars: ✭ 364 (+787.8%)
Mutual labels:  validator
wallet-address-validator
Useful library for validation of Bitcoin, Litecoin, Ethereum and other cryptocoin addresses
Stars: ✭ 240 (+485.37%)
Mutual labels:  validator
bpmnlint
Validate BPMN diagrams based on configurable lint rules.
Stars: ✭ 82 (+100%)
Mutual labels:  validator
openui5-validator
A library to validate OpenUI5 fields
Stars: ✭ 17 (-58.54%)
Mutual labels:  validator
laravel-vatvalidator
Package to validate a vat id via the api of the european union (vies)
Stars: ✭ 15 (-63.41%)
Mutual labels:  validator
filter
Go语言的数据过滤包,由 数据输入、格式化、校验、输出 几个部份组成。
Stars: ✭ 22 (-46.34%)
Mutual labels:  validator
wily
Build Node.js APIs from the command line (Dead Project 😵)
Stars: ✭ 14 (-65.85%)
Mutual labels:  validator
validation
Aplus Framework Validation Library
Stars: ✭ 99 (+141.46%)
Mutual labels:  validator
easiest-js-validator
The easiest way to validate your forms without 3rd party packages
Stars: ✭ 53 (+29.27%)
Mutual labels:  validator
ty
Here is a schema checker which can return well typed results. Tell your friends!
Stars: ✭ 21 (-48.78%)
Mutual labels:  validator
Maat
Validation and transformation library powered by deductive ascending parser. Made to be extended for any kind of project.
Stars: ✭ 27 (-34.15%)
Mutual labels:  validator

Validator

Validator is a Python library for dealing with request validating.

Table of Contents

Installation

Use the package manager pip to install Validator.

pip install validator

Usage

User should pass request dictionary and rules dictionary for validating data in the request.

Please see examples below:

from validator import validate

request = {"name": "John Doe",
           "age": 33,
           "mail": "[email protected]"}

rules = {"name": "required",
         "age": "integer|min:18",
         "mail": "required|mail"}

result = validate(request, rules) # True

validate() returns either True or False.

Another option is to use Validator class

from validator import Validator

request = {...}
rules = {...}

val = Validator(request, rules)
result = val.validate() # True

Validated Data/Error Messages

Validator allows user to have a look at failed validations and passed validations. validated_data is extremly useful when request contains data that is not needed for initialization of model, you can get rid of them and validate at the same time. See examples below:

  • Validated Data

    from validator import validate
    
    request = {"first_name": "John",
               "last_name": "Doe",
               "age": 33,
               "mail": "[email protected]",
               "_token": "WpH0UPfy0AXzMtK2UWtJ",
               "_cookie_data": "e9Uixp8hzUySy6bw3MuZ",
               "_session_id": "ZB7q7uIVdWBKgSCSSWAa"}
    
    rule = {"first_name": "required",
            "last_name": "required",
            "age": "required|min:18",
            "mail": "required|mail"}
    
    result, validated_data, _ = validate(request, rule, return_info=True)
    """
    result = True
    validated_data = {"first_name": "John",
                      "last_name": "Doe",
                      "age": 33,
                      "mail": "[email protected]"}
    """
  • Error Messages

    from validator import validate
    
    request = {"name": "",
               "mail": "john_doe"}
    
    rule = {"name": "required",
            "mail": "mail"}
    
    result, _, errors = validate(request, rule, return_info=True)
    
    """
    result = False
    errors = {"name": {"Required': "Field was empty"},
              "mail": {"Mail': "Expected a Mail, Got: john_doe"}}
    """

Or you can use Validator class for error messages as well as for validated data.

val = Validator(request, rules)
result = val.validate()
validated_data = val.get_validated_data()
errors = val.get_errors()

Validating Arrays

Validator comes with validate_many() function, which validates multiple requests. Function takes list of requests and one rule. This rule is checked for all the requests. If one or more requests fail validation function returns False, otherwise (if all pass) True. For more details see example below:

Validation Passes:

from validator import validate_many

requests = [{"name": "John"},
            {"name": "Rob"},
            {"name": "Tom"},
            {"name": "Greg"}]
rule = {"name": "required|min:3"}

result = validate_many(requests, rule) # True

We can also have a look at failed validations and error messages. validate_many() takes third argument as boolean, indicating return of error messages.

Validation Fails:

from validator import validate_many

requests = [{"name": "John"},
            {"name": ""},
            {"name": "Yo"},
            {"name": "Greg"}]
rule = {"name": "required|min:3"}

result, errors = validate_many(requests, rule, return_info=True)
"""
result = False
errors = [{},
          {"name": {"Min": "Expected Maximum: 3, Got: 0", "Required": "Field was empty"}},
          {"name": {"Min": "Expected Maximum: 3, Got: 2"}},
          {}]
"""

Available Validation Rules

Validator comes with pre initialized rules. All of rules are listed in RULES.md file

Rules

Validator Rules can be used in different ways. Please see some examples below:

Strings

rule = {"name": "required",
        "age": "integer|min:18",
        "mail": "required|mail"}

Array of Strings

rule = {"name": ["required"],
        "age": ["integer", "min:18"],
        "mail": ["required", "mail"]}

Array of Rules

from validator import rules as R

rules = {"name": [R.Required()],
         "age": [R.Integer(), R.Min(18)],
         "mail": [R.Requried(), R.Mail()]}

Other Miscellaneous

from validator import rules as R

rules = {"name": R.Required(),           # no need for Array Brackets if one rule
         "age": [R.Integer, R.Min(18)],
         "mail": [R.Requried, R.Mail]}   # no need for class initialization with brakcets () 
                                        # if no arguments are passed to rule

Rules Interconnection

Rules can affect each other. Let's take a look at Size rule. It takes 1 argument and checks if data is equal to given value (example: 'size:10').

  • Case 1: checks for length of '18' to be 18. len('18') is 2, therefore it is False.
request = {"age" : "18"}
rule = {"age" : "size:18"}

validate(request, rule)
"""
result = False
errors = {"age": {"Size": "Expected Size:18, Got:2"}}
"""
  • Case 2: checks if int representation of '18' is equal to 18. (int('18') = 18), therefore it is True.
request = {"age" : "18"}
rule = {"age" : "integer|size:18"}

validate(request, rule) # True

For more details please view Size Rule

Custom Rules

We give users ability to advance and use their own checkers. Write function and use is as a rule. See examples below:

  1. Use defined functions:
    from validator import validate
    
    def func_age(x):
        return x >= 18
    
    req = {"age": 30}
    rules = {"age": func_age}
    
    validate(req, rules)
  2. Use Lambda functions:
    from validator import validate
    
    req = {"age": 30}
    rules = {"age": lambda x: x >= 18}
    
    validate(req, rules)
  3. Any callable class (NOTE: Pass class instance and not class itself):
    from validator import validate
    
    class checker:
      def __init__(self):
          pass
    
      def __call__(self, x):
          return x >= 456
    
    req = {"age": 30}
    rules = {"age": checker()}
    
    validate(req, rules)
  4. Custom Rule:
    from validator import validate
    from validator.rules import Rule
    
    class AgeRule(Rule):
        def __init__(self, min):
            Rule.__init__(self)
            self.min = min
    
        def check(self, arg):
            return self.min <= arg
    
    req = {"age": 30}
    rules = {"age": AgeRule(18)}
    
    validate(req, rules)

Examples

We have written some examples for you to get started easier. Please view Examples folder, where you can find validator usages with frameworks like Flask, Django and etc.

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please see CONTRIBUTING.md before making PR :)

License

MIT

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].