Use Vue.js to display a class when the input is invalid and not empty

How can I apply a has-error class when an input is invalid and not empty in vue.js?

<div class="form-group">
  <input type="email" id="loginEmail" name="loginEmail" v-model="loginEmail" required>
  <label for="loginEmail">Email</label>
  <div class="icon form">
    <icon name="email"></icon>
  </div>
</div>

I attempted the following:

<div class="form-group">
  <input type="email" id="loginEmail" name="loginEmail" v-model="loginEmail" required>
  <label for="loginEmail">Email</label>
  <div class="icon form" v-bind:class="loginEmail.checkValidity ? 'has-success' : 'has-error'">
    <icon name="email"></icon>
  </div>
</div>

Vue Code:

var app = new Vue({
  el: '#app',
  data: {
    loginEmail: ''
  }
})

Although this solution displays a class, it remains even after making changes in the input field without refreshing. The has-error class persists.

SOLVED

input:not(:valid):not(:placeholder-shown) + label + .icon.form {
  svg {
    stroke: red;
  }
}

The solution turned out to be surprisingly simple. It was resolved using CSS without relying on vue.js. I regret not thinking of this sooner.

Answer №1

Make sure to include the following code snippet:

computed: {
    verifyValidity: function () {
      if(isValidated === true) return true;
      return false;
    }
  }

Then, in your HTML file, add this line of code:

<div :class = { 'has-error':!verifyValidity , 'has-success': verifyValidity} >

Answer №2

If you want to dynamically add a style class, you must pass it as an object

Please note: The object key will be added as a class to the element if the corresponding value is true

<div :class = { 'has-error':loginEmail.checkValidity , 'has-success': true  } >

For more information, refer to the official vue documentation - https://v2.vuejs.org/v2/guide/class-and-style.html

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

Enhancing your website's design with dynamic CSS variables using JavaScript

Is there a way to update CSS variables specifically scoped under a certain CSS class (or even other complex CSS selectors) that are predefined in a stylesheet? This question extends beyond just CSS variables and includes other CSS properties as well, quest ...

Is it possible to execute an ajax function at regular intervals until a specific condition is fulfilled?

My application consists of two JSP pages. One is responsible for the UI, while the other processes the response. UICounter.jsp: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Page</titl ...

I have discovered some amazing jQuery image hover effects that are simply breathtaking –

I have been using the Adipoli jQuery Image Hover Effects plugin, but I am facing issues with changing certain properties. The image is set to change to grayscale initially and then switch to color on hover. However, when I click on the image, it should mai ...

Comparing prevProps and this.props in React Native Redux: What is the most effective method?

Does anyone know how to efficiently handle triggering a function in my React Native app only when a specific prop has changed? This is the current implementation I have: componentDidUpdate(prevProps) { if (prevProps.a !== this.props.a) { <trigger ...

Issue with vue.js: inability to assign multiple classes using a variable component

I am trying to add multiple classes to a div element. One class is static, another one includes a variable, and the last one depends on an inner property. The code snippet below does not produce the desired output: <div v-for="card in cards" : ...

Performing unit testing on two services that reside in separate modules using the Jasmine testing framework

I have developed a service in Angular and you can view it on this PLUNKER. In the RouteService, I am injecting CommonService, $rootRouter, ModalService. Please note the following module structure : CommonService belongs to mysampleapp.core RouteS ...

What steps should I take to ensure that my website can recall the most recent interaction conducted by the user?

Our website features a search form that allows users to look for items on the page. In addition, there is a separate form with checkboxes that enables users to narrow down their searches in hopes of reducing the number of results returned. For example, i ...

Having trouble dynamically adding HTML elements in JQuery

I am dynamically adding HTML elements during runtime using an AJAX call from a JavaScript file. Currently, I am attempting to use a combo box drop-down element to display a list of data. Here is how I am trying to achieve this in my script: $("#myList") ...

Instructions for adding a unique custom external CSS link, such as Bootstrap CSS, to a specific REACT component

Is it possible to incorporate custom CSS from the Bootstrap website into a React component? Since this CSS file cannot be imported directly, what steps should I take to include it? <link href="https://getbootstrap.com/docs/4.5/dist/css/bootstrap. ...

What could be causing my jQuery switch not to function on the second page of a table in my Laravel project?

Having an issue with a button that is supposed to change the status value of a db column. It seems to only work for the first 10 rows in the table and stops functioning on the 2nd page. I'm new and could really use some help with this. Here's the ...

What kind of output should a Server Side Component generate?

Recently, I decided to incorporate the NextPage type from Next.js into my component writing routine after hearing it's a beneficial practice. However, I discovered that it only functions properly with client-side components. When attempting to utilize ...

Arrange the JSON object according to the date value

I am working on a JavaScript project that involves objects. Object {HIDDEN ID: "06/03/2014", HIDDEN ID: "21/01/2014"} My goal is to create a new object where the dates are sorted in descending order. Here's an example of what I want: SortedObject ...

The concept of position() is often mistaken for a function

I am currently developing a slider and have included the code below: $(document).ready(function() { // MAKE SLIDER WIDTH EQUAL TO ALL SLIDES WIDTH var totalWidth = 0; $('.slide').each(function() { totalWidth = totalWi ...

Limit the input to a specific format

Currently developing a JavaScript application, but having some confusion with Regular Expressions. The main goal is to allow users to input a specific format of strings in a text area for the application to process accordingly, thus requiring restriction o ...

The window.addEventListener function is failing to work properly on mobile devices

Hey there! I am facing an issue in my JS code. I wrote this code because I want the menu to close when a visitor clicks on another div (not the menu) if it is open. The code seems to be working fine in developer tools on Chrome or Firefox, but it's no ...

Enter the Kannada language into the HTML text box or input field

My html form consists of about 15 - 20 input and textarea fields. As a user, how can I enter information in Kannda or any other local language? https://i.stack.imgur.com/60PVT.png ...

jQuery event.preventDefault not functioning as expected

I am attempting to use jQuery's preventDefault() method, but when I submit the form, it still displays the default behavior and reloads the page. Here is the code from index.html: <body> <script src="/socket.io/socket.io.js"></script& ...

Access another page by clicking on a link within an HTML document

Is it possible to include an anchor tag in demo1.html that, when clicked, will take the user to the demo2.html page and automatically select a data filter on that page? Here is the code snippet for demo1.html: <li> <div><a href="urunli ...

While working with AJAX, the variable value remains static and is not refreshed

My jQuery code successfully calls a REST Service and handles the response in the AJAX Success event. However, I'm facing an issue where the variable "SelectedVal" (document.getElementById('Text1').value) is not getting updated with each cli ...

Retrieve text by tapping on icon within v-text-field

Is there a way to enable users to copy their login details by clicking on the copy icon? How can I retrieve the value of the relevant v-text-field? I considered using @click:append and connecting it to a method, but I am having difficulty in retrieving th ...