django專案基於鉤子驗證的註冊功能

ckxllf發表於2019-08-16

  前端html

  註冊

  {# 註冊的開始#}

  onsubmit="return false">

  {% csrf_token %}

  type=email

  data-val=true

  data-val-checkemailpostfix=不支援該郵箱字尾

  data-val-email=郵箱格式錯誤

  data-val-length=郵箱地址不能超過120個字元

  data-val-length-max=120

  data-val-regex=郵箱地址錯誤或不支援

  data-val-regex-pattern="[\w!#\$%&'\*\+\-\/=\^_`{\|}~.]+@([\w-]+\.)+(com|net|cn|org|me|cc|biz)$"

  data-val-remote="'郵箱' is invalid."

  data-val-remote-additionalfields=*.Email

  data-val-remote-url=/Account/CheckEmail

  data-val-required=請輸入郵箱地址 id=Email

  name=member_email>

  class="text-danger field-validation-valid" data-valmsg-for=Email

  data-valmsg-replace=true>

  手機號碼

  data-val-maxlength=國家程式碼格式錯誤 data-val-maxlength-max=4

  data-val-regex=國家程式碼格式錯誤 data-val-regex-pattern=^\+\d{1,3}$

  data-val-required=請輸入國家程式碼 id=CountryCode name=CountryCode

  value=+86>

  placeholder=繫結你的手機號 type=text

  data-val=true data-val-regex=手機號碼有誤

  data-val-regex-pattern=^\d{4,13}$

  data-val-remote="'手機號碼' is invalid."

  data-val-remote-additionalfields=*.PhoneNum

  data-val-remote-url=/Account/CheckPhoneNum

  data-val-required=請輸入手機號碼 id=PhoneNum

  name=member_tel>

  data-valmsg-replace=true>

  class="text-danger field-validation-valid"

  data-valmsg-for=PhoneNum

  data-valmsg-replace=true>

  登入名稱

  type=text

  data-val=true

  data-val-length=不合要求,至少2個字元,最多30個字元

  data-val-length-max=30 data-val-length-min=2

  data-val-nospace=登入使用者名稱不能包含空格

  data-val-remote="'登入名稱' is invalid."

  data-val-remote-additionalfields=*.LoginName

  data-val-remote-url=/Account/CheckLoginName

  data-val-required=請輸入登入使用者名稱 id=LoginName

  name=member_name>

  data-valmsg-replace=true>

  顯示名稱

  type=text

  data-val=true

  data-val-length=不合要求,至少2個字元,最多20個字元

  data-val-length-max=20 data-val-length-min=2

  data-val-regex=不能包含空格、@、:和,不能以._結尾

  data-val-regex-pattern=^(?!.*[@::\s]).*[^._]$

  data-val-remote="'顯示名稱' is invalid."

  data-val-remote-additionalfields=*.DisplayName

  data-val-remote-url=/Account/CheckDisplayName

  data-val-required=請輸入顯示名稱 id=DisplayName

  name=member_nickname>

  class="text-danger field-validation-valid" data-valmsg-for=DisplayName

  data-valmsg-replace=true>

  密碼

  placeholder=至少8位,必須包含字母、數字、特殊字元

  type=password data-val=true

  data-val-length=不合要求,密碼長度要求8-30位

  data-val-length-max=30

  data-val-length-min=8

  data-val-nospace=密碼不能包含空格

  data-val-regex=密碼必須包含字母、數字和特殊字元的組合

  data-val-regex-pattern="^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9])[-0-9a-zA-Z~!@#$%^&*`_=+\]\[{}:;\\|:;"'/?>.<,\(\)]{8,30}$"

  data-val-required=請輸入密碼 id=Password

  name=member_pwd>

  class="text-danger field-validation-valid" data-valmsg-for=Password

  data-valmsg-replace=true>

  確認密碼

  type=password

  data-val=true data-val-equalto=確認密碼錯誤

  data-val-equalto-other=*.Password

  id=ConfirmPassword

  name=r_pwd>

  class="text-danger field-validation-valid" data-valmsg-for=ConfirmPassword

  data-valmsg-replace=true>

  class="btn ladda-button mx-auto d-block cnblogs-btn-blue"

  data-style=zoom-in>註冊

  * 點選 “註冊” 按鈕,即表示您同意並願意遵守

  class=look-agreeon target=_blank

  href=//passport.cnblogs.com/agreement.html>使用者協議。

  {#註冊的表單結束#}

  前端jquery

  {#註冊的jquery#}

  $(document).ready(function () {

  //當點選註冊按鈕時候,把form表單裡的內容提交到後臺

  $("#submitBtn").click(function () {

  $.post("/blog/regist/", $('#registerForm').serialize(), function (data) {

  if (data.status == 0) {

  arr = {

  'member_name': '登入名稱',

  'member_nickname': '顯示名稱',

  'member_pwd': '密碼',

  'r_pwd': '確認密碼',

  'member_email': '郵箱',

  'member_tel': '手機號碼',

  '__all__': ''

  };

  $.each(data['info'], function (key, value) { //遍歷鍵值對

  console.log(key);

  console.log(value[0]);

  layer.msg(arr[key] + value[0]);

  return false;

  layer.msg(arr[key] + data['info'][key]);

  return false;

  });

  } else if (data.status == 1) {

  layer.msg(data['info'], function () {

  location.href = "{% url 'index' %}";

  });

  } else {

  layer.msg(data['info']);

  }

  }, 'json');

  });

  });

  {#註冊的jquery結束#}

  後臺路由

  # 註冊

  path('regist/', login.regist,name='regist'),

  寫鉤子驗證:專案目錄下建立my_forms.py檔案

  from django import forms #自動驗證 # forms元件

  from django.forms import widgets

  from django.core.exceptions import ValidationError

  from django.core.validators import RegexValidator

  from blog.models import Member

  class UserForm(forms.Form):

  wid_01 = widgets.TextInput(attrs={"class": "form-control"})#

  wid_02 = widgets.PasswordInput(attrs={"class": "form-control"})#

  member_name=forms.CharField(max_length=60,min_length=4,label="使用者名稱",widget=wid_01,error_messages={"required":"該欄位必填"})

  member_nickname = forms.CharField(max_length=60, min_length=2, label="顯示名稱", widget=wid_01,

  error_messages={"required": "該欄位必填"})

  member_pwd=forms.CharField(max_length=30,min_length=8,label="密碼",widget=wid_02,validators=[RegexValidator('\d+','只能是數字') ],error_messages={'required': '密碼不能為空','min_length': '密碼長度不能小於8','max_length': '密碼長度不能大於18','invalid': '密碼格式錯誤',})

  r_pwd=forms.CharField(max_length=30,min_length=8,label="確認密碼",widget=wid_02,validators=[RegexValidator('\d+','只能是數字') ],error_messages={'required': '密碼不能為空','min_length': '密碼長度不能小於8','max_length': '密碼長度不能大於18','invalid': '密碼格式錯誤',}) #/(?=.*[a-z])(?=.*\d)(?=.*[#@!~%^&*])[a-z\d#@!~%^&*]{8,16}/i

  member_email = forms.EmailField(label="郵箱",widget=wid_01,error_messages={"required":"該欄位必填","invalid":"格式不正確"})

  member_tel = forms.CharField(max_length=11, widget=wid_01,label="電話號碼",)

  # 區域性鉤子

  def clean_member_name(self):

  val = self.cleaned_data.get("member_name")

  res = Member.objects.filter(member_name=val)

  if not res:

  return val

  else:

  raise ValidationError("使用者名稱已存在!")

  # 全域性鉤子

  def clean(self):

  member_pwd=self.cleaned_data.get("member_pwd")

  r_pwd=self.cleaned_data.get("r_pwd")

  if member_pwd and r_pwd:

  if member_pwd==r_pwd:

  # print(self.cleaned_data)

  return self.cleaned_data

  else:

  raise ValidationError('兩次密碼不一致!')

  else: 無錫婦科醫院排名

  return self.cleaned_data

  後臺方法

  from blog.my_forms import *

  # 註冊頁

  def regist(request):

  res = {'status': None, 'info': None}

  if request.method == "POST":

  form = UserForm(request.POST)

  if not form.is_valid():

  res['status'] = 0

  res['info'] = form.errors

  return HttpResponse(json.dumps(res)) # 把這個結果告訴給前臺,ajax

  member_name = request.POST.get("member_name")

  member_nickname = request.POST.get("member_nickname")

  member_pwd = make_password(request.POST.get("member_pwd"))

  member_email = request.POST.get("member_email")

  member_tel = request.POST.get("member_tel")

  old_member_obj = Member.objects.filter(member_tel=member_tel)

  if old_member_obj:

  res['status'] = 3

  res['info'] = '手機號已註冊'

  return HttpResponse(json.dumps(res))

  member_obj = Member.objects.create(member_name=member_name, member_nickname=member_nickname,

  member_pwd=member_pwd, member_email=member_email, member_tel=member_tel)

  if member_obj:

  # res = {'status': 1, 'info': '登入成功'}

  res['status'] = 1

  res['info'] = '註冊成功,即將跳轉至首頁'

  else:

  res['status'] = 2

  res['info'] = '發生了一個意料之外的錯誤,註冊失敗'

  response_new = HttpResponse(json.dumps(res)) # 把這個結果告訴給前臺,ajax

  # response_new.set_cookie("member_id",member_obj.member_id)#設定cookie

  # response_new.set_cookie("member_name", member_obj.member_name)

  # session

  request.session['member_id'] = member_obj.member_id

  request.session['member_name'] = member_obj.member_name

  # response_new.set_cookie("member_id", member_obj.member_id, expires = 60 * 60 * 24 * 7)

  return response_new

  return render(request, 'blog/regist.html')

  頁面效果

  

  done。


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69945560/viewspace-2653945/,如需轉載,請註明出處,否則將追究法律責任。

相關文章