SoFunction
Updated on 2025-04-04

Implementation of vue input tag universal instruction verification

Mobile terminals usually require some verification for input tag input, and vue instructions can achieve the effect of perfect verification.

Expected results

<input v-model="times" :data-last_value="lastTimes" v-int v-max="8" v-min="2" />

The value of the attribute data-last_value is used to cache the value entered after the user input box lost focus lastTimes is an initialized variable and will not change this value at will in the future. v-model must not bind the same variable with data-last_value, because this will not cause the user to remember the last input value and use this value to use it if the verification does not pass.

Instruction implementation

The following 3 instructions can be used completely independently

Verify integers

 const util = {
  isNumber(str) {
    const num = Number(str);
    return (num) === num;
  }
 };
 directives: {
  int: {
   inserted: (el) =&gt; {
    let oldListener = ;
     = (e) =&gt; {
     if (oldListener) {
      oldListener(e);
     }
     const blurValue = Number();
     // Use the data-last_value attribute value to cache the last value to restore     const lastValue = ('data-last_value');
     if (!(blurValue)) {
      ('Please enter the number');
       = lastValue;
      (new Event('input'));
     }
     if ( === lastValue) return;
     // Update the last value     ('data-last_value', );
    }
   },
  },
 }

Check the minimum value

directives: {
  min: {
   inserted: (el, binding) =&gt; {
    const oldListener = ;
     = (e) =&gt; {
     if (oldListener) {
      oldListener(e);
     }
     const blurValue = Number();
     const min = ;
     if (blurValue &lt; min) {
      // Replace it with the toast prompt pop-up window for your own business      (`The minimum value cannot be less than${min}`);
       = min;
      (new Event('input'));
     }
     const lastValue = ('data-last_value');
     if ( === lastValue) return;
     // Update the last value     ('data-last_value', );
    }
   },
  },
 }

Check maximum value

 directives: {
  max: {
   // Definition of instructions   inserted: (el, binding) =&gt; {
    const oldListener = ;
     = (e) =&gt; {
     if (oldListener) {
      oldListener(e);
     }
     const blurValue = Number();
     const max = ;
     if (blurValue &gt; max) {
      (`The maximum value cannot be greater than${max}`);
       = max;
      (new Event('input'));
     }
     const lastValue = ('data-last_value');
     if ( === lastValue) return;
     // Update the last value     ('data-last_value', );
    }
   },
  },
 }

I didn't expect that there were so many details in the small verification command~~~

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.