Skip to content

Instantly share code, notes, and snippets.

@codetalks-new
Last active January 1, 2016 10:19
Show Gist options
  • Save codetalks-new/8130748 to your computer and use it in GitHub Desktop.
Save codetalks-new/8130748 to your computer and use it in GitHub Desktop.
一个简单的整形验证函数
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