All Projects → daveoncode → pyvaru

daveoncode / pyvaru

Licence: MIT license
Rule based data validation library for python 3.

Programming Languages

python
139335 projects - #7 most used programming language

Projects that are alternatives of or similar to pyvaru

Awesome Python Models
A curated list of awesome Python libraries, which implement models, schemas, serializers/deserializers, ODM's/ORM's, Active Records or similar patterns.
Stars: ✭ 124 (+629.41%)
Mutual labels:  validation, model, validator
Nice Validator
Simple, smart and pleasant validation solution.
Stars: ✭ 587 (+3352.94%)
Mutual labels:  validation, validator, form-validation
Approvejs
A simple JavaScript validation library that doesn't interfere
Stars: ✭ 336 (+1876.47%)
Mutual labels:  validation, validator, form-validation
Formhelper
ASP.NET Core - Transform server-side validations to client-side without writing any javascript code. (Compatible with Fluent Validation)
Stars: ✭ 155 (+811.76%)
Mutual labels:  validation, validator, form-validation
Validator
The Validator component provides tools to validate values following the JSR-303 Bean Validation specification.
Stars: ✭ 2,238 (+13064.71%)
Mutual labels:  validation, validator
Joiful
TypeScript Declarative Validation for Joi
Stars: ✭ 177 (+941.18%)
Mutual labels:  validation, validator
Redux Form
A Higher Order Component using react-redux to keep form state in a Redux store
Stars: ✭ 12,597 (+74000%)
Mutual labels:  validation, form-validation
Validr
A simple, fast, extensible python library for data validation.
Stars: ✭ 205 (+1105.88%)
Mutual labels:  validation, validator
Formr
Create and Validate PHP Forms in Seconds.
Stars: ✭ 163 (+858.82%)
Mutual labels:  validation, form-validation
Validation
The power of Respect Validation on Laravel
Stars: ✭ 188 (+1005.88%)
Mutual labels:  validation, validator
Resolvers
📋 Validation resolvers: Zod, Yup, Joi, Superstruct, and Vest.
Stars: ✭ 222 (+1205.88%)
Mutual labels:  validation, form-validation
Validetta
A tiny jquery plugin for validate forms
Stars: ✭ 175 (+929.41%)
Mutual labels:  validation, form-validation
Validator
A tiny library for easily validating TextInputLayouts in Android
Stars: ✭ 169 (+894.12%)
Mutual labels:  validation, form-validation
We Validator
💯 简单灵活的表单验证插件,支持小程序、浏览器以及Nodejs端使用
Stars: ✭ 180 (+958.82%)
Mutual labels:  validation, validator
Ozzo Validation
An idiomatic Go (golang) validation package. Supports configurable and extensible validation rules (validators) using normal language constructs instead of error-prone struct tags.
Stars: ✭ 2,471 (+14435.29%)
Mutual labels:  validation, validator
Validot
Validot is a performance-first, compact library for advanced model validation. Using a simple declarative fluent interface, it efficiently handles classes, structs, nested members, collections, nullables, plus any relation or combination of them. It also supports translations, custom logic extensions with tests, and DI containers.
Stars: ✭ 198 (+1064.71%)
Mutual labels:  validation, validator
openui5-validator
A library to validate OpenUI5 fields
Stars: ✭ 17 (+0%)
Mutual labels:  validation, validator
ATGValidator
iOS validation framework with form validation support
Stars: ✭ 51 (+200%)
Mutual labels:  validator, form-validation
FilterInputJs
Tiny and Powerful Library for limit an entry (text box,input) as number,string or more...
Stars: ✭ 37 (+117.65%)
Mutual labels:  validator, form-validation
node-input-validator
Validation library for node.js
Stars: ✭ 74 (+335.29%)
Mutual labels:  validation, validator
https://travis-ci.org/daveoncode/pyvaru.svg?branch=master

What is pyvaru?

Pyvaru is a simple, flexible and unobtrusive data validation library for Python 3 (3.4+), based on the concept of validation rules.

From the software design point of view, a rule is a class implementing the strategy pattern, by encapsulating the validation logic in an interface method called apply().

