插件窝 干货文章 一文讲解thinkphp5如何进行异步验证邮箱

一文讲解thinkphp5如何进行异步验证邮箱

message 验证 glyphicon 邮箱 120    来源:    2024-10-27

thinkphp框架教程栏目将给大家介绍thinkphp5使用bootstrapvalidator进行异步验证邮箱的方法,希望对需要的朋友有所帮助!

TP5使用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':'验证成功']}