How to create a custom validation directive in Vue.js



Image not found!!

Creating a custom validation directive in Vue.js involves defining a directive that checks the validity of the input and updates the UI accordingly. Here's a basic example of how you can create a custom validation directive for a text input field:

javascript
// Define the custom directive Vue.directive('custom-validation', { bind(el, binding, vnode) { // This function is called when the directive is bound to an element el.addEventListener('input', () => { const inputValue = el.value; // Perform your validation logic here const isValid = validateInput(inputValue); // Update the input's validity status el.setCustomValidity(isValid ? '' : 'Invalid input'); // If you want to update the input's styling based on validity status if (isValid) { el.classList.remove('invalid'); } else { el.classList.add('invalid'); } }); }, }); // Helper function for input validation function validateInput(inputValue) { // Example validation logic return inputValue.length >= 5; }

In this example:

  • We define a custom directive named 'custom-validation'.
  • The bind hook is used to attach an event listener to the input element. This listener triggers whenever the input value changes.
  • Inside the event listener, we perform the validation logic. You can replace validateInput with your own validation function.
  • We use setCustomValidity to set a validation message on the input element. This message will be displayed to the user when the input is invalid.
  • Additionally, we update the input's CSS class to reflect its validity status.

To use this directive in your Vue component template:

vue
<template> <div> <input v-model="inputValue" v-custom-validation /> </div> </template> <script> export default { data() { return { inputValue: '' }; } }; </script> <style> .invalid { border-color: red; } </style>

In this example, the v-custom-validation directive is applied to the input field. Whenever the user types in the input field, the custom validation logic defined in the directive is executed. If the input is invalid, the input field's border color changes to red.