Bootstrap form validation issues

Currently, I am utilizing Vue.js along with Bootstrap for the creation of a website. In this process, I have set up a form on which I am implementing my custom validation logic. Everything seems to be functioning correctly until the moment when the user hits the submit button and the was-validated class is added to the form as per Bootstrap guidelines.

The issue arises at this point, where any required input field with any input - regardless of whether it validates based on my custom logic or not - is marked as valid, displaying a green border and check mark. Interestingly, my custom validation still runs in the background and shows the error message using b-form-invalid-feedback. However, it appears that the was-validated class considers fields with the required property as valid without factoring in my custom validation, resulting in conflicting validation scenarios. A field could have a green check mark due to meeting the required property, yet still display an error because it doesn't pass my custom checks.

I have attempted to remove the :valid style; however, this didn't produce the desired effect as I do want those styles to show up when the field satisfies my custom validation criteria. If this explanation is unclear, I can provide visuals for better understanding. Additionally, there is another issue I encountered - a date picker that fails to trigger the appearance of b-form-invalid-feedback even after adding was-validated.

Snippet of My Code

<b-form @submit.prevent="addReview" name="review-form" novalidate>
  <div class="name">
    ...
  </div>

  ...
  
  <div class="description">
    ...
  </div>

  <b-button type="submit">Save</b-button>
</b-form>
...

Computed Properties and Methods Used

