Last active
January 1, 2016 10:19
-
-
Save codetalks-new/8130748 to your computer and use it in GitHub Desktop.
一个简单的整形验证函数
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def is_empty(value): | |
"""Check whether the given value should be considered "empty".""" | |
return value is None or value == '' or ( | |
isinstance(value, (list, tuple, dict)) and not value) | |
def int_to_python(value,min=None,max=None,empty=False,default=0,error=None): | |
""" | |
:param value: 待验证的值 | |
:param min: 值的最小取值范围 | |
:param max: 最大取值范围 | |
:param empty: 是否可以为空 | |
:param default: 默认值 | |
:param error: 如果出错的话,可以指定的返回错误语句 | |
:return: 返回(value,error) 元组 | |
""" | |
error = error if error else "非法的整数值" | |
if value and isinstance(value,basestring): | |
value = value.strip() | |
if is_empty(value): | |
return default,None if empty else None,error | |
try: | |
value = int(value) | |
if min is not None and value < min: | |
return None,error | |
if max is not None and value > max: | |
return None,error | |
return value,None | |
except (ValueError,TypeError): | |
return None,error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment