The field validation Django form.Form

 

RegexValidator checker:

In a custom form component class set field validators value introduced RegexValidator module

from django import forms

from django.core.validators import RegexValidator

from django.core.exceptions import ValidationError

 

class Myform(forms.Form):

    name = forms.CharField(

        # Required = True, # default is True

        min_length=2,

        max_length=6,

        Initial = 'ABC'# Default

        help_text = ' a length of 2 to . 6 characters! '# Help

        error_messages = [{  # custom error message ( default is English )

            'required' : ' can not be empty! ' ,

            'min_length' : ' can not be less than 2 characters! '

        }],

        validators = [RegexValidator ( R & lt '^ (\ W) + $' , ' User name only alphanumeric underscores! ' ),], 

        # Disabled = True # The default is True display

 

    )

    

email = fields.EmailField(required=False,

                           error_messages, = { 'required' : U ' E-mail can not be empty ' , 'invalid' : U ' mailbox format error ' },

                           widget=widgets.TextInput(attrs={'class': "form-control", 'placeholder': u'邮箱'}))

 

Custom function check:

from django.shortcuts import render,HttpResponse

from django import forms

from app01 import models

from django.core.validators import RegexValidator

import re

from django.core.exceptions import ValidationError

 

# Custom check function, directly in the field validators use

def name_valid(value):

    name_re=re.compile(r'^[a-zA-Z_]+$')

    if not name_re.match(value):

        The raise ValidationError ( " can only begin with the letter underlined! " )

class Myform(forms.Form):

    name = forms.CharField(

        # Required = True, # default is True

        min_length=2,

        max_length=6,

        Initial = 'ABC'# Default

        help_text = ' a length of 2 to . 6 characters! '# Help

        error_messages = [{  # custom error message ( default is English )

            'required' : ' can not be empty! ' ,

            'min_length' : ' can not be less than 2 characters! '

        }],

        validators = [RegexValidator ( R & lt '^ (\ W) + $' , ' User name only alphanumeric underscores! ' ), name_valid], 

# Custom validation rules ( the list of custom function names discharge or introduce django built RegexValidator validator, can mix )

    )

 

Calibration sequence:

自定义类实例化返回值对象的is_valid()方法调用:

1)字段规则校验

2validators校验(RegexValidator校验器或自定义校验函数)

3)局部钩子(类中定义的以clean_字段名命名的函数,校验正常必须返回该字段的值self.cleaned_data.get('name')

4)全局钩子(类中定义的函数名clean,校验正常必须返回该对象的校验结果值return self.cleaned_data

5)每一步通过校验单结果都以字典形式保存在类对象的cleaned_data属性中

Guess you like

Origin www.cnblogs.com/open-yang/p/11223160.html