Django基础之form表单验证

1. 方式一

from django.forms import Form
from django.forms import widgets
from django.forms import fields
from django.core.validators import RegexValidator

class MyForm(Form.forms):
    user = fields.CharField(
        validators = [
            RegexValidator(r"^[0-9]+$", "请输入数字"),
            RegexValidator(r"^159[0-9]+$", "数字必须以159开头")
        ]
    )

2. 方式二

import re
from django.forms import Form
from django.forms import widgets
from django.forms import fields
from django.core.exceptions import ValidationError

# 自定义验证规则
def mobile_validate(value):
    mobile_re = re.compile(r"(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$")
    if not mobile_re.match(value):
        raise ValidationError("手机号码格式错误")

class PublishForm(Form):
    title = fields.CharField(
        max_length=20,
        min_length=5,
        error_messages={
            "required": "标题不能为空",
            "min_length": "标题最少为5个字符",
            "max_length": "标题最多为20个字符"
        },
        widget=widgets.TextInput(attrs={
            "class": "form-control",
            "placeholder": "标题5-20个字符"
        })
    )
    
    # 使用自定义验证规则
    phone = fields.CharField(
        validators=[mobile_validate],
        error_messages = {
            "required": "手机不能为空"
        },
        widget=widgets.TextInput(attrs={
            "class": "form-control",
            "placeholder": u"手机号码"
        })
    )
    
    email = fields.EmailField(
        required=False,
        error_message={
            "required": u"邮箱不能为空",
            "invalid": u"邮箱格式错误"
        },
        widget=widgets.TextInput(attrs={
            "class": "form-control",
            "placeholder": u"邮箱"
        })
    )

  

posted @ 2018-11-22 20:21  _杨魏  阅读(344)  评论(0编辑  收藏  举报