Describes how to develop a bubble style Form validation component based on jQuery. validate and Bootstrap tooltip. validatemediltip

Source: Internet
Author: User

Describes how to develop a bubble style Form validation component based on jQuery. validate and Bootstrap tooltip. validatemediltip

Form Verification is a common requirement in page development. We believe that each front-end developer has experience in this field. There are many mature form verification frameworks on the Internet. Although they do not have much problems by default, in actual work, form Verification may have complicated Personalized Requirements, so we cannot use the default mechanism of these plug-ins to complete these functions, therefore, you need to modify them based on your own needs (after all, you cannot write a perfect verification framework level ). I have used the formValidation verification framework. Although it works well with bootstrap, the validation style is too rigid to meet personalized scenarios. Later I found jquery. validate, I found this framework is quite good, because it only provides the verification mechanism, but does not provide specific verification interaction, there is a lot of custom space. In terms of verification style, there are many forms of interaction, including color, border, animation, text display, and bullet box, it is determined by the needs and their preferences. I prefer to use the validation style of the bubble prompt, because the bubble information is only displayed around the field on the interface, and does not change the content of the form, it seems that the experience is better. This article describes how to use jquery. validate and bootstrap tooltip create a bubble Form Verification idea. If you have some personalized form verification requirements, I hope this article will be of some reference value to you.

Online demo(Click the Save button on the Link Page below or change the value of the form element to trigger verification ):

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

Demo-related logic code:

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

Effect preview:


Component implementation:

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

(Three associated files can be viewed through the above link)

Other items:

1) The verification implementation provided in this article relies on jquery, jquery. validate, bootstrap, and seajs for modular management;

2) the demo in this article is used together with the previously written form component. The relevant articles on form management include:

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

Further enrich and simplify form management components: form. js

Related documents:

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

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

Next let's take a look at how to implement this bubble Form validation.

1. Implementation ideas

Used jquery. validate knows that the default verification mechanism of this plug-in is to wrap the Verification Failed information with a label element after a form Element verification fails, and then insert it to the end of the form element. If we want to replace it with a bubble-type validation, we should first consider canceling the default mechanism of the label element for insertion failure information, because there is a bubble, this label is obviously redundant. Then, modify its verification control logic. When the element verification fails, use the bubble component to display the failure information. When the verification is successful, remove potential bubble components (because this element is initialized if verification fails before ). As for how to deal with these two actions, the simple method is to change the source code, but changing the source code will bring more problems. One is not conducive to upgrading, and the other is not conducive to expansion, in the future, it will be easy to conflict with other personalized verification tasks. The better way is to check the official documentation and find the best api for customization. In this way, the source code can be completely avoided. If we need to transform an existing component to complete another component and have to modify the source code, it is better not to directly write the logic of another component into an existing component, instead, add an appropriate interface to an existing component and then use the interface to complete another component.

Read jquery. the validate document shows that its core api is the validate method, which can be called directly on the jquery object, you can use option to pass many options. Two of them can be used to complete our custom functions: errorPlacement and showErrors. The functions and signatures of these two methods are:

errorPlacement : function(error, element) {…}

Use a method to customize the insert position of the form Element failure information. If this method is an empty function, the failure information will not be inserted into the DOM. It has two parameters. error indicates the jquery object generated by the failure information, and element indicates the jquery object of a single form element.

showErrors: function(errorMap, errorList) {…}

Use a display mechanism to customize verification information. It has two parameters. The first parameter encapsulates all verification failure information for the current verification operation in the form of an Object. The second parameter errorList is an array, each element contains the jq object and Failure Information of the failed form element. In addition, through this. successList in this method, you can also access the list of all successfully verified elements. this successList is also an array, and each element of this method is the DOM object of successfully verified form elements.

By describing the two methods, you can probably know how to complete the custom form verification function:

1) if nothing is done in the option errorPlacement, it will not be inserted into the page during verification;

2) In showErrors, We can traverse through errorList and successList to display tooltip for failed elements, and then remove tooltip for successful elements.

It is a simple description of how jquery. validate is called in my implementation. Only the two options mentioned above are used.


Next, let's take a look at some key points in actual implementation.

2. Detailed Implementation

1) start with Code Organization

This article mainly contains three files:

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

The https://github.com/liuyunzhuge/blog/tree/master/form/src/js/mod/validation (This file contains two files: validate. js and validator. js)

The core file is the mod/validation folder. Where:

Validate. javascript is the core code and contains all the custom logic; validator. js is just for jquery. the default verification information of validate is reset because it is in English by default, and the project environment does not need to consider English, so the file is processed in a unified manner; in addition, if you want to add some global validators, you can also consider adding them here.

