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

Guide to triggering an event when two distinct keys are pressed simultaneously (Using HTML5 and Javascript)

I'm looking to have my character jump whenever I press any key on the keyboard. Is there a method to achieve this using "case..." functions? Thanks! Jordan ...

What is the best way to retrieve data from a JSON object?

Can the status variable be used as a JSON object? What is the method to access the values of action_success and newIndex within the status object? Server: [HttpPost] public ActionResult UploadFiles() { // save file.. return Json(new { action_suc ...

Determining the value of an object property by referencing another property

Upon running the code below, I encounter the following error message: Uncaught TypeError: Cannot read property 'theTests' of undefined $(document).ready(function() { var Example = {}; Example = { settings: { theTests: $(&apo ...

A step-by-step guide on how to implement a window scroll-controlled color transition

I've implemented jQuery code to change the opacity of my navbar's background as the user scrolls, transitioning from transparent to blue. Here's the snippet: $(window).scroll(function(){ var range = $(this).scrollTop(); var limit = 45 ...

Display my additional HTML content on the current page

Is it possible for my addon to open a predefined html page in the current window when it is started? And if so, how can this be achieved? Currently, I am able to open my addon page in a new window using the following command: bridge.boot = function() { ...

Handling OnClick events in D3 with Websocket Integration

My goal is to implement a Websocket in JavaScript that transmits a variable obtained when clicking on a node in a D3 chart. While I have made progress using static data, I'm struggling with initiating the code upon node click to retrieve the "user inf ...

jQuery fails to modify HTML according to its intended purpose

I've been struggling to update a price using JQuery. Even though the code seems fine when I check the console, the HTML doesn't reflect the changes. Additionally, when I try to log console.log(newPrc), it gives an error saying "newPrc" is not def ...

Node.js module retriever showing as blank

My current challenge involves the creation of a settings class with one getter. Here is how it currently looks: class Configuration { get endpoint() { return 'https://api.example.com'; } } module.exports.Configuration = Configuration; In a ...

Creating a table in React using an object with nested objects

I have 2 different types of JSON APIs and I want to showcase them in a table. The first type has the following structure: data1:[ { "id": 1, "name": "Leanne Graham", " ...

Utilize the i18n tag for seamless translation

I am facing a challenge with my latest Vuejs project. I have implemented vuei18n similar to another project in my company, however, the tag is not working correctly in the new project. After turning off <code>silentTranslationWarn in i18n/index.js, ...

Tips for using rspec to test front end functionality?

In my Rails project, I have incorporated Vue.js using only the core library. Currently, most forms in the project are developed with Vue.js. When testing front-end features like form filling or validations using feature tests in RSpec, I found it to be qui ...

Incorporate a Flask variable into a webpage seamlessly without refreshing the page

I am facing a challenge in importing the variable test_data from Flask to my webpage without having to reload it. I have tried clicking a button, but haven't been successful so far. Any suggestions? Flask: @blueprint.route('/data_analysis' ...

What is the best way to implement ternary operators in a text input field using vue.js 2?

My Vue component looks like this: <template> <div> ... <li v-for="category in categories"> ... <input type="radio" class="category-radio" :value="category.id" (category.id == ...

Insert item at the end of the box and move all elements upwards

Hello! I'm experimenting with creating something using javascript's createElement method. My goal is to achieve an effect similar to this image: https://i.stack.imgur.com/itKUK.gif Currently, my code is functional, but the animation goes from to ...

How to change a value within an array stored in local storage using Vanilla JavaScript?

I recently started learning vanilla JavaScript and followed a tutorial on creating a shopping cart. While the tutorial was helpful, it was cut short and I had to figure out how to update a value in a local storage array by clicking a button on my own. Can ...

Troubles with deploying on Heroku

Every time I try to run my application on Heroku, all I see is: Heroku | Welcome to your new app! Refer to the documentation if you need help deploying. Because of this, I attempted to deploy my app to Heroku using this command: git push heroku master Ho ...

UI experiencing issues with selecting radio buttons

When trying to select a radio button, I am facing an issue where they are not appearing on the UI. Although the buttons can be clicked, triggering a function on click, the selected option is not displayed visually. <div data-ng-repeat="flagInfo in avai ...

Information failed to load into the datatable

i've implemented this code snippet to utilize ajax for loading data into a datatable. However, I'm encountering an issue where the data is not being loaded into the database. $('#new_table').DataTable({ "processing": true, "ser ...

angular trustAsHtml does not automatically insert content

Two divs are present on the page. Upon clicking button1, an iframe is loaded into div1. The same applies to button2 and div2. These iframes are loaded via ajax and trusted using $sce.trustAsHtml. This is how the HTML looks: <div ng-bind-html="video.tru ...

Tips for styling Ajax.ActionLink elements with CSS

Hi there, I'm trying to style a navigation bar using CSS. I'm pulling the navigation bar values from a database using Ajax.ActionLink. I attempted to use JavaScript but encountered an error stating "jQuery is not defined", Here's the cod ...