Create unique error messages using Vue validators

Two fields named text and email are included in my template. Below is the structure of the template:

HTML

<!DOCTYPE html>
<html>
<head>
    <title>Vue - Validations</title>
    <script src="Libraries/vue/vue.min.js"></script>
    <script src="Libraries/vue/vuelidate.min.js"></script>
    <script src="Libraries/vue/validators.min.js"></script>
</head>
<body>
<div id="app">
    <h2>Form Validation</h2>
    <input v-model="text" v-on:blur="$v.text.$touch()" :class="status($v.text)">
    <p style="color:red;">{{textErrMsg}}</p>
    <input v-model="email" v-on:blur="$v.email.$touch()" :class="status($v.email)">
    <p style="color:red;">{{emailErrMsg}}</p>
  <pre>{{ $v }}</pre>
</div>
<script src="app.js"></script>
</body>
</html>

JS

Vue.use(window.vuelidate.default)
const { required, minLength,email, numeric, minValue } = window.validators
new Vue({
    el: "#app",
  data: {
    text: '',
    email: '',
    textErrMsg: '',
    emailErrMsg: ''
  },
  validations: {
    text: {
      required,
      minLength: minLength(5)
    },
    email: {
     required,
     email
    }
  },
  methods: {
    status(validation) {
        return {
        error: validation.$error,
        dirty: validation.$dirty
        
         if(validation.text.required){
           this.textErrMsg == "Text is required";
         } else if(validation.text.minLength){
         this.textErrMsg == "Text must be 5 characters";
         }
         
         if(validation.email.required){
           this.emailErrMsg == "Email is required";
         } else if(validation.email.email){
         this.emailErrMsg == "Enter valid email";
         }
      }
    }
  }
})

The goal is to detect validation failure conditions such as required, email, minLength, etc., in the JavaScript file so that appropriate messages can be displayed in the template.

Instead of handling this directly in the template.

<p>{{!$v.text.required ? 'Text is required': !$v.text.minLength ? 'Text must be 5 characters' : '' }}</p>

Access Fiddle link

Answer №1

I have devised two solutions for your issue. The initial one is constructed based on your existing code and the key/value pairs linked to our inputs. On the other hand, the second solution utilizes an inputs object where I iterate through all values to formulate the form.

To enhance the error handling process, I introduced an errorMessages object instead of a mere error string for each value. Moreover, I updated it using vm.$set.

Vue.use(window.vuelidate.default)
const { required, minLength, email } = window.validators

// SOLUTION 1
new Vue({
  el: "#app",
  data() {
    return {
      text: '',
      email: '',
      errorMessages: {},
    }
  },
  validations: {
    text: {
      required,
      minLength: minLength(5)
    },
    email: {
      required,
      email
    }
  },
  methods: {
    status(e) {
      const name = e.target.name;
      const currentValidation = this.$v[name];

      // Reset initially
      this.$set(this.errorMessages, name, "");

      if(!currentValidation.required){
        this.$set(this.errorMessages, name, "Is required");
      } 
      if(typeof currentValidation.minLength !== 'undefined' && !currentValidation.minLength){
        this.$set(this.errorMessages, name, "Must be 5 characters");
      }

      // Email validation
      if(
        typeof currentValidation.email !== 'undefined' && 
        !currentValidation.email && 
        currentValidation.$invalid
      ) {
        this.$set(this.errorMessages, name, "Must be an email");
      }

    }
  }
});

// -------------------------

// SOLUTION 2
new Vue({
  el: "#app2",
  data() {
    return {
      inputs: {
        text: {
          value: '',
          title: 'Text',
          error: ''
        }, 
        email: {
          value: '',
          title: 'E-Mail',
          error: ''
        }, 
      },
      errorMessages: {},
    }
  },
  validations: {
    inputs: {
      text: {
        value: {
          required,
          minLength: minLength(5)
        }
      },
      email: {
        value: {
          required,
          email
        }
      },
    }
  },
  methods: {
    edit(e) {
      const value = e.target.value;
      const name = e.target.name;
      const currentValidation = this.$v.inputs[name].value;
      const currentInput = this.inputs[name];

      // Set the value
      this.$set(currentInput, 'value', value);

      // Reset
      this.$set(currentInput, 'error', '');

      // Implementing validations
      if(!currentValidation.required){
        this.$set(currentInput, 'error', "Is required");
      } 
      if(typeof currentValidation.minLength !== 'undefined' && !currentValidation.minLength){
        this.$set(currentInput, 'error',"Must be 5 characters");
      }


      if(
        typeof currentValidation.email !== 'undefined' && 
        !currentValidation.email && 
        currentValidation.$invalid
      ) {
        this.$set(currentInput, 'error', "Must be an email");
      }

    }
  }
})
input {
  border: 1px solid silver;
  border-radius: 4px;
  background: white;
  padding: 5px 10px;
}

.dirty {
  border-color: #5A5;
  background: #EFE;
}

.dirty:focus {
  outline-color: #8E8;
}

.error {
  border-color: red;
  background: #FDD;
}

