Exploring the world of Bootstrap Twitter 3.0 alongside the wonders of Knockout

When utilizing Twitter Bootstrap, the validation classes like has-error or has-warning must be added to the wrapping form-group element to style both the input and its label. However, Knockout-Validation directly adds the class to the input element itself.

<div class="form-group has-error">
    <label class="control-label">Input with error</label>
    <input type="text" class="form-control">
</div>

Is there a way to configure Knockout-Validation so that it applies the classes to the div instead of the input?

Answer №1

While thebringking's answer provides some guidance, it doesn't cover all necessary steps. You'll also have to define the errorMessageClass and decorateInputElement parameters.

ko.validation.init({
  errorElementClass: 'has-error',
  errorMessageClass: 'help-block',
  decorateInputElement: true
});

var viewModel = ko.validatedObservable({
  name: ko.observable().extend({
    required: true
  }),
  email: ko.observable().extend({
    required: true,
    email: true
  }),
  submit: function() {

    if (!this.isValid()) {
      this.errors.showAllMessages();
    } else {
      alert('good job');
    }
  }
});

ko.applyBindings(viewModel);
<link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.2/css/bootstrap.min.css" rel="stylesheet" />


<div class="container">
  <form class="form-horizontal">
    <div class="form-group" data-bind="validationElement: name">
      <label class="control-label col-xs-2" for="name">Name</label>
      <div class="col-xs-10">
        <input id="name" class="form-control" type="text" data-bind="textInput: name" />
      </div>
    </div>
    <div class="form-group" data-bind="validationElement: email">
      <label class="control-label col-xs-2" for="email">Email</label>
      <div class="col-xs-10">
        <input id="email" class="form-control" type="text" data-bind="textInput: email" />
      </div>
    </div>
    <div class="form-group">
      <div class="col-xs-offset-2 col-xs-10">
        <button type="submit" class="btn btn-primary" data-bind="click: submit">Submit</button>
      </div>
    </div>
  </form>
</div>


<script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.3/knockout.validation.min.js"></script>

Answer №2

One way to customize knockout validation core is by following this approach:

var initialize = ko.bindingHandlers['validationCore'].initialize;
ko.bindingHandlers['validationCore'].initialize = function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
    initialize(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
    var configuration = ko.validation.utils.getConfigOptions(element);
    // Check if decoration of element is requested
    if (configuration.decorateInputElement && ko.validation.utils.isValidatable(valueAccessor())) {
        var parentElement = $(element).parents(".form-group");
        if (parentElement.length) {
            ko.applyBindingsToNode(parentElement[0], { validationElement: valueAccessor() });
        }
    }
};

This modification ensures that the parent form-group will also have the same styling as the input.

Answer №3

One approach is to utilize the "validationElement" binding handler within the context of a bootstrap form division-

<div class="form-group" data-bind="validationElement: someObservable">
  <label class="control-label" for="inputSuccess">Input with success</label>
  <input type="text" class="form-control" id="inputSuccess">
</div>

It is important to configure the knockout validation plugin to use the bootstrap error class "has-error". This can be done by setting the configuration.

ko.validation.init({errorElementClass:'has-error'})

This method is commonly used in our tool.

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

JavaScript JSON function failing to show

I apologize for my limited knowledge on this matter... We are currently facing an issue with our website's pricing page. The dynamic calculator, which should display the price based on user input of size width and quantity, is not functioning as expe ...

Uploading Files with Vuetify 2 v-file-input and AxiosIn this tutorial, we

After researching extensively on the topic, I reviewed questions such as file-upload-in-vuetify and vuetify-file-uploads, but unfortunately, the solutions provided did not work for me. My current challenge involves utilizing Vuetify 2's <v-file-in ...

How can I eliminate unnecessary gaps in a CSS slider design?

Currently, I am in the process of learning CSS3 and attempting to create a purely CSS slider. Everything has been going smoothly until I encountered an unexpected padding or margin within my slider. After making some adjustments to the margins, the issue ...

Why doesn't setting the SVG viewBox to "0 0 100 100" scale my path to 100%?

My current dilemma involves an SVG path that is only displaying at 50% of its intended size. How can I adjust it to show at 100%? Below is the code snippet in question: <div className="svgPathContainer"> <svg width="100%" he ...

By utilizing jQuery, I am orchestrating the movement of a series of div elements within a container with the simple click of a button

