ToolTip development of bubble-style form checking components based on jquery.validate and bootstrap a detailed idea _jquery

Source: Internet
Author: User
Tags documentation extend

Form checking is a very common type of requirement in page development and is believed to be experienced by every front-end developer. There are a lot of mature form verification framework on the Internet, although it doesn't have much problem with the default design, but in practice, the form checksum can have more complex personalization requirements, so we can't use the default mechanism of these plug-ins to complete these functions. So you need to change them according to their needs (after all, they are not yet to write a perfect calibration framework of the hierarchy). I have used formvalidation this calibration frame, although it is very good with bootstrap, but the calibration style is too rigid, not too satisfied with the personalized scene And then I found jquery.validate, and I found the framework pretty good because it only provides a validation mechanism, but does not provide specific checksum interaction, there are more custom space. In the calibration style, there are many forms, through color, border, animation, text display, frame and other ways to generate interaction, as to what kind, by the needs and their preferences to decide. I prefer to use the bubble hint of the check style, because the bubble information in the interface is only displayed in the perimeter of the field, but not the contents of the form to change, it looks better experience. This article introduces oneself uses Jquery.validate and Bootstrap's ToolTip to create one kind of bubble form check the idea, if you have some personalized strong form verification demand, hoped this article can have some reference value to you.

Online Demo(click the Save button in the link below or change the value of the form element to trigger the checksum):

Http://liuyunzhuge.github.io/blog/form/dist/html/demo3.html

Demo-related logical code:

Https://github.com/liuyunzhuge/blog/blob/master/form/src/js/app/demo3.js

Effect preview:

Component implementations:

Https://github.com/liuyunzhuge/blog/blob/master/form/src/js/mod/formValidation.js

Https://github.com/liuyunzhuge/blog/tree/master/form/src/js/mod/validation

(There are 3 associated files that can be viewed from the links above)

Other matters:

1 This article provides the verification realization relies on the jquery,jquery.validate,bootstrap, and uses the SEAJS to do the modular management;

2 The demo of this article is combined with the form component previously written to work together, form management related articles are:

Simple and Easy-to-use form data settings and collection management components

Components to further enrich and simplify form management: Form.js

Related documents:

1) jquery.validate Use instructions: https://jqueryvalidation.org/documentation/

2) Tootip Use instructions: http://v3.bootcss.com/javascript/#tooltips

Let's take a look at how to implement this bubble form checksum.

1. Realize the idea

Use Jquery.validate to know, this plug-in default validation mechanism is a FORM element validation failure, the failure of the verification of information with a LABEL element wrapped, and then inserted into the form element behind. If we're going to change to a bubble-type checksum, the first thing to consider is to remove the default mechanism for inserting the label element of the failed message, because the label is obviously superfluous when there is a bubble, and then to modify its validation control logic to display failure information with the bubble component when the element checksum fails. When the checksum succeeds, remove the associated bubble component that may exist (because the element will initialize the associated bubble component if there is a checksum failure before). As for these two actions how to deal with, the simple method is to change the source code, but the source will bring greater problems, one is not conducive to upgrading, the second is not conducive to expansion, in the future to do other personalized check, it is easy to conflict. A better approach would be to check the official documentation and find the best API for customization, which would completely avoid the problem of changing the source code. If we encounter a transformation of an existing component to complete another component, and have to change the source code, the better way is not to direct the logic of another component into the existing components, but in the existing components to add the appropriate interface, and then through the interface to complete another component.

Flipping through Jquery.validate's documents, you can see that its core API is validate, a method that can be invoked directly on a jquery object, and when invoked, you can pass a lot of options through option, with two options, which you can use to complete our custom function : Errorplacement and ShowErrors, the roles and signatures of these two methods are:

Errorplacement:function (Error, Element) {...}

With the insertion position from which to define the failure information for the form element, if the method is an empty function, then the failure information is not inserted into the DOM. It has two parameters, the error represents the jquery object generated by the failure information, and element represents the jquery object for a single form element.