computed: {
        emailStateValidation() {
            ...
        },
        domainStateValidation() {
            ...
        },
    },
    methods: {
        emailIsValid() {
            ...
        },
        domainIsValid() {
            ...
        },
        isStateValid(variable) {
            ...
        },
        addReview() {
            ...
        ...

Specific Questions:

  1. How can I resolve the conflict between the required attribute and my custom validation to prevent premature marking of input fields as valid?
  2. Why is the b-form-invalid-feedback not showing up on the datepicker component upon form submission if a date is not selected?

Answer №1

To simplify, take out the novalidate attribute from the <form> in your Vue template. When you include novalidate, the input fields will retain their :valid status until you explicitly use setCustomValidity. Functional Sandbox

Additionally, because Bootstrap styles both the :valid and :invalid states of inputs, even if custom validators mark inputs as invalid, styles for both valid and invalid states will be applied such as :valid and .is-invalid. It seems that the :valid styles take precedence due to the structure of the Bootstrap stylesheet.

A̶v̶o̶i̶d̶ ̶u̶s̶i̶n̶g̶ ̶̶n̶o̶v̶a̶l̶i̶d̶a̶t̶e̶̶ ̶w̶h̶e̶n̶ ̶y̶o̶u̶ ̶a̶r̶e̶ ̶i̶m̶p̶l̶e̶m̶e̶n̶t̶i̶n̶g̶ ̶a̶ ̶f̶u̶l̶l̶ ̶v̶a̶l̶i̶d̶a̶t̶i̶o̶n̶ ̶s̶y̶s̶t̶e̶m̶ ̶y̶o̶u̶r̶s̶e̶l̶f̶ ̶i̶n̶c̶l̶u̶d̶i̶n̶g̶ ̶t̶h̶e̶ ̶̶r̶e̶q̶u̶i̶r̶e̶d̶̶ ̶v̶a̶l̶i̶d̶a̶t̶o̶r̶.̶

In relation to Bootstrap, it is preferable not to utilize novalidate since it applies styles to both :valid and :invalid states of input elements.

This may lead to browser popups prompting users to fill specific fields which could be undesirable.

Recommendation: Utilize the validated prop on your form and connect it to the form's state, setting it to true in the addReview() function. This will automatically add the was-validated class without the need to directly manipulate the DOM.

UPDATE: By removing novalidate, browser validation is enabled, causing the submit event to no longer trigger on the form. Consequently, the was-validated class is not added. To address this issue, I have adjusted the sandbox to propose a solution by binding the click event to the submit button for validation logic, while using the submit event for actions following successful validation.

Datepicker Update: The reason why the datepicker was always considered valid was due to an error in the isStateValid() method, specifically in the following section:

if(variable) { // "" evaluates to false
   // ...
}

As "" evaluates to false, it will consistently return null. The remedy involves combining the suggestion above regarding maintaining the validated state for the form. Instead of checking if(variable), we now verify if(this.validated) and if it is true, we proceed to evaluate the length and return either true or false.

Answer №2

  1. Essentially, was-validated is not a feature native to bootstrap-vue; it is native to browsers and does not comprehend :state. If you wish to utilize was-validated, custom validations cannot be used. However, an alternative suggestion for implementing custom validations is provided in point 2. This involves utilizing another variable to control when validation should be applied.

  2. Referencing the documentation on bootstrap-vue:

When enabled, the aria-required="true" attribute is added to the component. Handling required validation is the responsibility of your application.

It is important to explicitly determine when validation should be displayed. The functionality of the required attribute may not be clear from the documentation, as it does not impact validation. This could explain why that particular aspect is not functioning correctly. Personally, I set this.showValidations = true globally upon submission so that validations occur at the appropriate time, rather than prematurely or belatedly. In your situation, you can monitor the presence of the was-validated class that you have manually included. Although not ideal, it appears to be necessary in this case.

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

Various methods for deactivating controls in a CSS class

Is there a way to disable all buttons within a specific class? I have attempted the following code without success: $("input.myClass").attr('disabled', true); This is how I am trying to implement it: <script type="text/javascript> ...

Having trouble getting Vue to properly focus on an input field

I am attempting to use this.$refs.cInput.focus() (cInput being a ref) but it seems to not be functioning as expected. I expect that when I press the 'g' key, the input field should appear and the cursor should immediately focus on it, allowing me ...

Passing the results of sequelize through express after the completion of a forEach iteration

In an express route, I am running a somewhat complex sequelize query that requires me to run a second query afterward to append necessary data to the result: //Get inboxes based on passed params router.get('/:data', function(req, res, next) { ...

Is there a way to extract individual values from a for-each loop in JavaScript?

Would appreciate any guidance on my use of Bootstrap vue table with contentful's API. I'm currently working on implementing a for loop to iterate through an array and retrieve the property values. Although the console.info(episodes); call success ...

Attempting to send a formik form to a specified action URL

Seeking assistance with a simple fix as I navigate through the learning process. I have created an action called addTenant() that is supposed to receive the state and use it to dispatch a post API call, like so: export const addTenant = (tenant) => (di ...

How can I display a PHP variable in JavaScript?

I am having trouble displaying a PHP variable in Javascript; Below is the code I am using: <script type="text/javascript> $(document).ready(function (){ var n=<?php echo json_encode($count)?>; for(var i=0;i<n;i++){ var div ...

Puppeteer with Typescript: Encountering issues during the transpilation process

The issue stems from the fact that I am unable to use Javascript directly due to Firebase Functions Node.JS version lacking support for Async/Await. As a workaround, I have converted the code into Typescript and am currently attempting to transpile it to c ...

Updating Variables Declared in Parent Component from a Child Component in React using NextJS - A Comprehensive Guide

After reviewing the tutorial on React: Reverse Data Flow to update the variables foodObj, input, and buttonClicked declared in the Parent Component file Main.js, using the child component <SearchAndSuggestion>, I encountered an issue. Here is a snipp ...

Obtain the form value upon submission without the need to reload the page

I am facing an issue where I have a form and I want to trigger the display of a div (in the same page) and execute a JavaScript function upon clicking submit, all without causing a page refresh. <form action="#" method="post" name= "form1" id = "form ...

Unspecified locale with Next.js router

Despite extensive research and multiple attempts, I have not been able to find a solution to my problem. That's why I am reaching out for help again. Currently, I am working on a local project and I would like to implement Internationalized Routing f ...

Establishing flow types and generating unchangeable records

Looking to integrate Flow with Immutable.js Records, I've set up my record like this: const MyRecord = new Immutable.Record({id: undefined}) Now when I create records using new MyRecord({id: 1}), Flow gives me an error: constructor call Construct ...

Why does JSON.parse obscure objects in response body when using Node.js?

Whenever I utilize JSON.parse and output some fetched information with the require module, nested objects are shown as [Object]. For example, consider the following code (currently using Node version 10.15): const request = require("request"); const ur ...

Having trouble rendering an object in my ThreeJS project. The error message says: "THREE.OBJLoader: Unexpected line: 'usemap glass'"

I encountered an error while running threejs in an angular 8 application. The objective is to load an object, for which the object and material files were obtained from Kenney assets. Despite referencing examples on the official threejs site and other onli ...

Using TypeScript to test a Vue3 component that includes a slot with Cypress

I'm currently facing challenges setting up a new project. The technologies I am using include Vue3, TypeScript, and Cypress. It seems like the problem lies within the TypeScript configuration. Below is a Minimal Working Example (MWE) of my setup. Any ...

Obtain the string value of `reader.result` from the `FileReader

Struggling to retrieve a string in a reader.onloadend but it's constantly returning my entire function. Here is the function I'm using: uploadFile() { let vm = this; var file = vm.$refs["testeLogo"].files[0]; var reade ...

problem with saving session data

I am attempting to access data from another page using session storage. On my initial page, named home.html function go_to_faq(qnum){ window.open('FAQ.html', '_blank'); sessionStorage.setItem('key2', qnum); } <a s ...

Our system has picked up on the fact that your website is failing to verify reCAPTCHA solutions using Google reCAPTCHA V2

Error Message We have noticed that your website is not validating reCAPTCHA solutions. This validation is necessary for the correct functioning of reCAPTCHA on your site. Please refer to our developer site for further information. I have implemented the re ...

Dot/Bracket Notation: flexible key assignments

I have an item that contains various image URLs accessed through data[index].gallery.first.mobile/tablet/desktop "gallery": { "first": { "mobile": "./assets/product-xx99-mark-two-headphones/mobile/image-gallery-1.j ...

Guide on Fetching an Image from a Server with Vue Js

I am trying to fetch an image from the server using Vue.js and Laravel. Below is my code: Controller public function index() { $posts = Post::all(); return response()->json(["posts" => $posts]); } Router Route::get('test','Mas ...

What is the proper way to incorporate quotation marks within other quotation marks?

Is there a way to generate an ID within the myFunction() function in JavaScript? I need a single string to call an HTML script as a variable. Any corrections or suggestions are welcome. Here is a sample code snippet: <button class="tablinks" onclick=" ...