Package: validator
ValidatorValidator is a Python library for dealing with request validating.Table of ContentsInstallationOverviewUsageValidated Data/Error MessagesValidating ArraysAvailable Validation RulesRulesRules InterconnectionCustom RulesExamplesContributingLicenseInstallationUse the package managerpipto install Validator.pipinstallvalidatorUsageUser should pass request dictionary and rules dictionary for validating data in the request.Please see examples below:fromvalidatorimportvalidaterequest={"name":"John Doe","age":33,"mail":"john_doe@gmail.com"}rules={"name":"required","age":"integer|min:18","mail":"required|mail"}result=validate(request,rules)# Truevalidate()returns either True or False.Another option is to useValidatorclassfromvalidatorimportValidatorrequest={...}rules={...}val=Validator(request,rules)result=val.validate()# TrueValidated Data/Error MessagesValidator allows user to have a look at failed validations and passed validations.validated_datais 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 Datafromvalidatorimportvalidaterequest={"first_name":"John","last_name":"Doe","age":33,"mail":"johndoe@gmail.com","_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 = Truevalidated_data = {"first_name": "John","last_name": "Doe","age": 33,"mail": "johndoe@gmail.com"}"""Error Messagesfromvalidatorimportvalidaterequest={"name":"","mail":"john_doe"}rule={"name":"required","mail":"mail"}result,_,errors=validate(request,rule,return_info=True)"""result = Falseerrors = {"name": {"Required': "Field was empty"},"mail": {"Mail': "Expected a Mail, Got: john_doe"}}"""Or you can useValidatorclass 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 ArraysValidator comes withvalidate_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:fromvalidatorimportvalidate_manyrequests=[{"name":"John"},{"name":"Rob"},{"name":"Tom"},{"name":"Greg"}]rule={"name":"required|min:3"}result=validate_many(requests,rule)# TrueWe 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:fromvalidatorimportvalidate_manyrequests=[{"name":"John"},{"name":""},{"name":"Yo"},{"name":"Greg"}]rule={"name":"required|min:3"}result,errors=validate_many(requests,rule,return_info=True)"""result = Falseerrors = [{},{"name": {"Min": "Expected Maximum: 3, Got: 0", "Required": "Field was empty"}},{"name": {"Min": "Expected Maximum: 3, Got: 2"}},{}]"""Available Validation RulesValidator comes with pre initialized rules.All of rules are listed inRULES.mdfileRulesValidator Rules can be used in different ways. Please see some examples below:Stringsrule={"name":"required","age":"integer|min:18","mail":"required|mail"}Array of Stringsrule={"name":["required"],"age":["integer","min:18"],"mail":["required","mail"]}Array of RulesfromvalidatorimportrulesasRrules={"name":[R.Required()],"age":[R.Integer(),R.Min(18)],"mail":[R.Requried(),R.Mail()]}Other MiscellaneousfromvalidatorimportrulesasRrules={"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 ruleRules InterconnectionRules can affect each other. Let's take a look atSizerule. 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 = Falseerrors = {"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)# TrueFor more details please viewSizeRuleCustom RulesWe give users ability to advance and use their own checkers. Write function and use is as a rule. See examples below:Use defined functions:fromvalidatorimportvalidatedeffunc_age(x):returnx>=18req={"age":30}rules={"age":func_age}validate(req,rules)Use Lambda functions:fromvalidatorimportvalidatereq={"age":30}rules={"age":lambdax:x>=18}validate(req,rules)Any callable class(NOTE: Pass class instance and not class itself):fromvalidatorimportvalidateclasschecker:def__init__(self):passdef__call__(self,x):returnx>=456req={"age":30}rules={"age":checker()}validate(req,rules)Custom Rule:fromvalidatorimportvalidatefromvalidator.rulesimportRuleclassAgeRule(Rule):def__init__(self,min):Rule.__init__(self)self.min=mindefcheck(self,arg):returnself.min<=argreq={"age":30}rules={"age":AgeRule(18)}validate(req,rules)ExamplesWe have written some examples for you to get started easier. Please viewExamplesfolder, where you can find validator usages with frameworks like Flask, Django and etc.ContributingPull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.Please seeCONTRIBUTING.mdbefore making PR :)LicenseMIT