Showerrors:function (Errormap, errorlist) {...}

The display mechanism that is used to customize the checksum information. It has two parameters, and the first parameter, in the form of object, encapsulates all the checksum failures of the current checksum operation; The second parameter errorlist is an array, Each of its elements contains two attribute element and message representing the JQ object and failure information of the failed form element, respectively. In addition to this method, the This.successlist also has access to the list of all validated elements, and this successlist is also an array, each of which is a DOM object that verifies the successful form element.

By using a description of these two methods, you will probably know how to complete the custom form verification function:

1 If you do nothing in errorplacement this option, then the checksum will not be inserted into the page;

2 in ShowErrors, through errorlist and successlist, we can iterate through it, show ToolTip to the failed elements, and then remove the tooltip from the successful element.

The following figure is a simple way of describing the jquery.validate call in my implementation, using only the two options mentioned earlier.

Then let's take a look at some of the key points in the actual implementation.

2. Detailed implementation

1 Speaking from the Code organization

The implementation of this article consists primarily of three files:

Https://github.com/liuyunzhuge/blog/blob/master/form/src/js/mod/formValidation.js

Https://github.com/liuyunzhuge/blog/tree/master/form/src/js/mod/validation (this file contains two files: Validate.js and Validator.js)

The core files are two under the Mod/validation folder. which

Validate.js is the core code that contains all of the custom logic; Validator.js is simply a reset of the default checksum information for Jquery.validate, because it is in English by default, and my project environment does not need to consider English, so in this file to do a unified processing; In addition, if you want to add some global validators, you can also consider adding here.

Mod/formvalidation.js is a file that is referenced directly in the page, and it relies on mod/validation/ Validate.js, at the same time, based on the interface provided by Validate.js, registered a number of custom processing, these custom processing I will explain later, it is only to the function of the validate.js and I wrote the form related components to use.

If you are interested in the implementation of this article, but not interested in the form-related components I write, it is entirely possible to consider focusing only on validate.js and validator.js, because without formvalidation.js, their functionality remains intact.

2 new option added

You can see in validate.js that there is a defaults to define option for the component modules implemented in this article, in addition to overriding the option associated with the Jquery.validate plug-in, the following option is added to accomplish richer functionality:

usetooltip:true,//Configure whether bubble prompts are enabled to display validation failures, and the default enable Tipplacement: ' Right ',//global bubble hint location tooltipduration:2500,// How often to automatically hide ToolTip fieldconfig: {},//is configured by field name, such as:/** * {* Title: {* Fvtiptarget:function ($field) {return $field. Closes T (...);},//Configure the DOM element associated with the bubble hint * tipplacement: ' top ',///Configure the display location of the bubble hint: up or down * tooltipclass: ' tooltip-name ',//Configure the Bubble prompt component to add CSS Class * Errorplacement:function (Error,element) {},//configuration field error message insertion location * Fvrelatedtarget:function ($field) {return ...},//config checksum
Associated DOM Element *} *} * * where Fvtiptarget fvrelatedtarget can be a function and a jquery object in two forms/Fieldtypeconfig: {},//Configure something by field type, such as: /** * {* Date: {* Fvtiptarget:function ($field) {return $field. Closest (...);},//Configure the DOM element associated with the bubble hint when a date-type field validation fails * Tipp Lacement: ' Top ',//Configure the display position of the bubble prompt when the Date Type field checksum fails: up or down * tooltipclass: ' tooltip-name ',//Configure the CSS class that the bubble prompts component needs to add when the date-type field checksum fails Errorplacement:function (error,element) {},//Configure the insertion position of the error message for a date-type field * Fvrelatedtarget:function ($field) {return ...},/ /Configure the DOM element that is associated with the validation when the Date Type field is *} *} * If you want to have all typesDefines a configuration to set the type name to all, such as all: {Errorplacement:function () {.}}} * Priority: * fieldconfig > Fieldtypeconfig<type> > Validation.defaultfieldtypeconfig > fieldtypeconfig< All> *

