本文将分享vue-validator使用详解的详细内容,并且还将对vue中validator方法进行详尽解释,此外,我们还将为大家带来关于asp.net-mvc–FluentValidationAut
本文将分享vue-validator 使用详解的详细内容,并且还将对vue中validator方法进行详尽解释,此外,我们还将为大家带来关于asp.net-mvc – FluentValidation Autofac ValidatorFactory、bootstrap-validator使用详解(代码实例)、c# – FluentValidation,Validators生命周期并使用Validators检查Db、com.beust.jcommander.validators.NoValueValidator的实例源码的相关知识,希望对你有所帮助。
本文目录一览:- vue-validator 使用详解(vue中validator方法)
- asp.net-mvc – FluentValidation Autofac ValidatorFactory
- bootstrap-validator使用详解(代码实例)
- c# – FluentValidation,Validators生命周期并使用Validators检查Db
- com.beust.jcommander.validators.NoValueValidator的实例源码
vue-validator 使用详解(vue中validator方法)
自定义配置文件 (validateConfig):
import Vue from ''vue''
import VeeValidate, { Validator } from ''vee-validate''
const dictionary = {
en: {
messages: {
// <input type="text" v-model="phoneNumber" name="phone" v-validate="''required|phone''">
// 不满足required条件时,显示的提示对应下面的设置
required: (field) => `${field} is necessary!`,
},
attributes: {
// <input type="text" v-model="phoneNumber" name="phone" v-validate="''required|phone''">
// 上述messages提示信息中field显示的内容在此设置,对应标签的name属性
phone: ''Phone Number'',
}
}
}
// 引用上述设置
Validator.localize(dictionary)
// 自定义验证规则,取名为phone, 通过该方式使用v-validate="''required|phone''"
Validator.extend(''phone'', {
// 验证规则,符合规则通过,否则不通过 (规则为美国电话号码)
validate: (value, ref) => {
return /^(\d3|^\d{3}[.-]?)?\d{3}[.-]?\d{4}$/.test(value)
},
// 提示信息,不符合规则提示语
// <span v-show="errors.has(''phone'')"> {{ errors.first(''phone'') }} </span>
getMessage: (field) => ''The '' + field + '' is invalid.''
})
// 事件触发规则,在输入框中输入后点击事件触发验证,默认为实时验证
Vue.use(VeeValidate, { events: ''blur'' })
main.js 中引入文件
import ''@/assets/js/validateConfig''
页面使用:
<label>Phone Number</label>
<input type="text" v-model="phoneNumber" name="phone" v-validate="''required|phone''">
<span v-show="errors.has(''phone'')" class="error-message"> {{ errors.first(''phone'') }} </span>
提交方法中引入,进行校验,不通过中断执行
update () {
let result = await this.$validator.validateAll()
if (!result) {
return
}
....
}
对自定义的组件 (自定义 select),数据发生变化,validate 拿不到新的数据,需要使用 v-validate:userId="''required|phone''"
指定检测 userId,并在触发事件中使用 await this.$validator.validateAll () 来对提示语关闭或显示 (基于事件触发验证情况)
eg:
<my-select :select="users" :value="userId" @input="idChanged"
name="userId" v-validate:userId="''required''"></my-select>
<span v-show="errors.has(''userId'')" class="error-message"> {{ errors.first(''userId'') }} </span>
idChanged (value) {
this.userId = value
this.$validator.validateAll()
}
asp.net-mvc – FluentValidation Autofac ValidatorFactory
ValidatorFactory
public class ValidatorFactory : ValidatorFactoryBase { private readonly IComponentContext context; public ValidatorFactory(IComponentContext context) { this.context = context; } public override IValidator CreateInstance(Type validatorType) { return context.Resolve(validatorType) as IValidator; } }
如何提供上下文并注册ValidatorFactory
FluentValidation.Mvc.FluentValidationModelValidatorProvider.Configure(x => x.ValidatorFactory = new ValidatorFactory());
解决方法
public class ModelValidatorFactory : IValidatorFactory { public IValidator GetValidator(Type type) { if (type == null) { throw new ArgumentNullException("type"); } return DependencyResolver.Current.GetService(typeof(IValidator<>).MakeGenericType(type)) as IValidator; } public IValidator<T> GetValidator<T>() { return DependencyResolver.Current.GetService<IValidator<T>>(); } }
然后,您可以将任何类型的DependencyResolver注册为验证器,作为强类型IValidator< T>它总会最终解决.
bootstrap-validator使用详解(代码实例)
这次给大家带来bootstrap-validator使用详解,使用bootstrap-validator的注意事项有哪些,下面就是实战案例,一起来看一下。
【相关视频推荐:Bootstrap教程】
需要的js、css和img在下面都有说明,耐心点读!
需要的js文件: jquery.min.js,bootstrapValidator.min.js,bootstrap-validator-default.js(自定义的一个默认配置文件,是个人写的,非官方文件)
前两个文件cdn上都有,bootstrap-validator-default.js内容如下:
/*默认规则 start*///ip格式$.fn.bootstrapValidator.validators.ip = { //message: "ip格式不正确" validate: function(validator, $field, options) { var value = $field.val(), ipReg = /^(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)\.(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)\.(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)\.(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)$/; if (value === '') { return true; } return ipReg.test(value); } };//password格式$.fn.bootstrapValidator.validators.pw = { //message: "必须包含数字、英文字母、特殊字符" validate: function(validator, $field, options) { var value = $field.val(), ipReg = /.*(?=.*\d)(?=.*[a-zA-Z])(?=.*[~!@#$%^&*_])./; if (typeof value != 'string' || !ipReg.test(value)) { return false; } return true; } };//不允许有空格$.fn.bootstrapValidator.validators.noSpace = { //message: "必须包含数字、英文字母、特殊字符" validate: function(validator, $field, options) { var value = $field.val(); if (typeof value != 'string' || value.indexOf(' ') > -1) { return false; } return true; } };//网关格式$.fn.bootstrapValidator.validators.mask = { //message: "网关不可达" validate: function(validator, $field, options) { var ipArr = $field.parent().parent().find('input[name="ip"]').val().split('.'), gatewayArr = $field.parent().parent().find('input[name="gateway"]').val().split('.'), value = $field.val(), netmaskArr = value.split('.'), len = 4, i = 0; if (ipArr.length !== len || gatewayArr.length !== len || netmaskArr.length !== len) { return false; } for (; i < len; i++) { if ((ipArr[i] & netmaskArr[i]) !== (gatewayArr[i] & netmaskArr[i])) { return false; } } return true; } };//邮箱 表单验证规则$.fn.bootstrapValidator.validators.mail = { //message: "邮箱格式不正确" validate: function(validator, $field, options) { var mail = /^[a-z0-9._%-]+@([a-z0-9-]+\.)+[a-z]{2,4}$/, value = $field.val(); return mail.test(value); } };//电话验证规则$.fn.bootstrapValidator.validators.phone = { //message: "0371-68787027" validate: function(validator, $field, options) { var phone = /^0\d{2,3}-\d{7,8}$/, value = $field.val(); return phone.test(value); } };//区号验证规则$.fn.bootstrapValidator.validators.ac = { //message: "区号如:010或0371" validate: function(validator, $field, options) { var ac = /^0\d{2,3}$/, value = $field.val(); return ac.test(value); } };//无区号电话验证规则$.fn.bootstrapValidator.validators.noactel = { //message: "电话格式如:68787027" validate: function(validator, $field, options) { var noactel = /^\d{7,8}$/, value = $field.val(); return noactel.test(value); } };/*默认规则 end*/$.fn.extend({ initBV: function(config) { //初始化函数 if (this.length == 0 || this[0].tagName !== 'FORM') { return false; } var $form = this.eq(0), $inputs = $form.find('input'), $errors = $form.find('.errors'), $itemBtn = $form.find('.item-btn'); //让ul.errors中显示验证项 function initTips(fields) { var validator, notEmpty, $errField; fields = fields.fields || fields; if (!fields) return false; for (var field in fields) { $errField = $form.find('#errors-' + field); $errField.hide().find('li').remove(); validators = fields[field].validators; notEmpty = false; for (var vali in validators) { $('<li/>') .addClass('text-left') .attr('data-field', field) .attr('data-vali', vali) .html(validators[vali].message) .appendTo($errField); if (vali == 'notEmpty') { notEmpty = true; } } if (notEmpty) { $errField.data('status', 'error'); } else { $errField.data('status', 'success'); } } return false; } initTips(config.fields); $form.bootstrapValidator(config) .on('success.form.bv', function(e, data) { //点击提交之后 // Prevent form submission e.preventDefault(); return false; }).on('success.field.bv', function(e, data) { var removeClass, successClass; if (data.element[0].value) { //验证成功 console.log('real success') removeClass = 'error'; addClass = 'success'; } else { //验证的其实是''(空字符串),但也被算是success事件 console.log('not success'); removeClass = 'error success'; addClass = 'normal'; } $errors.hide(); $form.find('#errors-' + data.field).show().data('status', 'success').find('li').each(function(idx, item) { $(item).removeClass(removeClass).addClass(addClass); }); }).on('error.field.bv', function(e, data) { // data.bv --> The BootstrapValidator instance // data.field --> The field name // data.element --> The field element // Get the messages of field var field = data.field; var messages = data.bv.getMessages(data.element); // Remove the field messages if they're already available $errors.hide(); $form.find('#errors-' + data.field).show().data('status', 'error').find('li').each(function(idx, item) { item = $(item); if (messages.indexOf(item.text().replace('&', '&')) > -1 || config.fields[data.field].validators.notEmpty && messages.indexOf(config.fields[data.field].validators.notEmpty.message) > -1) { item.removeClass('success').addClass('error'); } else { item.removeClass('error').addClass('success'); } }); // Hide the default message // $field.data('bv.messages') returns the default element containing the messages data.element .data('bv.messages') .find('.help-block[data-bv-for="' + data.field + '"]') .hide(); }); $inputs.blur(function(e) { $errors.hide(); }) $inputs.focus(function(e) { $errors.hide(); $(this).trigger('input'); $(this).parent().find('.totalTip').hide(); $form.find('#errors-' + this.name).show(); }) $itemBtn.click(function(e) { e.preventDefault(); $form.find('input').trigger('input'); $('.errors').hide(); return false; }); }, valiFields: function(fields) { //验证fields是否验证通过,未通过则提示信息 var status = true, fieldStatus, $errField, $errFiePar, $totalTip; fields = fields.fields || fields; if (!fields) return false; for (var field in fields) { $errField = $('#errors-' + field); fieldStatus = $errField.data('status'); if (fieldStatus == 'error') { $errFiePar = $errField.parent(), $totalTip = $errFiePar.find('.totalTip'); if ($totalTip.length) { $totalTip.show(); } else { $errFiePar.append('<span>' + fields[field].message + '</span>'); } } status = status && fieldStatus == 'success'; } return status; } });
需要的css文件: bootstrap-validator-my.css(自定义的一个默认配置文件,是个人写的,非官方文件)
bootstrap-validator-my.css内容如下:
* { margin: 0; padding: 0; box-sizing: border-box; }input,button { outline: none; }ul { list-style: none; }/*字体样式*/.text-right { text-align: right; }.text-left { text-align: left; }.text-center,.center { text-align: center; }.bold { font-weight: bold; }/*位置样式*/.relative { position: relative; }.absolute { position: absolute; }.fixed { position: fixed; }/*浮动相关*/.float,.float-left { float: left; }.float-right { float: right; }.clear:after { content: "."; display: block; height: 0; visibility: hidden; clear: both; }.pageWrap { height: auto; min-height: 100%; }/*panel start*/.panel { border: 1px solid #6AC7DC; border-radius: 4px; background: #fff; }.panel>div:first-child { border-bottom: 1px solid #6AC7DC; height: 35px; line-height: 35px; border-radius: 4px; }.panel .panel-head { padding: 0 20px; position: relative; }.panel .panel-head .panel-title { font-weight: bold; }.panel .panel-head .panel-btns { position: absolute; right: 20px; }.panel .panel-head .panel-btns span { border-radius: 5px; color: #fff; padding: 2px 8px; }.panel .panel-head .panel-btns span:hover { cursor: pointer; }.panel .panel-head .panel-btns .panel-btn-add { background: #3686D1; }.panel .panel-body { padding: 20px; }.panel .panel-body .panel-table { width: 100%; border-collapse: collapse; text-align: center; }.panel .panel-body .panel-table td,.panel .panel-body .panel-table th { border: 1px solid #E0E0E0; font-size: 14px; padding: 0 8px; font-style: normal; }.panel .panel-body .panel-table th { height: 33px; line-height: 33px; }.panel .panel-body .panel-table td { height: 28px; line-height: 28px; }/*panel end*//*所有表单元素样式 start*/.form { display: flex; justify-content: center; padding: 20px; }.form .item-txt,.form .item-sel { width: 300px; height: 30px; line-height: 30px; border: 1px solid #CCCCCC; padding: 0 10px; }.form .item-dis { background: #E3E3E3; color: #999999; }.form .item-dis:hover { cursor: not-allowed; }.form .item { font-size: 0; position: relative; margin-bottom: 15px; }.form .totalTip { position: absolute; left: 386px; top: 0; width: 235px; height: 30px; line-height: 30px; color: red; }.form .errors { width: 235px; position: absolute; left: 386px; top: 0; border: 1px solid #ddd; box-shadow: 1px 1px 1px #efefef; background: #f9f9f9; padding: 5px 10px; z-index: 100; }.form .errors li { line-height: 20px; padding-left: 18px; font-size: 12px; color: #666; font-family: Tahoma,Helvetica,"Microsoft Yahei","微软雅黑",Arial,STHeiti; background: url(reg_icons.png) no-repeat -86px -112px; }.form .errors .arrow { position: absolute; top: 8px; left: -6px; height: 0px; width: 0px; border-top: 6px solid transparent; border-right: 6px solid #ddd; border-bottom: 6px solid transparent; }.form .errors .arrow:after { content: ''; position: absolute; top: -5px; left: 1px; border-top: 5px solid transparent; border-right: 5px solid #f9f9f9; border-bottom: 5px solid transparent; }.form .errors li.normal { background-position: -86px -112px; }.form .errors li.success { background-position: -86px -128px; }.form .errors li.error { background-position: -86px -144px; color: red; }.form .item * { font-size: 14px; }.form .item .item-label { display: inline-block; }.form .item .item-btn { height: 30px; width: 300px; line-height: 30px; display: inline-block; background: #3686D1; color: #fff; font-weight: bold; text-align: center; }.form .item .item-btn:hover { cursor: pointer; }.form .error-cont { color: gray; display: inline-block; text-align: left; font-size: 12px; height: 15px; position: relative; white-space: nowrap; }.form .error-cont .icon { position: absolute; top: 1px; }.form .error-cont .tip { position: absolute; left: 20px; font-size: 12px; }.form .redtip { color: red; font-weight: bold; display: inline-block; height: 30px; line-height: 30px; }/*所有表单元素样式 end*/
需要的img为:
<!DOCTYPE html><html><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>bootstrap-validator-my</title> <link rel="stylesheet" href="bootstrap-validator-my.css"> </head><body> <div> <div> </div> <div> <form id="defaultForm" role="form"action="registerAccount.do" method="post"> <div> <div> <labelfor="username">用户名:</label> <inputtype="text" name="username" id="username" /> <ul id="errors-username" data-status=""> <span></span> </ul> </div> <div> <labelfor="ip">ip:</label> <inputtype="text" name="ip" id="ip" /> <ul id="errors-ip" data-status=""> <span></span> </ul> </div> <div> <labelfor="password">密码:</label> <inputtype="password" name="password" id="password" /> <ul id="errors-password" data-status=""> <span></span> </ul> </div> <div> <labelfor="newpassword">新密码:</label> <inputtype="password" name="newpassword" id="newpassword" /> <ul id="errors-newpassword" data-status=""> <span></span> </ul> </div> <div> <labelfor="repassword">确认密码:</label> <inputtype="password" name="repassword" id="repassword" /> <ul id="errors-repassword" data-status=""> <span></span> </ul> </div> <div> <spantype="submit">确认注册</span> </div> </div> </form> </div> </div> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdn.bootcss.com/bootstrap-validator/0.5.3/js/bootstrapValidator.min.js"></script> <script src="bootstrap-validator-default.js"></script> <script> var config = { fields: { /*验证:规则*/ username: { //验证input项:验证规则 message: 'The username is not valid', validators: { stringLength: { min: 6, max: 30, message: '用户名长度必须在6到30之间' }, regexp: { regexp: /^[a-zA-Z0-9_\.]+$/, message: '用户名由数字字母下划线和.组成' }, notEmpty: { message: '用户名不能为空' } } }, ip: { message: 'ip无效', validators: { ip: { message: 'ip格式不正确' } } }, password: { message: '密码无效', validators: { pw: { // regexp: /.*(?=.*\d)(?=.*[a-zA-Z])(?=.*[~!@#$%^&*_])./, message: '必须包含数字、英文字母、特殊字符' }, stringLength: { min: 8, message: '密码长度须大于等于8位' } } }, newpassword: { message: '密码无效', validators: { regexp: { regexp: /.*(?=.*\d)(?=.*[a-zA-Z])(?=.*[~!@#$%^&*_])./, message: '密码没通过' }, stringLength: { min: 8, message: '密码长度须大于等于8位' }, different: { //不能和用户名相同 field: 'password', //需要进行比较的input name值 message: '新密码不能和旧密码相同' }, identical: { //相同 field: 'repassword', //需要进行比较的input name值 message: '新密码和确认密码要一致' } } }, repassword: { message: '密码无效', validators: { regexp: { regexp: /.*(?=.*\d)(?=.*[a-zA-Z])(?=.*[~!@#$%^&*_])./, message: '密码没通过' }, stringLength: { min: 8, message: '密码长度须大于等于8位' }, different: { //不能和用户名相同 field: 'password', //需要进行比较的input name值 message: '确认密码不能和旧密码相同' }, identical: { //相同 field: 'newpassword', //需要进行比较的input name值 message: '新密码和确认密码要一致' } } } } }; var $form = $('#defaultForm'); $form.initBV(config); $form.find('.item-btn').click(function(e) { if($form.valiFields(config.fields)) { console.log(1) }else { console.log(0) } }); </script></body></html>
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
相关阅读:
sublime怎样快速的创建html头部代码
JS中的常用函数汇总
HTML5的集合
用
和段落
写一个三毛语录
以上就是bootstrap-validator使用详解(代码实例)的详细内容,更多请关注php中文网其它相关文章!
c# – FluentValidation,Validators生命周期并使用Validators检查Db
我有两个问题:
>我应该如何管理验证器的生命周期?可以让他们成为单身人士吗?或者没有区别,我可以根据自己的需要管理生命周期?这里的最佳做法是什么?
> FluentValidation非常好.我一直在使用它进行简单的验证(例如:属性不是空的等).我正在考虑使用它做一些Db验证(比如:属性值是唯一的.)我可以使用StructureMap将我的存储库传递给它,并检查Db的值.这是一个好主意吗?或者我应该在我的服务层而不是在我的IValidator中实现这个逻辑?
如果您在类似场景中使用它,您的体验是什么?
解决方法
>就个人而言,创建验证器的成本并不是很昂贵,所以我不会让它们成为单身人士.我遇到了需要访问HttpContext以要求文件上传的单身人士的问题.会发生什么是第一个HttpContext始终用于验证而不是当前的验证.
我个人建议你不要使用单身人士.
>我实际上一直这样做,我喜欢它.请注意,您注入的任何依赖都应该是有效的.如果您的数据库查询执行全表扫描并需要30秒,那么这不是一个好的体验.就像我上面说的那样,我通常会注入HttpContext来检查文件是否上传,并且我传递了一个DataContext来验证电子邮件是否尚未被采用.
对此疯狂,它是FluentValidation的一个巨大优势,只需确保依赖性在时间和资源方面并不昂贵.
com.beust.jcommander.validators.NoValueValidator的实例源码
public static void validateValueParameter(Class<? extends IValueValidator> validator,String name,Object value) { try { if (validator != NovalueValidator.class) { p("Validating value parameter:" + name + " value:" + value + " validator:" + validator); } validator.newInstance().validate(name,value); } catch (InstantiationException | illegalaccessexception e) { throw new ParameterException("Can't instantiate validator:" + e); } }
关于vue-validator 使用详解和vue中validator方法的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于asp.net-mvc – FluentValidation Autofac ValidatorFactory、bootstrap-validator使用详解(代码实例)、c# – FluentValidation,Validators生命周期并使用Validators检查Db、com.beust.jcommander.validators.NoValueValidator的实例源码等相关内容,可以在本站寻找。
本文标签: