Package: validator-collection
Python library of 60+ commonly-used validator functionsBranchUnit Testslatestv. 1.5v. 1.4v. 1.3v. 1.2v. 1.1v. 1.0developTheValidator Collectionis a Python library that provides more than 60
functions that can be used to validate the type and contents of an input value.Each function has a consistent syntax for easy use, and has been tested on
Python 2.7, 3.4, 3.5, 3.6, 3.7, and 3.8.For a list of validators available, please see the lists below.COMPLETE DOCUMENTATION ON READTHEDOCS:http://validator-collection.readthedocs.io/en/latestContentsInstallationAvailable Validators and CheckersValidatorsCheckersHello, World and Standard UsageUsing ValidatorsWhen Validation FailsDisabling ValidationUsing CheckersDisabling CheckingBest PracticesDefensive Approach: Check, then Convert if NecessaryConfident Approach: try … exceptQuestions and IssuesContributingTestingLicenseInstallationTo install theValidator Collection, just execute:$pipinstallvalidator-collectionDependencies:Python 3.xPython 2.7jsonschemafor JSON Schema Validation.jsonschemafor JSON Schema Validation.Theregexdrop-in replacement for
Python’s (buggy) standardremodule.Conditional dependencies will be automatically installed if you are
installing to Python 2.x.Available Validators and CheckersValidatorsSEE:Validator ReferenceCoreDate/TimeNumbersFile-relatedInternet-relateddictdatenumericbytesIOemailjsondatetimeintegerstringIOurlstringtimefloatpathdomainiterabletimezonefractionpath_existsip_addressnonetimedeltadecimalfile_existsipv4not_emptydirectory_existsipv6uuidreadablemac_addressvariable_namewriteablemimetypeexecutableCheckersSEE:Checker ReferenceCoreDate/TimeNumbersFile-relatedInternet-relatedis_typeis_dateis_numericis_bytesIOis_emailis_betweenis_datetimeis_integeris_stringIOis_urlhas_lengthis_timeis_floatis_pathlikeis_domainare_equivalentis_timezoneis_fractionis_on_filesystemis_ip_addressare_dicts_equivalentis_timedeltais_decimalis_fileis_ipv4is_dictis_directoryis_ipv6is_jsonis_readableis_mac_addressis_stringis_writeableis_mimetypeis_iterableis_executableis_not_emptyis_noneis_callableis_uuidis_variable_nameHello, World and Standard UsageAll validator functions have a consistent syntax so that using them is pretty
much identical. Here’s how it works:fromvalidator_collectionimportvalidators,checkers,errorsemail_address=validators.email('test@domain.dev')# The value of email_address will now be "test@domain.dev"email_address=validators.email('this-is-an-invalid-email')# Will raise a ValueErrortry:email_address=validators.email(None)# Will raise an EmptyValueErrorexcepterrors.EmptyValueError:# Handling logic goes hereexcepterrors.InvalidEmailError:# More handlign logic goes hereemail_address=validators.email(None,allow_empty=True)# The value of email_address will now be Noneemail_address=validators.email('',allow_empty=True)# The value of email_address will now be Noneis_email_address=checkers.is_email('test@domain.dev')# The value of is_email_address will now be Trueis_email_address=checkers.is_email('this-is-an-invalid-email')# The value of is_email_address will now be Falseis_email_address=checkers.is_email(None)# The value of is_email_address will now be FalsePretty simple, right? Let’s break it down just in case: Each validator comes in
two flavors: a validator and a checker.Using ValidatorsSEE:Validator ReferenceA validator does what it says on the tin: It validates that an input value is
what you think it should be, and returns its valid form.Each validator is expressed as the name of the thing being validated, for exampleemail().Each validator accepts a value as its first argument, and an optionalallow_emptyboolean as its second argument. For example:email_address=validators.email(value,allow_empty=True)If the value you’re validating validates successfully, it will be returned. If
the value you’re validating needs to be coerced to a different type, the
validator will try to do that. So for example:validators.integer(1)validators.integer('1')will both return anintof1.If the value you’re validating is empty/falsey andallow_emptyisFalse,
then the validator will raise aEmptyValueErrorexception (which inherits from
the built-inValueError). Ifallow_emptyisTrue, then an empty/falsey
input value will be converted to aNonevalue.CAUTION:By default,allow_emptyis always set toFalse.HINT:Some validators (particularly numeric ones likeinteger) have additional
options which are used to make sure the value meets criteria that you set for
it. These options are always included as keyword argumentsaftertheallow_emptyargument, and are documented for each validator below.When Validation FailsValidators raise exceptions when validation fails. All exceptions raised inherit
from built-in exceptions likeValueError,TypeError, andIOError.If the value you’re validating fails its validation for some reason, the validator
may raise different exceptions depending on the reason. In most cases, this will
be a descendent ofValueErrorthough it can sometimes be aTypeError, or anIOError, etc.For specifics on each validator’s likely exceptions and what can cause them, please
review theValidator ReferenceHINT:While validators will always raise built-in exceptions from the standard library,
to give you greater programmatic control over how to respond when validation
fails, we have defined a set of custom exceptions that inherit from those
built-ins.Our custom exceptions provide you with very specific, fine-grained information
as towhyvalidation for a given value failed. In general, most validators
will raiseValueErrororTypeErrorexceptions, and you can safely catch those
and be fine. But if you want to handle specific types of situations with greater
control, then you can instead catchEmptyValueError,CannotCoerceError,MaximumValueError, and the like.For more detailed information, please see:Error ReferenceValidator ReferenceDisabling ValidationCAUTION:If you aredisabling validatorsusing theVALIDATORS_DISABLEDenvironment variable, their related checkers willalsobe disabled (meaning they will always returnTrue).Validation can at times be an expensive (in terms of performance) operation. As
a result, there are times when you want to disable certain kinds of validation
when running in production. Using theValidator-Collectionthis is simple:Just add the name of the validator you want disabled to theVALIDATORS_DISABLEDenvironment variable, and validation will automatically be skipped.CAUTION:VALIDATORS_DISABLEDexpects a comma-separated list of values. If it isn’t
comma-separated, it won’t work properly.Here’s how it works in practice. Let’s say we define the following environment
variable:$exportVALIDATORS_DISABLED="variable_name, email, ipv4"This disables thevariable_name(),email(), andipv4()validators respectively.Now if we run:fromvalidator_collectionimportvalidators,errorstry:result=validators.variable_name('this is an invalid variable name')exceptValueError:# handle the errorThe validator will return thevaluesupplied to it un-changed. So that meansresultwill be equal tothis is an invalid variable name.However, if we run:fromvalidator_collectionimportvalidators,errorstry:result=validators.integer('this is an invalid variable name')excepterrors.NotAnIntegerError:# handle the errorthe validator will run and raiseNotAnIntegerError.We can force validators to run (even if disabled using the environment variable)
by passing aforce_run = Truekeyword argument. For example:fromvalidator_collectionimportvalidators,errorstry:result=validators.variable_name('this is an invalid variable name',force_run=True)exceptValueError:# handle the errorwill produce aInvalidVariableNameError(which is a type ofValueError).Using CheckersPlease see theChecker ReferenceLikewise, a checker is what it sounds like: It checks that an input value
is what you expect it to be, and tells youTrue/Falsewhether it is or not.IMPORTANT:Checkers donotverify or convert object types. You can think of a checker as
a tool that tells you whether its correspondingvalidatorwould fail. SeeBest Practicesfor tips and tricks on
using the two together.Each checker is expressed as the name of the thing being validated, prefixed byis_. So the checker for an email address isis_email()and the checker
for an integer isis_integer().Checkers take the input value you want to check as their first (and often only)
positional argumet. If the input value validates, they will returnTrue. Unlikevalidators, checkers will not raise an exception if
validation fails. They will instead returnFalse.HINT:If you need to knowwhya given value failed to validate, use the validator
instead.HINT:Some checkers (particularly numeric ones likeis_integer()) have additional
options which are used to make sure the value meets criteria that you set for
it. These options are alwaysoptionaland are included as keyword argumentsafterthe input value argument. For details, please see theChecker Reference.Disabling CheckingCAUTION:If you are disabling validators using theVALIDATORS_DISABLEDenvironment variable, their related checkers willalsobe disabled. This means
they will always returnTrueunless called withforce_run = True.Checking can at times be an expensive (in terms of performance) operation. As
a result, there are times when you want to disable certain kinds of checking
when running in production. Using theValidator-Collectionthis is simple:Just add the name of the checker you want disabled to theCHECKERS_DISABLEDenvironment variable, and validation will automatically be skipped.CAUTION:CHECKERS_DISABLEDexpects a comma-separated list of values. If
it isn’t comma-separated, it won’t work properly.Here’s how it works in practice. Let’s say we define the following environment
variable:$exportCHECKERS_DISABLED="is_variable_name, is_email, is_ipv4"This disables theis_variable_name(),is_email(), andis_ipv4()checkers respectively.Now if we run:fromvalidator_collectionimportcheckersresult=checkers.is_variable_name('this is an invalid variable name')# result will be TrueThe checker will returnTrue.However, if we run:fromvalidator_collectionimportcheckersresult=validators.is_integer('this is an invalid variable name')# result will be Falsethe checker will returnFalseWe can force checkers to run (even if disabled using the environment variable)
by passing aforce_run = Truekeyword argument. For example:fromvalidator_collectionimportcheckersresult=checkers.is_variable_name('this is an invalid variable name',force_run=True)# result will be Falsewill returnFalse.Best PracticesCheckersandValidatorsare designed to be used together. You can think of them as a way to quickly and
easily verify that a value contains the information you expect, and then make
sure that value is in the form your code needs it in.There are two fundamental patterns that we find work well in practice.Defensive Approach: Check, then Convert if NecessaryWe find this pattern is best used when we don’t have any certainty over a given
value might contain. It’s fundamentally defensive in nature, and applies the
following logic:Check whethervaluecontains the information we need it to or can be
converted to the form we need it in.Ifvaluedoes not contain what we need butcanbe converted to what
we need, do the conversion.Ifvaluedoes not contain what we need butcannotbe converted to what
we need, raise an error (or handle it however it needs to be handled).We tend to use this where we’re first receiving data from outside of our control,
so when we get data from a user, from the internet, from a third-party API, etc.Here’s a quick example of how that might look in code:fromvalidator_collectionimportcheckers,validatorsdefsome_function(value):# Check whether value contains a whole number.is_valid=checkers.is_integer(value,coerce_value=False)# If the value does not contain a whole number, maybe it contains a# numeric value that can be rounded up to a whole number.ifnotis_validandcheckers.is_integer(value,coerce_value=True):# If the value can be rounded up to a whole number, then do so:value=validators.integer(value,coerce_value=True)elifnotis_valid:# Since the value does not contain a whole number and cannot be converted to# one, this is where your code to handle that error goes.raiseValueError('something went wrong!')returnvaluevalue=some_function(3.14)# value will now be 4new_value=some_function('not-a-number')# will raise ValueErrorLet’s break down what this code does. First, we definesome_function()which
takes a value. This function uses theis_integer()checker to see ifvaluecontains a whole number, regardless of its type.If it doesn’t contain a whole number, maybe it contains a numeric value that can
be rounded up to a whole number? It again uses theis_integer()to check if that’s
possible. If it is, then it calls theinteger()validator to coercevalueto a whole number.If it can’t coercevalueto a whole number? It raises aValueError.Confident Approach: try … exceptSometimes, we’ll have more confidence in the values that we can expect to work
with. This means that we might expectvaluetogenerallyhave the kind of
data we need to work with. This means that situations wherevaluedoesn’t
contain what we need will truly be exceptional situations, and can be handled
accordingly.In this situation, a good approach is to apply the following logic:Skip a checker entirely, and just wrap the validator in atry...exceptblock.We tend to use this in situations where we’re working with data that our own
code has produced (meaning we know - generally - what we can expect, unless
something went seriously wrong).Here’s an example:fromvalidator_collectionimportvalidators,errorsdefsome_function(value):try:email_address=validators.email(value,allow_empty=False)excepterrors.InvalidEmailErroraserror:# handle the error hereexceptValueErroraserror:# handle other ValueErrors here# do something with your new email address valuereturnemail_addressemail=some_function('email@domain.com')# This will return the email address.email=some_function('not-a-valid-email')# This will raise a ValueError that some_function() will handle.email=some_function(None)# This will raise a ValueError that some_function() will handle.So what’s this code do? It’s pretty straightforward.some_function()expects
to receive avaluethat contains an email address. We expect thatvaluewilltypicallybe an email address, and not something weird (like a number or
something). So we just try the validator - and if validation fails, we handle
the error appropriately.Questions and IssuesYou can ask questions and report issues on the project’sGithub Issues PageContributingWe welcome contributions and pull requests! For more information, please see theContributor Guide.And thanks toall those who have contributed!TestingWe useTravisCIfor our build automation andReadTheDocsfor our documentation.Detailed information about our test suite and how to run tests locally can be
found in ourTesting Reference.LicenseTheValidator Collectionis made available on aMIT License.