Detailed functions are as follows:

Usetooltip determines whether to enable bubble checksum, default to True, if the module provided for False,validate.js will use the default checksum mechanism to display the validation logic;

Tipplacement: The location of the global bubble hint, used bootstrap tooltip know, it can be displayed to the top and bottom of an element, through this can change the bubble hint default position;

Tooltipduration: Configures the time the bubble displays. The implementation I provide, when the bubble is displayed, is the logic: when the checksum fails, display Tootip, and then disappear automatically after the time specified by this option, and when the mouse moves into the failed element again, ToolTip again, and then disappears when the mouse moves out.

Fieldconfig: Can be used to make some configuration based on the field name, with an example in the annotation. The configurable options are described below:

-Fvtiptarget: Which element is displayed with the from-definition bubble;-tipplacement: Configure the display position of an element bubble hint-tooltipclass: Custom bubble Component CSS Class- Errorplacement: Customize the insertion position of the failure information for an element-Fvrelatedtarget: Custom element checksum for other elements that require association effects. In fact, when the form element checksum fails, the related validclass and Errorclass two CSS classes are managed synchronously to other elements.

It is important to note that the Fieldconfig is configured based on the field element name, because the corresponding element can only be found by name, so the form element must have a name attribute on it to find the configuration item in Fieldconfig.

Fieldtypeconfig: Can be used to do some configuration by field type, its configuration item is consistent with Fieldconfig, but its advantage is that you can specify the same configuration for the same type of field, the province in the Fieldconfig to repeat the configuration.

Note that FieldType is specified by the type attribute or the Data-type attribute or the Data-fv-type property on the form element, priority: Data-fv-type > Data-type > Type. In Fieldtypeconfig, you can use all this special type, which does not need to be specified on a FORM element to make a uniform configuration of all fields. On the static members of the Validate.js module, the Defaultfieldtypeconfig object is provided, and by extending this object, you can provide a default number of configuration by field type to facilitate some unified processing. The last point is described in detail in the static member section.

Jquery.validate related to some of the option that needs to be overridden and their descriptions are as follows:

debug:true,//prevent validation After the form is automatically submitted
Submithandler: $.noop,//mask Form validation after successful form submission function, the external form component is responsible for submitting
ignore: ' [type= ' Hidden "]:not (. fv-yes), [Disabled]:not (. fv-yes),. Fv-no ',//To filter elements that do not participate in validation
errorelement: ' I ',//Use <i> Elements to package validation failure information
errorclass: ' Fv-error ',//checksum failure of the corresponding class
Validclass: ' fv-valid '//Validation of the corresponding class when successful

it is necessary to add that:

A. Why prevent forms from being submitted automatically because I am more inclined to actively control form submission;

B. Ignore section, not completely exclude hidden or disabled form elements, sometimes hidden elements can also be used for verification.

3) Core Implementation

The core implementation approach is the following code:

