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的是否爲郵箱格式以及是否符合定義時的格式,如果不符合則拋出異常



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章