Simple to use nice-validator form validation plugin
Foreword
Front-end form validation is to filter invalid data, the first step in false data, toxic data, data security is the first hurdle, although we can not 100% believe that the data submitted by the client (the real check on the server have to be ), but set the front-end form validation is also essential, to write a logic code for a form field to check unrealistic, but also does not want to create the wheel, using a jquery plugin is a good choice, use it to record here in the project the nice-validator form validation plug-in is simple to use
nice-validator, simple, smart, pleasing form validation program, easy to use, rich configuration items, high degree of freedom, of developer-friendly, more of the description please Tell me what network: https://validator.niceue.com/
Coding
We check the login form, registration form IM system as an example, tests using nice-validator
Download ( https://github.com/niceue/nice-validator/releases/tag/1.1.4 ) download nice-validator-1.1.4.zip , leaving only after critical files have downloaded to other We are deleted, and then introduced in the common head head.html
Instructions
nice-validator used in two ways:
(1), DOM binding rule, without JS code, reference: https://validator.niceue.com/docs/dom-bindings.html , typically using the second configuration rule in js
(2), JS configuration rule, non-invasive DOM
// submit the login function the Login () { $ ( "loginForm #") Validator ({. Rules: custom rules {// }, Fields: {// configuration rules userName: 'required;', password: 'required;' } , messages: {// check fails customized prompt }, Valid: function () {// verified by callback $ .post (ctx + "/ imsUser / login", $ ( "# loginForm") serializeObject (),. function (Data) { IF (data.flag) { window.location.href = CTX + "/ imsUser / socketChart /" + data.data.userName + ".html" } the else { // Tip Tip tip.msg(data.msg); } }); } }).trigger("validate"); }
Built-in rules
Plug-built eight rules:
- required - the field is required
- checked - Required, you can also control the number of selected items
- match - comparing the current field to another field
- remote - server authentication result obtaining
- integer - only fill integer
- range - only fill the specified range of the number of
- length - the length values must be specified
- filter - filter value of the current field, is not verified
If a custom rule with built-in rules of the same name, the custom rules take precedence
Custom Rules
$ ( "# myForm") Validator ({. rules: {// custom rules a direct use of regular, intended for use to verify a single regular can do it // 1, using an array parcels regular and error messages, when the rule does not pass tips the message mobile: [/ ^ 1 [3458 ] \ d {9} $ /, ' Please check the phone number format'], // 2, or directly define the regular, additional custom error message (written below messages parameters li), default prompt message or mobile: / ^ 1 [3458] \ d {9} $ / Second, using a function, the function of the embodiment having the maximum flexibility, different verification get any return value, resulting in different verification result: // 1, using the built .test () method of detecting whether a rule matches, by returning if true, otherwise an error message Mobile: function (Element, the params) { return / 1 ^ [3458] \ {D}. 9 $ /. test (element.value) || 'Please check the phone number format'; } // 2, custom validation ajax // You only need to return $ .ajax, and ensure response in line with the return value above description, other plug-ins are automatically processed. // Of course, you can also add success callback to do something else, or add their own custom header Mobile: function (Element) { return $ .ajax ({ url: 'the Check / username.php', of the type: 'POST ', Data: element.name +' = '+ element.value, dataType:' JSON ' }); } more details can be custom rules of function: https: //validator.niceue.com/docs/custom- rules.html }, Fields: {// configuration rules (usage rules) Phone: 'required; Mobile', username: 'required;' }, messages: {// custom validation fails tips mobile: 'Please check the phone number format' }, Valid: function () {// through the callback authentication } .}) Trigger ( "the validate");
Custom Theme
Comes with rules is relatively small, relatively ugly style, but fortunately we have introduced in the language file inside (zh-CN.js) defines the part of the rule, already part of the theme
There are several themes (results, please poke :): https://validator.niceue.com/releases/1.1.4/demo/option-theme.html , we use yellow_right_effect , there is animation, looks better
But found outside the div box partially occluded when we put the project
Therefore, we refer zh-CN.js, in head.html declare a custom theme, and global configuration
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Scope rules
(1) The global
Use $.validator.config()
recommended configuration in the local configuration files (such as: zh-CN.js) in any instance, you can access any of the fields to the rule
.validator.config $ ( the rules: { Mobile: [/ ^. 1 [3-9] \ {D}. 9 $ /, "Please provide a valid phone number"], chinese: [/ ^ [\ u0391- \ uFFE5] + $ /, "please fill out the Chinese character"] } );
(2) The current instance
When calling initialization parameter passing authentication, only valid for instances when the call
$("#myForm").validator( rules: { mobile: [/^1[3-9]\d{9}$/, "请填写有效的手机号"], chinese: [/^[\u0391-\uFFE5]+$/, "请填写中文字符"] } );
(3). 当前字段
只能通过 DOM 方式在表单元素上定义
<input name="demo" data-rule="required;xxx" data-rule-xxx="[/^\d{6}$/, '请输入6位数字']">
效果演示
登录表单
登录校验简单一点,就一个非空校验就OK了
//提交登录 function login() { $("#loginForm").validator({ rules: {//定制规则 }, fields: {//配置规则(使用规则) userName: 'required;', password: 'required;' }, messages: {//定制校验失败提示 }, valid: function () {//验证通过,回调 $.post(ctx + "/imsUser/login", $("#loginForm").serializeObject(), function (data) { if (data.flag) { window.location.href = ctx + "/imsUser/socketChart/" + data.data.userName + ".html" } else { // tip提示 tip.msg(data.msg); } }); } }).trigger("validate"); }
效果
注册表单
注册的时候判断账号是否已经存在,我们之前是这样做的
现在做如下修改,先在controller新增一个查询接口,去掉保存方法里面的校验
修改js代码
//提交注册 function register() { $("#registerForm").validator({ rules: {//定制规则 reusername: function (element) { return _ajax({ url: ctx + '/imsUser/reusername', type: 'post', data: element.name +'='+ element.value, dataType: 'json' }); } }, fields: {//配置规则(使用规则) userName: 'required;reusername', password: 'required', nickName: 'required', email: 'required;email', phone: 'required;mobile', }, messages: {//定制校验失败提示 reusername:"账号已存在!!!" }, valid: function () {//验证通过,回调 let newTime = commonUtil.getNowTime(); $("#createdTime").val(newTime); $("#updataTime").val(newTime); $("#avatar").val("/image/logo.png"); $.post(ctx + "/imsUser/save", $("#registerForm").serializeObject(), function (data) { if (data.flag) { switchover(); } // tip提示 tip.msg(data.msg); }); } }).trigger("validate"); }
effect
postscript
Article to end here, additional parameters nice validator check plug configurations, methods, events, etc. Please introduce specific access to official documents: https://validator.niceue.com/docs/