Layui手动验证表单必填项

2023-10-05 20:03

本文主要是介绍Layui手动验证表单必填项,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.JS文件(formVerify.js)

//验证规则设定
var verifyConfig = {required: [/[\S]+/,'必填项不能为空'],phone: [/^1\d{10}$/,'请输入正确的手机号'],email: [/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/,'邮箱格式不正确'],url: [/(^#)|(^http(s*):\/\/[^\s]+\.[^\s]+)/,'链接格式不正确'],number: function(value){if(!value || isNaN(value)) return '只能填写数字'},date: [/^(\d{4})[-\/](\d{1}|0\d{1}|1[0-2])([-\/](\d{1}|0\d{1}|[1-2][0-9]|3[0-1]))*$/,'日期格式不正确'],identity: [/(^\d{15}$)|(^\d{17}(x|X|\d)$)/,'请输入正确的身份证号']
};
//扩展JQuery
$.fn.formVerify=function(v){var device = layui.device();var stop = null //验证不通过状态,verify = verifyConfig //验证规则,DANGER = 'layui-form-danger' //警示样式,verifyElem = this.find('*[lay-verify]'); //获取需要校验的元素//开始校验layui.each(verifyElem, function(_, item){var othis = $(this),vers = othis.attr('lay-verify').split('|'),verType = othis.attr('lay-verType') //提示方式,value = othis.val();othis.removeClass(DANGER); //移除警示样式//遍历元素绑定的验证规则layui.each(vers, function(_, thisVer){var errorText = '' //错误提示文本,isFn = typeof verify[thisVer] === 'function';//匹配验证规则if(verify[thisVer]){var isTrue = isFn ? errorText = verify[thisVer](value, item) : !verify[thisVer][0].test(value);errorText = errorText || verify[thisVer][1];if(thisVer === 'required'){errorText = othis.attr('lay-reqText') || errorText;}var verifyType=$(item).attr('type');if(verifyType==="radio" || verifyType==="checkbox"){var verifyName=$(item).attr('name'),verifyElem=$(item).parents('.layui-form').find('input[name='+verifyName+']');isTrue= !verifyElem.is(':checked');if(isTrue){var focusElem = verifyElem.next().find('i.layui-icon');//定位焦点focusElem.css(verifyType=='radio'?{"color":"#FF5722"}:{"border-color":"#FF5722"});//对非输入框设置焦点focusElem.first().attr("tabIndex","1").css("outline","0").blur(function() {focusElem.css(verifyType=='radio'?{"color":""}:{"border-color":""});}).focus();if(verType === 'tips'){layer.tips(errorText, function(){return othis.next();}(), {tips: 1});} else if(verType === 'alert'){layer.alert(errorText, {title: '提示', shadeClose: true});} else {layer.msg(errorText, {icon: 5, shift: 6});}return stop = true;}}//如果是必填项或者非空命中校验,则阻止提交,弹出提示if(isTrue){//提示层风格if(verType === 'tips'){layer.tips(errorText, function(){if(typeof othis.attr('lay-ignore') !== 'string'){if(item.tagName.toLowerCase() === 'select' || /^checkbox|radio$/.test(item.type)){return othis.next();}}return othis;}(), {tips: 1});} else if(verType === 'alert') {layer.alert(errorText, {title: '提示', shadeClose: true});} else {layer.msg(errorText, {icon: 5, shift: 6});}//非移动设备自动定位焦点if(!device.android && !device.ios){setTimeout(function(){item.focus();}, 7);}othis.addClass(DANGER);return stop = true;}}});if(stop) return stop;});if(stop){return false;} else {return true;}
};//直接定义JS方法
function formVerify(formId){var $ = layui.$//,layer = layui.layer,device = layui.device();var stop = null //验证不通过状态,verify = verifyConfig //验证规则,DANGER = 'layui-form-danger' //警示样式,verifyElem = $(formId).find('*[lay-verify]'); //获取需要校验的元素//开始校验layui.each(verifyElem, function(_, item){var othis = $(this),vers = othis.attr('lay-verify').split('|'),verType = othis.attr('lay-verType') //提示方式,value = othis.val();othis.removeClass(DANGER); //移除警示样式//遍历元素绑定的验证规则layui.each(vers, function(_, thisVer){var errorText = '' //错误提示文本,isFn = typeof verify[thisVer] === 'function';//匹配验证规则if(verify[thisVer]){var isTrue = isFn ? errorText = verify[thisVer](value, item) : !verify[thisVer][0].test(value);errorText = errorText || verify[thisVer][1];if(thisVer === 'required'){errorText = othis.attr('lay-reqText') || errorText;}var verifyType=$(item).attr('type');if(verifyType==="radio" || verifyType==="checkbox"){var verifyName=$(item).attr('name'),verifyElem=$(item).parents('.layui-form').find('input[name='+verifyName+']');isTrue= !verifyElem.is(':checked');if(isTrue){var focusElem = verifyElem.next().find('i.layui-icon');//定位焦点focusElem.css(verifyType=='radio'?{"color":"#FF5722"}:{"border-color":"#FF5722"});//对非输入框设置焦点focusElem.first().attr("tabIndex","1").css("outline","0").blur(function() {focusElem.css(verifyType=='radio'?{"color":""}:{"border-color":""});}).focus();if(verType === 'tips'){layer.tips(errorText, function(){return othis.next();}(), {tips: 1});} else if(verType === 'alert'){layer.alert(errorText, {title: '提示', shadeClose: true});} else {layer.msg(errorText, {icon: 5, shift: 6});}return stop = true;}}//如果是必填项或者非空命中校验,则阻止提交,弹出提示if(isTrue){//提示层风格if(verType === 'tips'){layer.tips(errorText, function(){if(typeof othis.attr('lay-ignore') !== 'string'){if(item.tagName.toLowerCase() === 'select' || /^checkbox|radio$/.test(item.type)){return othis.next();}}return othis;}(), {tips: 1});} else if(verType === 'alert') {layer.alert(errorText, {title: '提示', shadeClose: true});} else {layer.msg(errorText, {icon: 5, shift: 6});}//非移动设备自动定位焦点if(!device.android && !device.ios){setTimeout(function(){item.focus();}, 7);}othis.addClass(DANGER);return stop = true;}}});if(stop) return stop;});if(stop){return false;} else {return true;}
};

2.调用验证方法

<form id="addUserForm" class="layui-form layui-form-pane"><div class="layui-form-item"><label class="layui-form-label">登录账号</label><div class="layui-input-block"><input type="text" name="userName" class="layui-input" lay-verify="required"></div></div><div class="layui-form-item"><label class="layui-form-label">登录密码</label><div class="layui-input-block"><input type="password" name="passWord" class="layui-input" lay-verify="required|pass"></div></div>
</form><a class="layui-btn" onclick="formSubmit()">提交表单</a><script src="formVerify.js" type="text/javascript"></script>
<script>
//自定义验证规则
layui.$.extend(true, verifyConfig,{pass: [/^[\S]{6,12}$/,'密码必须6到12位,且不能出现空格']}
);function formSubmit(){if($("#addUserForm").formVerify()){alert("表单提交成功");}
}
</script>

 

这篇关于Layui手动验证表单必填项的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/151939

相关文章

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

C++ | Leetcode C++题解之第393题UTF-8编码验证

题目: 题解: class Solution {public:static const int MASK1 = 1 << 7;static const int MASK2 = (1 << 7) + (1 << 6);bool isValid(int num) {return (num & MASK2) == MASK1;}int getBytes(int num) {if ((num &

HTML提交表单给python

python 代码 from flask import Flask, request, render_template, redirect, url_forapp = Flask(__name__)@app.route('/')def form():# 渲染表单页面return render_template('./index.html')@app.route('/submit_form',

C语言 | Leetcode C语言题解之第393题UTF-8编码验证

题目: 题解: static const int MASK1 = 1 << 7;static const int MASK2 = (1 << 7) + (1 << 6);bool isValid(int num) {return (num & MASK2) == MASK1;}int getBytes(int num) {if ((num & MASK1) == 0) {return

easyui同时验证账户格式和ajax是否存在

accountName: {validator: function (value, param) {if (!/^[a-zA-Z][a-zA-Z0-9_]{3,15}$/i.test(value)) {$.fn.validatebox.defaults.rules.accountName.message = '账户名称不合法(字母开头,允许4-16字节,允许字母数字下划线)';return fal

easyui 验证下拉菜单select

validatebox.js中添加以下方法: selectRequired: {validator: function (value) {if (value == "" || value.indexOf('请选择') >= 0 || value.indexOf('全部') >= 0) {return false;}else {return true;}},message: '该下拉框为必选项'}

form表单提交编码的问题

浏览器在form提交后,会生成一个HTTP的头部信息"content-type",标准规定其形式为Content-type: application/x-www-form-urlencoded; charset=UTF-8        那么我们如果需要修改编码,不使用默认的,那么可以如下这样操作修改编码,来满足需求: hmtl代码:   <meta http-equiv="Conte

js异步提交form表单的解决方案

1.定义异步提交表单的方法 (通用方法) /*** 异步提交form表单* @param options {form:form表单元素,success:执行成功后处理函数}* <span style="color:#ff0000;"><strong>@注意 后台接收参数要解码否则中文会导致乱码 如:URLDecoder.decode(param,"UTF-8")</strong></span>

前端form表单+ifarme方式实现大文件下载

// main.jsimport Vue from 'vue';import App from './App.vue';import { downloadTokenFile } from '@/path/to/your/function'; // 替换为您的函数路径// 将 downloadTokenFile 添加到 Vue 原型上Vue.prototype.$downloadTokenF

web群集--nginx配置文件location匹配符的优先级顺序详解及验证

文章目录 前言优先级顺序优先级顺序(详解)1. 精确匹配(Exact Match)2. 正则表达式匹配(Regex Match)3. 前缀匹配(Prefix Match) 匹配规则的综合应用验证优先级 前言 location的作用 在 NGINX 中,location 指令用于定义如何处理特定的请求 URI。由于网站往往需要不同的处理方式来适应各种请求,NGINX 提供了多种匹