Mod/formValidation. js is a file directly referenced on the page. It depends on mod/validation/validate. js, also based on validate. the interface provided by js registers some custom processing. I will describe these custom processing later. Its function is only to validate date. js functions are used in combination with the form-related components I have previously written.

If you are interested in the implementation of this article, but you are not interested in the form-related components I have written, you can simply focus on validate. js and validator. js, because there is no formValidation. js. Their functions are still complete.

2) Newly Added option

In validate. js shows a ults to define the option of the component module implemented in this article, except for jquery. the options related to the validate plug-in are overwritten, and the following options are added to complete richer functions:

useTooltip: true, // Configure whether to enable bubble tips to display verification failure information, enabled by default
tipPlacement: 'right', // The position of the global bubble tip
tooltipDuration: 2500, // how often automatically hide tooltip
fieldConfig: {}, // Configure something by field name, such as:
/ **
 * {
 * title: {
 * fvTipTarget: function ($ field) {return $ field.closest (...);}, // Configure the DOM element associated with the bubble prompt
 * tipPlacement: 'top', // Configure the display position of bubble tips: up, down, left and right
 * tooltipClass: 'tooltip-name', // Configure the css class that needs to be added to the bubble tip component
 * errorPlacement: function (error, element) {}, // Configure the insertion position of field error information
 * fvRelatedTarget: function ($ field) {return ...}, // Configure the DOM elements affected by the correlation when verifying
 *}
 *}
 *
 * Among them fvTipTarget fvRelatedTarget can be two forms of function and jQuery object
 * /
fieldTypeConfig: {}, // Configure some things by field type, such as:
/ **
 * {
 * date: {
 * fvTipTarget: function ($ field) {return $ field.closest (...);}, // Configure a DOM element associated with a bubble when the date field validation fails
 * tipPlacement: 'top', // Configure the display position of the bubble prompt when the validation of the date type field fails: up, down, left and right
 * tooltipClass: 'tooltip-name', // Configure the css class that the bubble prompt component needs to add when the field validation of the date type fails
 * errorPlacement: function (error, element) {}, // Configure the insertion position of error information for date type fields
 * fvRelatedTarget: function ($ field) {return ...}, // The DOM elements affected by the association when verifying when configuring a field of type date
 *}
 *}
 * If you want to define a configuration for all types, set the type name to all, such as all: {errorPlacement: function () {..}}
 * priority:
 * fieldConfig> fieldTypeConfig <type>> Validation.defaultFieldTypeConfig> fieldTypeConfig <all>
 * /

The detailed functions are as follows:

UseTooltip determines whether to enable the bubble verification function. The default value is true. If it is false, the modules provided by validate. js use the default verification mechanism to display the verification logic;

TipPlacement: the position where the global bubble prompt is displayed. You can use the bootstrap tooltip to display it to the upper, lower, and lower sides of an element. This can change the default position of the bubble prompt;

TooltipDuration: configure the time when the bubble is displayed. The logic for displaying bubbles is: Display tootip when verification fails, and then automatically disappears after the time specified by this option expires, when the mouse moves into the failed element again, the tooltip is displayed again and disappears when the mouse moves out.

FieldConfig: it can be used to make some configurations based on the field name. There are configuration examples in the annotations. Configurable options are described as follows:

-FvTipTarget: defines the element on which the bubble is displayed.-tipPlacement: Specifies the position where the bubble prompt of an element is displayed.-tooltipClass: Specifies the css class-errorPlacement of the custom bubble component: customize the Insertion Location of failed information for an element-fvRelatedTarget: other elements that need to be affected during custom element verification, in fact, when the form Element verification fails, the related validClass and errorClass css classes are also managed to other elements synchronously.

It should be noted that fieldConfig is configured based on the field element name, because the corresponding element can only be found based on the name, so the form element must have the name attribute on it, in this way, the configuration items in fieldConfig can be found.

FieldTypeConfig: it can be used to make some configuration based on the field type. Its configuration items are the same as those of fieldConfig, except that the same configuration can be specified for fields of the same type, you must repeat the configuration in fieldConfig.

It should be noted that fieldType is specified by the type attribute on the form element, data-type attribute, or data-fv-type attribute. Priority: data-fv-type> data-type> type. In fieldTypeConfig, you can use the special type "all", which does not need to be specified on the form element. It is used to configure all fields in a unified manner. The defaultFieldTypeConfig object is provided on the static members of the validate. js module. By extending this object, you can provide some default field-based configurations to facilitate unified processing. The last point will be detailed in the static member section.

