Struggling to make Bootstrap-vue form validation functional

I am encountering an issue with form validation in Vue CLI and Bootstrap. When the page loads, all input fields show as invalid due to being assigned the is-invalid class. I managed to solve this problem by setting the state prop to null when it is false. It seems unusual for the validation to run automatically when the page loads, even though I have followed the bootstrap-vue documentation carefully.

Here's a snippet of my code:

<b-form
            @submit.prevent="addReview"
            name="review-form"
            class="needs-validation"
            novalidate
          >
            <div class="name">
              <label class="sr-only" for="form-input-name">Name</label>
              <b-input
                id="form-input-name"
                class="form-inputs mb-2 mr-sm-2 mb-sm-0"
                v-model="name"
                placeholder="Name"
                required
                :state="isEmpty(this.name) ? true : null"
              ></b-input>
              ...
          </b-form>

The issue arises from the ternary operator which needs three results - null on load to hide error messages, false to display errors on validation, and true to indicate valid input. After struggling with this for days, I would appreciate any help or suggestions regarding this setup. The submit button adds the class was-validated but does not validate inputs properly.

Question:
How can I validate inputs without displaying error messages on page load?

Answer №1

Don't limit yourself to just using a ternary statement in the :state attribute - you can directly link :state to a computed property, offering several advantages (similar to what is demonstrated in the documentation):

  1. You can have more than two conditions, bypassing the restrictions of the ternary statement.
  2. The computed property will assess user input in real-time, ensuring immediate validation of the form input.
  3. Your template code will be cleaner and easier to understand (which is crucial).

I'm building upon your example here, but something like the following should resolve your problem:

<template>
  <div id="app">
    <img width="25%" src="./assets/logo.png" style="margin-bottom: 15px;">
    <b-form>
      <div class="name">
        <label class="sr-only" for="form-input-name">Name</label>
        <b-input v-model="name" id="form-input-name" :state="isNameStateValid"></b-input>
      </div>
    </b-form>
  </div>
</template>

<script>
  export default {
    name: "App",
    data() {
      return {
        name: ""
      };
    },
    methods: {
      isValid() {
        return this.name.length > 3 ? true : false; //your validation criteria goes here
      }
    },
    computed: {
      isNameStateValid() {
        if (this.name) {
          return this.isValid(this.name);
        }
        return null;
      }
    }
  };
</script>

In the above example, you would have a method that validates against your specific criteria (isValid, isEmpty, etc.).

