django 邮箱校验

本篇主要介绍django中比较常用校验邮箱的方法

环境:

python 2.7
django 1.8.3

方法一:  validate_email

def ValidateEmail( email ):
    from django.core.validators import validate_email
    from django.core.exceptions import ValidationError
    try:
        validate_email( email )
        return True
    except ValidationError:
        return False 

方法二:EmailField

在表单forms的 EmailField字段在验证
froms.py

class RegisterForm(forms.Form):
    '''
    注册
    '''
    username = forms.EmailField(widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "请输入邮箱账号", "value": "", "required": "required",}),
                              max_length=50,error_messages={"required": "用户名不能为空",})
    password = forms.CharField(widget=forms.PasswordInput(attrs={"class": "form-control", "placeholder": "请输入密码", "value": "", "required": "required",}),
                              min_length=8, max_length=50,error_messages={"required": "密码不能为空",})

    def clean(self):

         # 用户名
        try:          
            username=self.cleaned_data['username']
        except Exception as e:
            print 'except: '+ str(e)
            raise forms.ValidationError(u"注册账号需为邮箱格式")    

        return self.cleaned_data  
在cleaned_data会校验username的是否为邮箱格式以及是否符合定义时的格式,如果不符合则抛出异常



你可能感兴趣的:(django,正则表达式)