本文介紹了thinkphp5使用bootstrapvalidator進行非同步驗證郵箱的樣本,分享給大家,具體如下:
js驗證
/** * Created by HONGXIN on 2017-10-23. */$(function () { $('form').bootstrapValidator({ message: 'This value is not valid', feedbackIcons: { valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-refresh' }, live: 'disabled',//驗證失敗後,提交按鈕仍然是可選狀態 fields: { email: { message: '使用者名稱驗證失敗',//預設 verbose: false, validators: { notEmpty: { message: '郵箱不可為空' }, emailAddress: { message: '郵箱地址格式有誤' }, remote: { url: '/ajax_email', message:"此郵箱已經註冊", type: "post", dataType: 'json', data: { //預設傳遞的就是輸入框的值 }, delay: 500,//延遲效果 }, } }, password: { validators: { notEmpty: { message: '郵箱地址不可為空' }, stringLength: { min: 6, max: 18, message: '使用者名稱長度必須在6到18位之間' }, }, }, password2: { validators: { notEmpty: { message: '確認密碼不可為空' }, identical: { field: 'password', message: '兩次密碼必須一致' } } }, username:{ validators: { notEmpty: { message: '使用者名稱不可為空' }, stringLength: { min: 2, max: 8, message: '使用者名稱長度必須在2到8位之間' } } } } });});
TP5處理
public function ajax_email(){ //該message可以為空白,它替換JS驗證的message屬性 echo json_encode(['valid'=>false,'message'=>'驗證碼不正確']); }
js驗證幾個注意點
verbose: false,代表js驗證合法後再非同步後台驗證,這樣減少伺服器壓力
data: {} ,預設傳遞的就是輸入框的值,所以一般不用寫該屬性,或者為空白即可
後台注意點
注意不是return而是echo
返回json格式 {'valid':true[,'message':'驗證成功']}