The library already offers a series of common validation rules like:

  • TypeRule (it checks that the target value is an instance of the expected type)
  • FullStringRule (it checks the the target value is a string with content)
  • ChoiceRule (it checks that the target value is contained in a list of available options)
  • MinValueRule (it checks that the target value is >= x) *
  • MaxValueRule (it checks that the target value is <= x) *
  • MinLengthRule (it checks that the target value length is >= x) *
  • MaxLengthRule (it checks that the target value length is <= x) *
  • RangeRule (it checks that the target value is contained in a given range)
  • IntervalRule (it checks that the target value is contained in a given interval)
  • PatternRule (it checks that the target value matches a given regular expression)
  • PastDateRule (it checks that the target value is a date in the past)
  • FutureDateRule (it checks that the target value is a date in the future)
  • UniqueItemsRule (it checks that the target iterable does not contain duplicated items)

* where "x" is a provided reference value

The developer is then free to create his custom rules by extending the abstract ValidationRule and implementing the logic in the apply() method. For example:

class ContainsHelloRule(ValidationRule):
    def apply(self) -> bool:
        return 'hello' in self.apply_to

These rules are then executed by a Validator, which basically executes them in the provided order and eventually returns a ValidationResult containing the validation response.

Installation

pip install pyvaru

Usage

Given an existing model to validate, like the one below (but it could be a simple dictionary or any data structure since pyvaru does not make any assumption on the data format):

class User:
    def __init__(self, first_name: str, last_name: str, date_of_birth: datetime, sex: str):
        self.first_name = first_name
        self.last_name = last_name
        self.date_of_birth = date_of_birth
        self.sex = sex

We have to define a validator, by implementing the get_rules() method and for each field we want to validate we have to provide one or more proper rule(s).

from pyvaru import Validator
from pyvaru.rules import TypeRule, FullStringRule, ChoiceRule, PastDateRule

class UserValidator(Validator):
    def get_rules(self) -> list:
        user = self.data # type: User
        return [
            TypeRule(apply_to=user,
                     label='User',
                     valid_type=User,
                     error_message='User must be an instance of user model.',
                     stop_if_invalid=True),
            FullStringRule(lambda: user.first_name, 'First name'),
            FullStringRule(lambda: user.last_name, 'Last name'),
            ChoiceRule(lambda: user.sex, 'Sex', choices=('M', 'F')),
            PastDateRule(lambda: user.date_of_birth, 'Date of birth')
        ]

It's also possible to create groups of rules by using RuleGroup and avoid code duplication if multiple rules should be applied to the same field. So this code:

def get_rules(self) -> list:
    return [
        TypeRule(lambda: self.data.countries, 'Countries', valid_type=list),
        MinLengthRule(lambda: self.data.countries, 'Countries', min_length=1),
        UniqueItemsRule(lambda: self.data.countries, 'Countries')
    ]

can be replaced by:

def get_rules(self) -> list:
    return [
        RuleGroup(lambda: self.data.countries,
                  'Countries',
                  rules=[(TypeRule, {'valid_type': list}),
                         (MinLengthRule, {'min_length': 1}),
                         UniqueItemsRule])
    ]

Finally we have two choices regarding how to use our custom validator:

  1. As a context processor:
with UserValidator(user):
    # do whatever you want with your valid model

In this case the code inside with will be executed only if the validation succeed, otherwise a ValidationException (containing a validation_result property with the appropriate report) is raised.

  1. By invoking the validate() method (which returns a ValidationResult)
validation = UserValidator(user).validate()
if validation.is_successful():
    # do whatever you want with your valid model
else:
    # you can take a proper action and access validation.errors
    # in order to provide a useful message to the application user,
    # write logs or whatever

Assuming we have a instance of an User configured as the one below:

user = User(first_name=' ',
            last_name=None,
            date_of_birth=datetime(2020, 1, 1),
            sex='unknown')

By running a validation with the previous defined rules we will obtain a ValidationResult with the following errors:

{
    'First name': ['String is empty.'],
    'Last name': ['Not a string.'],
    'Sex': ['Value not found in available choices.'],
    'Date of birth': ['Not a past date.']
}

Full API Documentation

Go to: http://pyvaru.readthedocs.io/en/latest/contents.html

Credits

Pyvaru is developed and maintained by Davide Zanotti.

Blog: http://www.daveoncode.com

Twitter: https://twitter.com/daveoncode

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