preface

Form data verification is required. Html5 was originally used to complete the verification, but the effect is poor and not flexible enough, so custom form verification needs to be carried out. Online plug-ins are too large, and the project does not have so many requirements. Let’s write one ourselves!

Knowledge to prepare

  1. The specific custom instructions of VUE can be found in the official manual. The connection is as follows

Vuejs.org/v2/guide/cu…

This allows you to skip functions and parameters (el, binding, vnode) within specified hook functions.

  • El: bound DOM
  • Binding: Attributes of a directive
  • Vnode: virtual node generated by Vue compilation

    start

  1. The directive declaration needs to be noted that arguments are not bound to the back of the closure method

    Vue.directive('validate', {
    // called when the instruction is first backbound
    bind(el, binding, vnode) {
    }
    }Copy the code
    <form id="red-package" @submit.prevent="submit" v-validate.formData="validate">.<button type="submit" class="save">save</button>
    </form>Copy the code
  2. Analytical parameters

Vue.directive('validate', {
  // VM objects, which are components
  const vm = vnode.context;
  // Get the argument bound to the parameter, which is the rule object
  const validate = binding.value;
  // Get the key of the data
  const dataKey = Object.keys(binding.modifiers)[0];
});Copy the code
  1. Verify rules when input changes
el.addEventListener('change', (e) => {
  try {
    // The name of the input tag triggered by the event
    const changeElName = e.srcElement.name;
    // No validation if no rule is set
    if (validate[changeElName]) {
      // Pass in all the parameters of the form
      validate[changeElName](vm[dataKey]);
      // Add a successful class
      Util.removeClass(e.srcElement, 'success'); }}catch (err) {
    // Throw an exception to add a failed class
    Util.addClass(e.srcElement, 'error'); }});Copy the code
  1. All data is validated at commit time
// There is a better solution
el.getElementsByTagName('button') [0].addEventListener('click', (e) => {
  try {
    // Iterate over the object
    Object.keys(vm[dataKey]).forEach((item) = > {
      if(validate[item]) { validate[item](vm[dataKey]); }}); }catch (err) {
    // Throw an error message
    vm.loading({
      text: 'Please check parameters'}); vm.loaded(1000);
    / / stop the submite.preventDefault(); }});Copy the code
  1. Validation Rule instance
amountRandomUpper({ budget, amountRandomUpper, amountRandomLower }) {
    if (amountRandomUpper < 1) {
        throw new Error('too small');
    }
    if (amountRandomUpper < amountRandomLower) {
        throw new Error('too small');
    }
    if (amountRandomUpper > budget) {
        throw new Error('too small'); }}Copy the code

The end of the

There are still many problems. Do you have any good suggestions to point out