The new computed property, isNameStateEmpty, will utilize the return value of that method, returning false for a failed validation (triggering BootstrapVue's validation failure state), true for a successful validation, or null if this.name does not currently have a value (such as on page load or if a user empties the input field).

Check out a live Codesandbox showcasing this behavior here.

Since the input's v-model (v-bind:value and @change) is connected to our "name" data property, any changes in the input field will automatically update our data property (this.name).

Given that our isNameStateValid computed property depends on this.name, it will continuously reassess with every change in the this.name data property - guaranteeing real-time validation using BootstrapVue's validation system.

I hope this explanation is helpful.

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

When an absolute positioned DIV is nested inside a relatively positioned DIV, it disappears when the page is scrolled

A unique feature of my DIV is that it remains fixed at the top of the page as you scroll. This is achieved by setting its position to fixed. However, within this main container, I have another div with a relative position. While the content in the relative ...

Animation of disappearing blocks covering the entire screen

I am currently working on creating a slider with fading blocks animation similar to the one shown here. The challenge I am facing is making it fullscreen, where the height and width will be variable. This makes using the background-position trick ineffecti ...

Does JSX have an API that can handle self-closing tags, such as <br>, if they are not closed properly?

For my latest project, I've been working on a ReactJS component using JSX and it looks something like this: <script type="text/jsx"> var HelloWorld = React.createClass({ render: function() { return ( < ...

Using Scrollspy with sticky-top in Bootstrap allows for easy navigation and fixed positioning of elements

I'm attempting to recreate a layout similar to the privacy policy page on Twitter. On this page, you'll notice that it is divided into sections with a left menu corresponding to each section. As you scroll down the page, the menu sticks to the ...

What is the best way to notify the JSON code below using jQuery?

I have received a JSON response after using the Reverse Geocoding API from Google. The response includes various address components such as route, sublocality, locality, and political information. { "results": [ { "address_components": [ ...

Is there a way to store JSON data in a constant variable using Node Fetch without encountering the error TypeError [ERR_INVALID_URL]: Invalid URL?

In my current NodeJS project, I am working on extracting data from a JSON file and then sending it to a constant variable in my app2.mjs. The goal is to organize this data into an array of objects and eventually save it into a database. However, when tryin ...

Deliver feedback from NodeJS Server to JavaScript on the client side

I have set up an HTTP server in NodeJS by utilizing the http.createServer(...) method. In my client-side JavaScript file, I sent a query using the POST method to the localhost URL. The server effectively received the data from the client, but now I am enco ...

Change the z-index of divs when clicked

When a button is clicked, I want to iterate through a group of absolutely positioned children divs with varying z-indexes. The goal is for the z-index of the currently visible div to decrease on each click, creating a looping effect where only one div is v ...

What is the best way to navigate back on a button click in jquery AJAX without causing a page refresh?

Is there a way to navigate back without refreshing the page? I am fetching data dynamically using AJAX, but when I try to go back using the browser button, it takes me all the way back to the starting point. Let's look at the situation: 3 Different ...

A series of OR interfaces in TypeScript Interface

Imagine a scenario where there is a choice between multiple interfaces interface a {x:string} interface b {y:string} interface c {z:string} type all = a | b | c Now, consider an object fulfilling all by being of type c When you try to access the propert ...

Displaying a loading spinner using JQuery while content is being loaded into a div

I have a navigation bar with links that load content from corresponding HTML pages into a div next to the navigation bar when clicked. To make it more user-friendly, I want to display a spinner while the content is loading. However, the current code I trie ...

Troubleshoot the reason behind the malfunctioning Console log on the website

I have been troubleshooting why console.log is not printing anything. I have tried defining and enabling debugger mode, but nothing seems to work. https://i.sstatic.net/5clXf.png Check out the website here: Any suggestions on how I can resolve this issu ...

Tips for transferring an entire array to a servlet and retrieving it efficiently

I have been attempting to collect all jqgrid data into one array and send it to a servlet. So far, I have tried the following code snippet: var rows= jQuery("#list").jqGrid('getRowData'); var paras=new Arr ...

Dynamic font size that adjusts as you change the window dimensions

Is there a way to adjust the font size in HTML so that when I resize the window, the text size adjusts accordingly? It's like setting a percentage for the text based on the size of the container it is in. Let me provide an example of what I have in m ...

Saving user input as a local variable to be utilized on a different web page

I am attempting to capture a user input from a form and then utilize that variable on a separate page. This process should be straightforward, but I am not receiving any results and I am unsure of the reason why. Here is the code on the first page: <di ...

Issue with Basic jQuery Demonstration (Failure to Conceal Item)

Below is a jQuery example where an element should be hidden, but it's not working as expected: <html> <head> <script src="../lib/jquery-1.7.1.min.js" type="text/javascript"></script> <script type="text/javascript"> $ ...

Issue with aligning the image product in Bootstrap 4

I'm currently working on creating a basic online shopping page for my PHP training, and I've run into a bit of a roadblock with the HTML portion. Even after using Bootstrap, I'm still struggling to simplify things. When I view the result of ...

Ways to retrieve particular items/properties from the JSON response string

Is there a way to extract and display only the first 3 items from my JSON data instead of the entire string? Below is the code I am currently using to loop through and display my records: <tr v-for="(list) in myData" v-bind:key="list.ema ...

Reacting to URL Changes but Failing to Load the Requested Page

Welcome to my App Component import React, { useEffect } from 'react'; import './App.css'; import Navbar from './components/layout/Navbar'; import Landing from './components/layout/Landing'; import { BrowserRouter as ...

What happens when a JavaScript variable is used inside the $.ajax function and returns null?

I've come across numerous questions that are similar to mine, but unfortunately, I haven't been able to find a solution! My issue involves attempting to open a PHP file while passing certain Javascript variables into the URL using $.ajax. However ...