What is the best way to handle empty inputs in a class?

I am a novice web developer working on my first application, a small CRUD project. Here is the code I have so far:

<template>
  <CRow>
    <CCol col="12">
      <CCard no-header>
        <CCardBody>
          <h3>
            Create Note
          </h3>
          <CAlert
            :show.sync="dismissCountDown"
            color="primary"
            fade
          >
            ({{ dismissCountDown }}) {{ message }}
          </CAlert>
          
          <!-- Rest of the code goes here -->
        </CCardBody>
      </CCard>
    </CCol>
  </CRow>
</template>

<script>
// JavaScript code goes here
</script>

<style>
// Styling code goes here
.invalid input, textarea, select, checkbox {
  border-color: red;
}
</style>

Currently, the font color and input border change automatically after clicking "Save". I want the border to appear only on empty inputs. How can I achieve this functionality?

Your help will be greatly appreciated! :)

Answer №1

Make sure to include a condition inside the binding class

<CInput label="New Title" type="text" id="newTitle" placeholder="Enter New Title" v-model="newNote.title"
              v-bind:class="[newNote.title == '' ? 'text-warning error' : '']"></CInput>

Answer №2

Make sure to have an error indicator for each input field. It's recommended to organize and track errors in an object.

Example

<CInput label="Enter Title" type="text" id="title" placeholder="Title" v-model="note.title"
                  v-bind:class="{ 'text-danger invalid': errors['title']}"></CInput>

<CInput textarea="true" label="Content" id="content" :rows="9" placeholder="Content.."
                  v-model="note.content" v-bind:class="{ 'text-danger invalid': errors['content'] }"></CInput>

Data

 data: () => {
    return {
      errors: {
        title: false,
        content: false,        
      },
      note: {
        title: '',
        content: '',
        applies_to_date: '',
        status_id: null,
        note_type: '',
      },

Validate Inputs

checkInputs() {
      let errorCount = 0;

      // Check each input field     
      if (!this.note.title){
        this.errors['title'] = true;
        errorCount++;    
      }
      else {
       this.errors['title'] = false;
      }

      if (!this.note.content){
        this.errors['content'] = true;
        errorCount++;    
      }
      else {
       this.errors['content'] = false;
      }

     // Additional validation steps can be added

      return errorCount;
    }

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

Encountering issues with Monaco Editor's autocomplete functionality in React

I'm facing an issue with implementing autocomplete in the Monaco Editor using a file called tf.d.ts that contains all the definitions in TypeScript. Despite several attempts, the autocomplete feature is not working as expected. import React, { useRef, ...

My WordPress loadmore function is not providing any additional posts

Hey everyone, I'm facing a Wordpress issue that I can't seem to resolve. I've checked other posts but haven't found the solution yet. So, I decided to share my code here and seek help. My problem is with trying to load more posts using ...

Tips for adjusting the text color of input fields while scrolling down

I am currently working on my website which features a search box at the top of every page in white color. I am interested in changing the color of the search box to match the background color of each individual page. Each page has its own unique background ...

Exploring Excel files using the exceljs library

Using the exceljs module, I am able to read Excel files when they are in the same folder as my application. The code works perfectly in this scenario: var workbook = new Excel.Workbook(); workbook.xlsx.readFile('Data.xls') .then(function() ...

Avoiding errors on the client side due to undefined levels in a specific response JSON can be achieved using the RESTful API

Below is a straightforward JSON response example: { "blog": { "title": "Blog", "paragraphs": [{ "title": "paragraph1", "content": "content1" }, { "title": "paragraph2", "content": "content2" }, { ...

Encountering issues while attempting to pass a function into axios.then and catch and receiving errors

axios.post('http://localhost:3000/api/v1/login', { email: this.state.email, password: this.state.password }, { headers: { "Access-Control-Allow-Origin": "*", ...

Warning: An unhandled promise rejection occurred while using agenda

I encountered an UnhandledPromiseRejectionWarning while running my project which utilizes the agenda package. Here is the code snippet: agenda.define('transferDBField', (job, done) => { if (this.tPrice) { this.prices.push(this.tP ...

Creating smooth animations in JavaScript without relying on external libraries such as jQuery

Is there a way in JavaScript to make a <div> slide in from the right when hovered over, without relying on jQuery or other libraries? I'm looking for a modern browser-friendly solution. const div = document.querySelector('.fro ...

Exploring the capabilities of incorporating multiple nested if-else statements in an AJAX/JavaScript function

Can anyone help me with this code issue? I am trying to run a function with data received from a CI controller to ajax, but having trouble with multiple if else statements. The code works fine with one if else statement, but not with nested or multiple one ...

Decoding JSON in AngularJS

Looking for assistance in parsing a JSON 2D array with Angular JS and fetching images from the array. Can anyone provide some guidance on this? I have updated my Plunker at this link HTML Code <!DOCTYPE html> <html lang="en" ng-app="myAp ...

The jQuery target is not able to locate the specified element

Why does this code snippet work in one case: jQuery(this).closest("li").find("p").text(); But when enclosed within a function, it fails to produce the desired result: jQuery.each(words, function(i, v) { jQuery(this).closest("li").find("p").text(); } ...

I am looking to include a popover within my modal using Bootstrap version 3.0.2

Hey there, I'm having an issue where the popover that should be inside the modal is actually appearing outside of it in the top left corner, not visible within the modal itself. Below is my index code: <button type="button" id="example" class="bt ...

Getting access to props within a child component's mounting phase

It is commonly understood that when the child component is mounted before the parent component, trying to access props in the child component's mounted period will result in null. However, I recently came across a scenario where props were successful ...

When using AngularJS and Laravel together, the CORS functionality may cause the POST request to halt after the preflight

Once upon a time, there was a bird who dreamt of joining the postal service but failed his preflight test... Using Laravel as a RESTful API and AngularJS/ionic for the app, everything was working smoothly until suddenly... it stopped. The withCredentials ...

What is the best way to ensure that all input is consistently capitalized in vue.js?

As I work on a form with vue.js, I face the need to have inputs in vue that are always capitalized. My initial thought was to use the CSS property text-transform: uppercase; and then transform the data before sending it using data.someData.toUpperCase() ...

Trick to enable editing in Bootstrap Select Combobox

Is there a way for users to add their own options to bootstrap-select? Greetings! I have spent some time searching for a straightforward solution that is compatible with Bootstrap 4 styling. Despite exploring various suggestions, as well as unresolved thr ...

The changing of colors does not function properly when clicked in JavaScript

I am having an issue with a drop-down list that offers two options: blue and green. When I select blue and click on the text input field, its background color alternates between blue and black (the default text field color). The same applies when I choose ...

Preventing FlatList from scrolling when re-sizing

Resizable from the re-resizable package is causing my Flatlist not to scroll properly. Despite having enough elements to trigger scrolling, it fails to do so when the resizable element is present. This issue does not occur when the resizable element is rem ...

mongoose populate method does not return the expected results

My Project Objective I am currently in the process of creating a travel booking platform for a transportation company. One of the key features I am working on is displaying the name of the individual who made the booking on a specific page within the webs ...

Having trouble getting a local npm installation to work from a specific file path?

After following the instructions from this helpful link to install an npm package through a file path, I encountered an error when attempting to use it: Cannot find module '<module_name>' or its corresponding type declaration Are there an ...