hehey-hvalidation 是一个python 全面的验证器工具类.
其主要特点有:
https://gitee.com/chinahehe/hehey-hvalidation
更 多 示 例 请 查 看 e x a m p l e s 目 录 \color{red}{更多示例请查看examples目录} 更多示例请查看examples目录
# 基础示例
from hvalidation.Validation import Validation
validation = Validation()
validateData = {
'name': '验证通过',
'userid': 10,
'age': 1
};
validateRules = [
['name',[['required']],{'message':'请输入一个10-20位的字符串'}],
['userid',[['!empty']],{'message':'user_id 不能为空'}],
];
if not validation.validate(validateData,validateRules):
print("验证错误:{0}".format(validation.getFirstError()))
else:
print('验证通过!')
# 验证多个属性
validateRules = [
[['userid','name'],[['!empty']],{'message':'参数不能为空'}],
];
# 定义多个验证类型,支持与或 or,and,&,|
validateRules = [
['name',[['!empty'],['minlen',{'number':1}]],{'message':'请输入一个10-20位的字符串'}],
['age',['and',['boolean'],['minlen',{'number':2}]],{'message':'请输入一个长度最少是{number}的字符串!'}],
];
# 新增验证类型
# 验证别名customType,hehe.core.validate.BooleanValidate 验证器,
validation.addValidator('customType','hehe.core.validate.BooleanValidate.BooleanValidate','自定义消息内容');
# 快捷方式验证-直接调用验证器方法
result = validation.eq('127.0.0.1',number = "127.0.0.1");
# 或
result = validation.eq('127.0.0.1',{"number":"127.0.0.1"});
# 装饰器注册验证器
from hvalidation.Validation import Validation,reg_func_validator,reg_clazz_validator
@reg_func_validator('用户名不能为空')
# 注册函数方法验证器
def username(self,value,name = None):
return False;
pass
# 注册类验证器
from hvalidation.base.Validator import Validator
import re;
@reg_clazz_validator('ip 格式有误','ip')
class IpValidator(Validator):
def __init__(self,attrs,validation = None):
self.pattern = r'^(\d+\.\d+\.\d+\.\d+)$'
super().__init__(attrs,validation)
def validateValue(self,value,name = None):
if re.match(self.pattern, value) is not None:
return True
else:
return False
# 验证类属性
from hvalidation.Validation import reg_valid_rule
class Address:
@reg_valid_rule("ip", property="myuser", attrs={"message": "哈安安"})
@reg_valid_rule("float", property="myuser", attrs={"message": "哈安安"})
def __init__(self):
self.myuser = "什么规则"
address = Address()
if not validation.validate(address):
print("验证错误:{0}".format(validation.getFirstError()))
else:
print('验证通过!')
#或
if not validation.validateObject(address):
print("验证错误:{0}".format(validation.getFirstError()))
else:
print('验证通过!')