Package: django-rulebase
Django Rule-base Validatorinspired by laravel Requests , for making django validations painless.to use:pip install django-rulebasein app.views:fromdjango_rulebase.validatorimportrequire_validation@require_validation({"egg":"file|mimetypes:application/octet-stream"})defview_function(request):...orfromdjango.httpimportHttpResponse,HttpResponseBadRequestfromdjango_rulebaseimportRequestdefgood_request(request,is_valid,errors):ifis_valid:returnHttpResponse("good request")returnHttpResponseBadRequest(errors['date'])classCustomRequest(Request):view=good_requestdefrules(self):return{"date":"date|required|before:tomorrow|after:yesterday"}in app.urlsfromdjango.conf.urlsimporturlfrom.viewsimportCustomRequesturlpatterns=[url(r'^validate/$',CustomRequest.asView()),]with custom rule :fromdjango_rulebaseimportRequest,Ruleclassdivisible(Rule):name="divisible"defpasses(self,value):# should return booleanreturnall([value%self.parse_value(field)[1]==0forfieldinself.options])defmessage(self):return"{value}is not divisible to{options}"classCustomRequest(Request):view=good_requestdefrules(self):return{"date":"date|required|string|before:tomorrow|after:yesterday","some":"required|integer","num":["required|integer",divisible(["some"])]}or use everywhere:fromdjango_rulebaseimportValidatordefgood_request(request):data=json.loads(request.body)validator=Validator({"date":"date|required|string|before:tomorrow|after:yesterday","some":"required|integer","num":["required|integer",divisible(["some"])]})validator.run_validation(data)ifnotvalidator.valid:returnJsonResponse(validator.errors,safe=False)built-in rulesBelow is a list of all available validation rules and their function:ruleruleruleAcceptedActive URLAfter (Date)After Or Equal (Date)AlphaAlpha DashAlpha NumericArrayBefore (Date)Before Or Equal (Date)BetweenBooleanConfirmedDateDate EqualsDate FormatDifferentDigitsDigits BetweenDistinctEMailExists (Database)FileFilledGreater ThanGreater Than Or EqualImage (File)InIn ArrayIntegerIP AddressJSONLess ThanLess Than Or EqualMaxMIME TypesMIME Type By File ExtensionMinNot InNot RegexNullableNumericPresentRegular ExpressionRequiredRequired IfRequired UnlessRequired WithRequired With AllRequired WithoutRequired Without AllSameSizeStringTimezoneUnique (Database)URLUUID--acceptedThe field under validation must be yes, on, 1, or true. This is useful for validating "Terms of Service" acceptance.active-urlThe field under validation must have a valid A or AAAA record according to thednspython.after:dateThe field under validation must be a value after a given date. The dates will be passed into thedateparser:'finish_date':'required|date|after:start_date''another_date':'required|date|after:tomorrow'after-or-equal:dateThe field under validation must be a value after or equal to the given date. For more information, see theafter rule.alphaThe field under validation must be entirely alphabetic characters.alpha-dashThe field under validation may have alpha-numeric characters, as well as dashes and underscores.alpha-numThe field under validation must be entirely alpha-numeric characters.arrayThe field under validation must be a list array.before:dateThe field under validation must be a value preceding the given date. The dates will be passed intodateparser. In addition, like theafter rule, the name of another field under validation may be supplied as the value of date.before-or-equal:dateThe field under validation must be a value preceding or equal to the given date. The dates will be passed intodateparser. In addition, like theafter rule, the name of another field under validation may be supplied as the value of date.between:min,maxThe field under validation must have a size between the given min and max. Strings, numerics, arrays, and files are evaluated in the same fashion as thesize rule.booleanThe field under validation must be able to be cast as a boolean. Accepted input are true, false, 1, 0, "1", and "0".confirmedThe field under validation must have a matching field of foo_confirmation. For example, if the field under validation is password, a matching password_confirmation field must be present in the input.date|The field under validation must be a valid date according to thedateparser.date-equals:dateThe field under validation must be equal to the given date. The dates will be passed intodateparser.date-format:formatThe field under validation must match the given format. You should use either date or date_format when validating a field, not both.different:fieldThe field under validation must have a different value than field.digits:valueThe field under validation must be numeric and must have an exact length of value.digits-between:min,maxThe field under validation must have a length between the given min and max.distinctWhen working with arrays, the field under validation must not have any duplicate values.'foo.*.id':'distinct'emailThe field under validation must be formatted as an e-mail address.exists:table,columnThe field under validation must exist on a given database table.Basic Usage Of Exists Rule'state':'exists:states'If the column option is not specified, the field name will be used.Specifying A Custom Column Name'state':'exists:states,abbreviation'Specifying A Custom connection'state':'exists:connection.states,abbreviation'or usring model:fromapp.modelsimportSomeModelfromdjango_rulebase.ruleimportexists...'state':exists(SomeModel,"attribute")fileThe field under validation must be a successfully uploaded file.filledThe field under validation must not be empty when it is present.gt:fieldThe field under validation must be greater than the given field. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as thesize rule.gte:fieldThe field under validation must be greater than or equal to the given field. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as thesize rule.imageThe file under validation must be an image (jpeg, png, bmp, gif, or svg)in:foo,bar,...The field under validation must be included in the given list of values.
Since this rule often requires you to implode an array,
you can use _in() from .rule  to fluently construct the rule:fromdjanfo_rulebase.ruleimport_in..."field":["required",_in(1,3,"string")]in-array:anotherfield.*The field under validation must exist in anotherfield's values.integerThe field under validation must be an integer.ipThe field under validation must be an IP address.ipv4The field under validation must be an IPv4 address.ipv6The field under validation must be an IPv6 address.jsonThe field under validation must be a valid JSON string.lt:fieldThe field under validation must be less than the given field. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as thesize rule.lte:fieldThe field under validation must be less than or equal to the given field. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as thesize rule.max:valueThe field under validation must be less than or equal to a maximum value. Strings, numerics, arrays, and files are evaluated in the same fashion as thesize rule.mimetypes:text/plain,...The file under validation must match one of the given MIME types:'video':'mimetypes:video/avi,video/mpeg,video/quicktime'To determine the MIME type of the uploaded file, the file's contents will be read and the framework will attempt to guess the MIME type, which may be different from the client provided MIME type.mimes:foo,bar,...The file under validation must have a MIME type corresponding to one of the listed extensions.Basic Usage Of MIME Rule'photo':'mimes:jpeg,bmp,png'Even though you only need to specify the extensions, this rule actually validates against the MIME type of the file by reading the file's contents and guessing its MIME type.A full listing of MIME types and their corresponding extensions may be found at the following location:read moremin:valueThe field under validation must have a minimum value. Strings, numerics, arrays, and files are evaluated in the same fashion as thesize rule.not-in:foo,bar,...The field under validation must not be included in the given list of values. The Rule::notIn method may be used to fluently construct the rule:not-regex:patternThe field under validation must not match the given regular expression.Internally, this rule uses the re.search. The pattern specified should obey the same formatting required by preg_match and thus also include valid delimiters. For example:'email':'not_regex:^.+$'.Note: When using the regex / not_regex patterns, it may be necessary to specify rules in an array instead of using pipe delimiters, especially if the regular expression contains a pipe character.nullableThe field under validation may be null. This is particularly useful when validating primitive such as strings and integers that can contain null values.numericThe field under validation must be numeric.presentThe field under validation must be present in the input data but can be empty.regex:patternThe field under validation must match the given regular expression.Internally, this rule uses the re.search. The pattern specified should obey the same formatting required by re.compile and thus also include valid delimiters. For example:'email':'regex:^.+@.+$'.Note: When using the regex / not_regex patterns, it may be necessary to specify rules in an array instead of using pipe delimiters, especially if the regular expression contains a pipe character.requiredThe field under validation must be present in the input data and not empty. A field is considered "empty" if one of the following conditions are true:The value is null.
The value is an empty string.
The value is an empty array or empty Countable object.
The value is an uploaded file with no path.required-if:anotherfield,value,...The field under validation must be present and not empty if the anotherfield field is equal to any value.required-unless:anotherfield,value,...The field under validation must be present and not empty unless the anotherfield field is equal to any value.required-with:foo,bar,...The field under validation must be present and not empty only if any of the other specified fields are present.required-with-all:foo,bar,...The field under validation must be present and not empty only if all of the other specified fields are present.required-without:foo,bar,...The field under validation must be present and not empty only when any of the other specified fields are not present.required-without-all:foo,bar,...The field under validation must be present and not empty only when all of the other specified fields are not present.same:fieldThe given field must match the field under validation.size:valueThe field under validation must have a size matching the given value. For string data, value corresponds to the number of characters. For numeric data, value corresponds to a given integer value. For an array, size corresponds to the count of the array. For files, size corresponds to the file size in kilobytes.stringThe field under validation must be a string. If you would like to allow the field to also be null, you should assign thenullable ruleto the field.timezoneThe field under validation must be a valid timezone identifier according to the pytz.unique:table,columnThe field under validation must be unique in a given database table. If the column option is not specified, the field name will be used.Specifying A Custom Column Name:'email':'unique:users,email_address'urlThe field under validation must be a valid URL.uuidThe field under validation must be a valid RFC 4122 (version 1, 3, 4, or 5) universally unique identifier (UUID).to do :integrate with django formintegrate with rest_framwork