form的valid驗證的原理

2022-05-04 13:12:13 字數 3035 閱讀 3829

import re

import copy

class

validateerror(exception):

def __init__(self,detail):

self.detail =detail

# ###################### 外掛程式

class textinput(object

): def __str__(self):

return""

class emailinput(object

): def __str__(self):

return""

# ###################### 內部包含正則,用於驗證

class field(object

): def __init__(self,required=true,error_messages=none,widget=none):

self.required =required

self.error_messages =error_messages

ifnot widget:

self.widget =textinput()

else

: self.widget =widget

def __str__(self):

return

str(self.widget)

class

charfield(field):

def valid(self,val):

ifself.required:

ifnot val:

msg = self.error_messages['

required']

raise validateerror(msg)

return

valclass

emailfield(field):

reg = "

^\w+@\w+$

"def valid(self,val):

ifself.required:

ifnot val:

msg = self.error_messages['

required']

raise validateerror(msg)

result =re.match(self.reg,val)

ifnot result:

msg = self.error_messages.get('

invalid

','格式錯誤')

raise validateerror(msg)

return

val# ###################### form,獲取使用者提交內容+獲取定義的字段物件

class form(object

): def __init__(self,data=none):

# 獲取派生類中的所有靜態字段

# print(self.__class__.__dict__)

self.data =data

self.fields =copy.deepcopy(self.__class__.declare_field)

self.cleaned_data ={}

self.errors ={}

def __new__(cls, *args, **kwargs):

declare_field ={}

for field_name, field in

cls.__dict__.items():

ifisinstance(field,field):

declare_field[field_name] =field

cls.declare_field =declare_field

return

object

.__new__(cls)

def is_valid(self):

# 使用者提交的資料

# self.data #

# self.fields #

for field_name,filed in

self.fields.items():

try:

input_val = self.data.get

(field_name)

val =filed.valid(input_val)

method = getattr(self,"

cleaned_%s

" %field_name,none)

ifmethod:

val =method(val)

self.cleaned_data[field_name] =val

except validateerror

ase:

self.errors[field_name] =e.detail

return len(self.errors) == 0

def __iter__(self):

return

iter(self.fields.values())

class

userform(form):

username = charfield(error_messages=,widget=textinput())

pwd = emailfield(error_messages=,widget=emailinput())

# ############### 應用

obj = userform(data=)

ifobj.is_valid():

print(

'驗證成功

',obj.cleaned_data)

else

: print(

"驗證失敗

",obj.errors)

# ##################### html #####################

for x in

obj:

print(x)

form元件的驗證

django 的form元件可以實現自定義的驗證規則。建立基於form的類,在類中建立字段,定義規則。建立該類的物件,並將待驗證的資料傳入,使用is valid 函式。is valid 函式的原始碼實現是 通過full clean 函式挖出存在的errors並返回,如果沒錯誤,則返回true。校驗多...

Django中的Form表單驗證

前端有若干個input輸入框,將使用者輸入內容,以字典傳遞給後端。後端預先存在乙個form表單驗證的基類,封裝了乙個檢測使用者輸入是否全部通過的方法。該方法會先定義好錯誤資訊的字典,並會遍歷類的所有屬性 對應前端待驗證的輸入域 呼叫各自的驗證方法,將錯誤資訊 兩類,必要與否以及格式正確與否 存入字典...

Valid註解的使用

在實體類上打上註解 data public class user2.在controller上加上註解 valid,進行引數校驗 public string testuser requestbody valid user user,bindingresult bindingresult return ...