A group of div elements located within a container. When the button is clicked, the train should start moving. <script> $('document').ready(function(){ $("button").click(function(){ $("#train").animate({left: "300px"}, 2000); ...

I would like my division to split into two halves, each with a width of 50%, and be aligned next to each other using fxLayout

<div fxLayout="row" fxLayoutAlign="space-between" style="background-color: blue;"> <div fxLayout="column" style="width: 50%;">1stOne </div> <div fxLayout="column" styl ...

Using specific sections of JSON data to display in an alert message (Vanilla JavaScript)

I am seeking a bookmarklet that, upon clicking, will access JSON data and retrieve the "temp" information to display in an alert indicating the weather with just one click. Is there a method to achieve this or do I need to utilize a different API? Here&ap ...

Transform JavaScript code to integrate with a pre-existing WebSocket within a React.js application

I have created a JavaScript code to establish connections with my own Ruby WebSocket server, where it waits for incoming messages, parses them, and then displays content based on certain conditions (the implementation details are not relevant at the moment ...

Refreshing the webpage with new data using jQuery after an AJAX request is

I'm experiencing a problem where the DOM is not updating until after the completion of the $.each loop. On my website, I have several div elements that are supposed to turn orange as they are being looped over. However, once the data is sent to the s ...

how to implement a delay in closing a window using JavaScript

I am currently developing a Google Chrome extension and I want to express my gratitude to everyone here for tolerating my sometimes silly questions. The functionality of the extension is quite basic but it works smoothly. However, I am facing an issue wher ...

Aligning text vertically within an HTML <a> tag block

Calling all CSS experts! I'm struggling with aligning text to the bottom of a block element with a fixed width and height that contains a background image and a title. I've tried using display: table-cell; and vertical-align: bottom; without succ ...

The Evolution of Bulma's Navigation Menu

Creating a transparent menu in Bulma has been successful for the desktop viewport: VIEW DESKTOP MENU However, when attempting to implement the same design on mobile, the menu ends up like this: VIEW MOBILE/TABLET MENU The mobile version seems to inheri ...

Is there a workaround to prevent me from using overflow: scroll when I addEventListener("touchmove", preventBehavior, false)?

I am developing an iOS app using PhoneGap, and I have encountered a problem where the window cannot be moved due to the code document.addEventListener("touchmove", preventBehavior, false); Although this code prevents the window from moving, it also stops ...

Web Dialogue Dimensions: Adjusting the MDC-Web Dialog Width

When designing a dialog following Material Design guidelines, one issue that often arises is how to handle the width of the dialog on larger viewports such as tablets and desktops. Some sources suggest using increments of 56px for dialog width, but it&apos ...

What could be the reason for this code not waiting for module imports?

Currently, I am facing an issue with dynamically importing modules in a nodejs server running in the development environment. To achieve this, I have implemented an immediately-invoked async function which, in theory, should work perfectly. However, it see ...

How can I show the post JSON response that was retrieved in ReactJS on the same form component that was used to submit the value?

Thank you for your assistance in advance. I am currently developing a web crawler that will operate in the following steps: The user inputs the seed URL (front-end) The user clicks the submit button (front-end) The seed URL is processed by the backend usi ...

The MUI Slide Transition experiences a malfunction when using multiple Slide components simultaneously

I'm having trouble getting the animations to work for each mui Slide when the button is clicked. It seems like they don't want to cooperate and work together. Oddly enough, if you disable one of the slides, the other one starts working fine, but ...

Utilize Vuetify to showcase a vertical layout consisting of a header and a v-card, occupying the full height

<template> <div> <div style="height: 20px; color: yellow"> test </div> <v-card class="markdown-preview" tile> <v-card-text v-html="previewText"> </v-card-text> ...

Effortless AJAX Submission and MySQL Data Refresh

I've hit a roadblock and can't seem to figure things out. I'm getting rid of my current code because it's not working well across different browsers, particularly when it comes to ajax submission. Could someone please provide me with a ...

What is the best way to eliminate the curved border and inset box shadow from the Material UI TextField component in React?

Check out this input field: https://i.sstatic.net/Z6URV.png Notice the inner shadow and curved borders. Take a look at the given code snippet: import React, {Component} from 'react'; import TextField from 'material-ui/TextField'; im ...