.error:focus {
  outline-color: #F99;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="44323121282d2025302104746a736a71">[email protected]</a>/dist/validators.min.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="05737060696c6164716045352b322b30">[email protected]</a>/dist/vuelidate.min.js"></script>

<div id="app">
  <h3>Form Validation</h3>
  <input 
    v-model="text" 
    name="text"
    @input="status"
    @focus="status"
    @blur="$v.text.$touch()" 
  />

  <p style="color:red;">{{errorMessages.text}}</p>

  <input 
    v-model="email" 
    name="email"
    @input="status"
    @focus="status"
    @blur="$v.email.$touch()" 
  />

  <p style="color:red;">{{errorMessages.email}}</p>
</div>

<h1>Group</h1>

<div id="app2">
  <h3>Form Validation</h3>
  
  <template v-for="(input, name) in inputs">
    {{input.title}}
    <input 
      :value="input.value"
      :name="name"
      @input="edit"
      @blur="$v[name].$touch()" 
    />

    <p style="color:red;">{{input.error}}</p>
  </template>

  
  <pre>{{ inputs }}</pre>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using JavaScript's Regex to match sentences, while ensuring any full stops within quotes are ignored

Here is the regular expression: (?:(?:Jr|Master|Mr|Ms|Mrs|Dr|Capt|Col|Sgt|Sr|Prof|Rep|Mt|Mount|St|Etc|Eg)\.\s+|["'“(\[]?)(?:\b(?:(?!(?:\S{1,})[.?!]+["']?\s+["']?[A-Z]).)*)(?:(?:(?:Jr|Master|Mr|M ...

What occurs when there are conflicting export names in Meteor?

After researching, I discovered that in Meteor, If your app utilizes the email package (and only if it uses the email package!) then your app can access Email and you can invoke Email.send. While most packages typically have just one export, there a ...

Vue Codemirror encountering issue with loading imports during initialization

I am attempting to integrate CodeMirror into a component. import 'codemirror-cdn'; import {codemirror} from 'https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d4b4858105e52595850544f4 ...

How can I address multiple buttons with various events using jQuery?

I am new to learning jQuery and I'm currently working on some exercises. However, I've run into an issue with two buttons in the DOM that are supposed to perform different actions. I can't seem to figure out how to assign different functions ...

retrieving serialized object from an ajax request sent to the web server

As a newcomer to web development, I decided to create an ASP.NET project with a web API to test my skills. In the process, I crafted a controller and some JavaScript files as follows: Controller: namespace MyNamespace.Controllers { public c ...

Parsley JS failing to validate

I attempted to validate my form using parsley.js, following the instructions from the official documentation. However, for unknown reasons, it is not functioning as expected. Below is the code snippet: <div class="container"> <div class= ...

Automatically fill in an input field with jQuery by using the value from another input field

I am currently working on a loan calculator and am trying to find a way to automatically populate an interest rate field based on the loan amount entered. Here is an example scenario: For amounts ranging from 0 to 100,000, the interest rate is 4.50 For ...

Error: Service Liferay encountered an unexpected identifier causing a syntax error

Upon clicking on the button labeled "delete save" in the Chrome console, an error is encountered: "Uncaught SyntaxError: Unexpected identifier". Additionally, when this action is performed, an object is printed to the console revealing its data ({company ...

The header row in HTML tables sometimes vanishes unexpectedly after sorting the table

Upon filtering the table, I noticed that the header disappears sporadically. The issue is that the table header row should remain in place regardless of whether or not the characters used for filtering are present in the table rows. In Example 1: When fil ...

Displaying Data in React Table from JavaScript Object

I'm working on a React component that will display a table of data from a JavaScript object called pixarMovies. The initial state is set with this object. My goal is to sort the movies chronologically by date and render them in a table format (refer t ...

When the page loads, a JavaScript function is triggered

My switchDiv function in Javascript is being unexpectedly called when the page loads. It goes through each case in the switch statement, except for the default case. Does anyone know how to solve this issue? $(document).ready(function() { $("#be-button" ...

Enhance Laravel 5 by integrating browserify into the Elixir build process

My workflow for transforming coffee to js using browserify, browserify-shim, and coffeeify looks like this: I work with two main files: app.coffee and _app.coffee, designated for frontend and backend respectively. These files are located in resources/coff ...

What is the best way to retrieve the ID of a conditionally displayed item within a modal component?

I am facing an issue with my notes component where I need to delete a specific note based on its ID after accepting a modal confirmation. It works fine without the modal, but I want to ensure that the note is only deleted when the modal is accepted. This ...

Incorporating an HTML element into a Vue template

I'm currently utilizing a chart component (Chartist) that needs an HTML element to serve as a parent during SVG rendering. The elements that the chart requires are generated within a v-for loop, meaning they are not part of the DOM when the chart is ...

Combine a JSON object and a JSON array by matching the value of the JSON object to the key of the JSON array

I am looking to create a JSON array in node by combining two JSON objects and arrays. `var template = { "key1": "value1", "key3": "value3", "key4": "value3", "key6": "Dummy Value1" }; var data = [ { "value1": "1", "value2": "2", ...

Utilizing jQuery boilerplate to execute functions

I am currently utilizing jQuery Boilerplate from However, I have encountered an issue where I am unable to call the "openOverlay" function within the "clickEvents" function. Oddly enough, I am able to successfully call "openOverlay" within the "init" fun ...

Using ReactJS to Send Props Between Two Components

Currently, in my project, I am working on a payment form that conditionally renders 2 Stripe elements (PaymentRequestForm.js & CheckoutForm.js). While I have successfully passed down props from the main form component FullfillRequest.js to PaymentRequestFo ...

What is the best way to include a post identifier in my ajax request?

Currently, I am looking to enhance my ajax functionality by including a post identifier. At the moment, I identify my posts by checking for the presence of a specific input field. Below is the snippet of code that illustrates this: <input name="id" id= ...

What is the best way to retain data after clicking a button?

I am facing an issue where I need to figure out how to add information to a new page when a button is clicked. For example, let's say I have an "add to cart" button and upon clicking it, I want to store some data. How can I achieve this functionality? ...

Clicking on the image in the Swiper Slider will update the URL

Hi there! I am looking for help with changing the image URL when clicked. Currently, I am using swiper for my image gallery. I want to change this URL: to If anyone has a solution or suggestion on how I can achieve this, please let me know! ...