Some options related to jquery. validate that need to be covered and their descriptions are as follows:

debug: true, // prevent form from submitting automatically after successful verification
submitHandler: $ .noop, // Shield the form submission function after successful form validation, and the external Form component is responsible for submitting
ignore: '[type = "hidden"]: not (.fv-yes), [disabled]: not (.fv-yes) ,. fv-no', // Used to filter elements that do not participate in the verification
errorElement: 'i', // Use the <i> element to wrap the verification failure message
errorClass: 'fv-error', // The corresponding class when the verification fails
validClass: 'fv-valid' // The corresponding class when the verification is successful

You need to add:

A. Why do I want to Prevent Automatic Form submission, because I prefer to control form submission;

B. The ignore part does not completely exclude hidden or disabled form elements. In some cases, hidden elements can also be used for verification.

3) Core Implementation

The core implementation method is the following code:

$ element.validate ($. extend (opts, {
 errorPlacement: function (error, element) {
 if (opts.useTooltip) {
  return;
 }
 // The default way of inserting the validation failure information of the jquery.validate component is: Insert the validation failure information after the element
 // We can customize the insertion method by fieldConfig and fieldTypeConfig 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) {
 // Override this method to display the tooltip when the verification fails
 // Fail to display tooltip by default when tooltip is not enabled
 var successList = this.successList;
 // Process the fields that failed the verification
 if ($ .isArray (errorList)) {
  errorList.forEach (function (item) {
  setRelatedTargetStyle (item.element, opts, 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 the tooltip that might have failed
   showSuccessItem (element, opts, that);
  }
  });
 }
 // The official documentation requires that after customizing showErrors, other processing is fully built-in by calling the following method
 this.defaultShowErrors ();
 }
}));

The two codes should be well understood, because the logic of each part has been extracted and encapsulated separately. You can read the details one by one:


Each of the above methods is relatively simple, so we will not discuss them separately.

4) inherit other api methods provided by jquery. validate

In actual work, the logic of Form Verification is sometimes complicated, especially when adding, deleting, and modifying fields and adding, deleting, and modifying verification rules are involved. Let's look at jquery. the valiate document can also find that it provides more than the validate api, there are many other useful methods, for convenience, so directly put jquery. other validate provided by validate. methods not available in js are inherited:

// Proxy jquery.validate's api method to itself
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) reset Form Verification

A common requirement is that the form needs to be reset sometimes. In this case, besides resetting the values of the form elements, they also have to reset their validation status, although jquery. validate provides related methods, but because we have used the tooltip component and added some other processing, we need to reset the form verification function and customize it, it mainly involves the destruction of tooltip components and restoration of some states:

resetForm: function () {
  var $ element = this. $ element,
  opts = this.options;
  // Clear out the tooltip component and bound events
  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 some static members with attributes and methods. For the methods used, see mod/formValidation. js. Where

DefaultFieldTypeConfig: used to store global configuration items by field type;

ExtendFieldTypeConfig: Used to extend defafielfieldtypeconfig.

ValidateEvents: used to store global custom verification events.

AddValidateEvent and removeValidateEvent are used to add and remove custom verification events.

Why is there a custom validation event? Because under the default mechanism of jquery. validate plug-in, the change event of some form elements does not trigger the verification of the current element, so that the interface cannot feedback the verification status of the element in real time. This is used to automatically register special events of some elements, and actively trigger element verification in these event callbacks.

3. Example

From the demo-related logic code, we can see the actual example:



From this example, we can also see that the new Validation component uses jquery directly. there is no big difference between validate, that is, there are several more options. Both rules and messages are jquery. the option provided by validate, while fieldTypeConfig is the new option. However, in terms of function, the verification method has completely changed to the bubble type verification I expected. This experience is similar to jquery. the default validate experience is definitely much better.

4. Related CSS

Css is also an important part to correctly display the verification results in the demo. The demo-related css can be searched in src/css/form.css. the css related to the verification can pass. keyword fv to search.

5. Summary

This article describes how to use jquery. validate, an existing verification framework, is used to complete personalized form verification functions. In the future, when other personalized verification requirements are met, you can refer to this idea completely, try to do some unified custom components. After all, expansion based on existing results is faster and lighter than self-built. The verification method provided in this article is quite easy to use. It also supports addition, deletion, and modification of verification rules. The method is the same as the official document. Welcome to use and discuss related issues. I will use it in projects, especially in the development of management systems, it is very efficient.

I hope this will help you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!


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.