$element. Validate ($.extend (opts, {errorplacement:function (error, Element) {if (Opts.usetooltip) {return; The default checksum failure information for the//jquery.validate component is inserted by inserting a checksum failure after the element//We can use the Fieldconfig and fieldtypeconfig to customize the insertion by field and field type var _
 Errorplacement = Getcommonconfig (' errorplacement ', element, opts);
  if (!isfunc (_errorplacement)) {_errorplacement = function () {error.insertafter (element);
 } _errorplacement (Error, Element); Showerrors:function (Errormap, errorlist) {//overwrites this method to display the failure information by default when the checksum fails to display the ToolTip///without ToolTip enabled Var Successlis
 t = this.successlist; The field to process this checksum failure if ($.isarray (errorlist)) {Errorlist.foreach (function (item) {Setrelatedtargetstyle (item.element, opt
  s, true);
  if (Opts.usetooltip) {//Show failed ToolTip Showerroritem (item, opts, that);
 }
  }); 
  } if ($.isarray (successlist)) {Successlist.foreach (function (Element) {Setrelatedtargetstyle (element, opts, false); if (Opts.usetooltip) {//Remove ToolTip showsuccessitem that could have been caused by the previous failure (elemenT, opts, that);
 }
  });
 //Official documentation requirements, after the custom showerrors, by calling the following method completely built-in other processing this.defaultshowerrors (); }
}));

These two codes should be well understood, because the logic of each part has been isolated and encapsulated, and the details can be read individually:

Each of these methods is relatively simple, so do not take apart to introduce.

4) Inherit other API methods provided by Jquery.validate

Because in the actual work, the form verifies the logic sometimes to be very complex, especially relates to the field to have the deletion, the verification rule has the time which the enhancement, So to look at Jquery.valiate's documentation, you can also find that it provides more than validate this API, there are many other useful methods, for convenience, so directly to the jquery.validate provided by the other validate.js do not have to inherit the method:

The Jquery.validate API method is proxied to its own for
(var i in this._validator) {
 if (!) ( I in this) && Isfunc (This._validator[i]) {
 this[i] = (function (context, func) {return
  function () {
   
    return func.apply (context, arguments);
  }
 }) (This._validator, This._validator[i]);
 }

   

5 Form Checksum Reset

A common requirement is to reset the form sometimes, in addition to resetting the values of the form elements, and resetting their checksum state. Although Jquery.validate provides the relevant methods, because we are useful to the ToolTip component and added some other processing, we need to do some customization of the reset function of the form checksum, mainly the destruction of the ToolTip component and the restoration of some states:

Resetform:function () {
 var $element = this. $element,
 opts = this.options;
 Clear out the ToolTip component and the bound event
 if (opts.usetooltip) {
 $element. Find ('. Fv-tip-target '). each (function () {
  var ToolTip = $ (this). Data (' Bs.tooltip ');
  Checkhidetimeout (tooltip);
  ToolTip && Tooltip.destroy ();
 Off ('. FV ');
 }
 $element. Find ('. Fv-related-target '). Removeclass (Opts.validclass + ' fv-related-target ' + opts.errorclass);
 This._validator.resetform ();
}

6) Static Members

Validate.js provides a number of static members, there are attributes and methods, using the method see Mod/formvalidation.js. which

Defaultfieldtypeconfig: Used to store some of the global configuration items by field type;

Extendfieldtypeconfig: Used to extend Defaultfieldtypeconfig.

Validateevents: Some custom checksum events that are used to store the global.

Addvalidateevent and removevalidateevent are used to add and remove custom checksum events.

Why is there a custom checksum event? Because under the default mechanism of Jquery.validate this plugin, some form element's change event does not trigger the current element's checksum, causes the interface not to be able to feedback the element's verification state in real time. This special event that helps us register some elements automatically, and then actively triggers the validation of the elements within those event callbacks.

3. Use examples

From the logical code associated with the demo, see examples of actual use:

As you can see from this example, The new validation component is not much different from the direct use of jquery.validate, which is that more than a few option,rules and messages are jquery.validate provided option, and Fieldtypeconfig is the new optio n; But in function, the way of checking has completely become the bubble check that I expect, this experience is certainly much better than the jquery.validate default experience.

4. Related CSS

In order to correctly display the verification effect in the demo, CSS is also a very important part of the demo-related CSS can be found in the SRC/CSS/FORM.CSS, with the check-related CSS can be used. FV this keyword to search.

5. Summary

This paper describes how to complete the personalized form checking function based on the existing calibration framework of jquery.validate, in the future, when you encounter other personalized verification requirements, you can also fully refer to this idea, try to do some unified custom components, after all, based on the results to expand than to build their own wheels, to come faster and more Light some. This article provides the calibration method, the use is quite cool, also supports the verification rule additions and deletions, the way with official documents, welcome to use and discuss related issues, I use it in the project, especially in the management system inside development, very efficient.

The above mentioned hope to help everyone, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.