The input field or help text fails to change to a red color when the field contains invalid information

Previously, I developed an Angular 2/4 application using Bootstrap 3 and Reactive Forms for field validation. In this setup, when there was an error in input fields, the border of the field turned red and an error message would display below the field in red font.

Here is an example of how it appeared:

<div class="form-group row"
                [ngClass]="{'has-error':    (sourcesForm.get('sourceName').touched || 
                                            sourcesForm.get('sourceName').dirty) && 
                                            !sourcesForm.get('sourceName').valid }">
                <label class="col-md-2 col-form-label"
                        for="sourceNameId">Source Name</label>
                <div class="col-md-8">
                    <input  class="form-control"
                            id="sourceNameId"
                            type="text"
                            placeholder="Source Name (required)"
                            formControlName="sourceName" />
                    <span class="help-block" *ngIf="(sourcesForm.get('sourceName').touched || 
                                                    sourcesForm.get('sourceName').dirty) && 
                                                    sourcesForm.get('sourceName').errors">
                        <span *ngIf="sourcesForm.get('sourceName').errors.required">
                            Please enter the Source Name.
                        </span>
                        <span *ngIf="sourcesForm.get('sourceName').errors.minlength">
                            The Source Name must be longer than 3 characters.
                        </span>
                        <span *ngIf="sourcesForm.get('sourceName').errors.maxlength">
                            The Source Name is too long.
                        </span>
                    </span>
                </div>
</div>

Currently, I need to transition to Bootstrap 4 but I am facing challenges as neither the error message nor the input-field turns red anymore. How can I achieve the same effect with Bootstrap 4? I attempted changing the class of the parent span block to "form-text" but without success.

Answer №1

If you're interested in the beta version of Bootstrap v4, feel free to explore the Form validation docs for detailed information. This version introduces a new approach to form validation supported by modern browsers that utilizes valid and invalid CSS classes like .was-validated and .invalid-feedback.

For a quick start using Bootstrap 4 beta, here's a code snippet:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet"/>
<form class="container" id="needs-validation" novalidate>
      <label for="validationCustom02">Last name</label>
      <input type="text" class="form-control" id="validationCustom02" placeholder="Last name" value="Otto" required>
      <label for="validationCustom03">City</label>
      <input type="text" class="form-control" id="validationCustom03" placeholder="City" required>
      <div class="invalid-feedback">
        Please provide a valid city.
      </div>
  <button class="btn btn-primary" type="submit">Submit form</button>
</form>

<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
  "use strict";
  window.addEventListener("load", function() {
    var form = document.getElementById("needs-validation");
    form.addEventListener("submit", function(event) {
      if (form.checkValidity() == false) {
        event.preventDefault();
        event.stopPropagation();
      }
      form.classList.add("was-validated");
    }, false);
  }, false);
}());
</script>

For those looking for an approach similar to Bootstrap 3, server-side validation can be used with .is-invalid and .is-valid classes as explained below:

As a fallback, .is-invalid and .is-valid classes may be used instead of the pseudo-classes for server side validation. They do not require a .was-validated parent class.

In case you need information on the alpha version of Bootstrap V4, refer to the Bootstrap V4 Form Validation Docs where examples are provided for your reference.

To adapt from the alpha version to the beta version, remember to change has-error to has-danger.

Answer №2

Here is the resolved answer:

<div class="form-group row">
                <label class="col-md-2 col-form-label"
                        for="sourceNameId">Source Name</label>
                <div class="col-md-8">
                    <input  class="form-control"
                            [ngClass]="{'is-invalid':    (sourcesForm.get('sourceName').touched || 
                                sourcesForm.get('sourceName').dirty) && 
                                !sourcesForm.get('sourceName').valid }"
                            id="sourceNameId"
                            type="text"
                            placeholder="Source Name (required)"
                            formControlName="sourceName" >
                    <span class="invalid-feedback" *ngIf="(sourcesForm.get('sourceName').touched || 
                                                    sourcesForm.get('sourceName').dirty) && 
                                                    sourcesForm.get('sourceName').errors">
                        <span *ngIf="sourcesForm.get('sourceName').errors.required">
                            Please enter the Source Name.
                        </span>
                        <span *ngIf="sourcesForm.get('sourceName').errors.minlength">
                            The Source Name must be longer than 3 characters.
                        </span>
                        <span *ngIf="sourcesForm.get('sourceName').errors.maxlength">
                            The Source Name is too long.
                        </span>
                    </span>
                </div>
</div>

I added [ngClass] to the input tag and assigned it the class is-invalid. I also modified the parent span-class to invalid-feedback.

Answer №3

Although your question may be from a while ago, it's still important to know the best way to validate form-control input fields using reactive forms and Bootstrap 4 for displaying validation. To start, you'll need to add some code to your form:

<form [formGroup]="myForm">
  <div class="form-group">
   <label for="name">First Name: </label>
   <input type="text" class="form-control" formControlName="firstName" id="name">
   <div *ngIf="firstName.touched && firstName.invalid" class="alert alert-danger">
   <div *ngIf="firstName.errors.required">Filling in the name is required!</div>
   </div>
  </div>

In your TypeScript file, you need to implement the logic for conducting the validation.

In the TypeScript file:

 myForm = new FormGroup({
 'firstName':new FormControl('',Validators.required)

 })
 // Getter method
 get firstName(){
 this.myForm.get('firstName');
 }

By following these steps, you will see that the validation is now working. To style the input field with a red border around any invalid inputs, simply add the following CSS class to the component's CSS file:

 .form-control.ng-touched.ng-invalid{border:2px solid red;}

Now you can easily observe the results of your form validation.

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

How to style a triangle-shaped border with CSS transparency

I'm on a quest to create a border with a dynamic triangle effect. So far, I've managed to achieve a basic gradient effect, resulting in the following design: Check out my current design in action However, the background features a gradient that ...

Occasionally, the popup fails to open when a button is clicked. What could be causing this issue? -Asp.net

Have you ever encountered issues with popups not working at times? It seems that there is no specific condition for the popup to appear. The expectation is that whenever a button is clicked, the popup should show up. Where do you think the problem lies in ...

Steps for passing a JSON object as a PathVariable in a Spring controller

Currently, I am in the process of developing a spring application using AngularJS. My goal is to pass a JSON object as a @PathVariable to the spring controller. However, with my existing code, I am facing an issue where when attempting to pass the JSON obj ...

Positioning with Bootstrap CSS libraries

The text next to the logo in the navbar isn't aligning properly (refer to this link for the page -> ). Furthermore, the logo isn't positioning correctly either, and this issue is present in all the navbar codes. I'm utilizing CSS bootstr ...

The uppermost part is malfunctioning

Below is the snippet of code: $('> li', this).each(function (index) { var top_space = $(this).css('padding-top'); $(this).prepend('<div></div>'); $('> div', this).css({ position ...

Designing tables and adherence to WCAG 2 accessibility standards

I'm aware that WCAG 2.0 allows tables for layout purposes, but I keep encountering an error in achecker despite this: Error 245: Data table with multiple rows/columns of headers does not utilize id and headers attributes to identify cells Resolution ...

Issues with Linear-Gradient functionality in NativeScript 8 on Android devices

I recently added a linear-gradient to an image in my NativeScript 8 app. Surprisingly, it seems to work perfectly on iOS, but I'm encountering some issues on Android. Despite trying solutions like using -webkit-linear-gradient(), the desired effect is ...

Connect to a particular section of the webpage with additional top spacing

The navigation on this page is not transparent. Whenever I link to a specific part of the page, some text becomes hidden behind the navigation bar. This is illustrated in the image below: https://i.sstatic.net/h0ExX.png What I desire is a navigation bar l ...

Customize Bootstrap 5: Changing the default color scheme

Currently, I am utilizing Bootstrap 5 (v5.2.1) along with a form on my website. I am attempting to customize the default styles for form validation. Specifically, I want to modify the colored 'tick' or 'check' icon that is displayed wh ...

What causes variations in layouts when using the same CSS grid code across different pages?

I've encountered an issue where the CSS on two pages, with slight color changes, is behaving differently in terms of grid layout. Despite multiple attempts to troubleshoot by adjusting items, grid-template-layout, and other parameters, the issue persi ...

Updating data within rows in Angular 4

Is there a way for me to update the value in my row based on a selected ingredient from a dropdown list? I want the unit price to be patched into the input field when a specific ingredient is chosen. You can find the relevant code snippets by visiting TH ...

How to create a stylish border line to separate rows using CSS

Having some trouble with HTML code... <table class="table table-condensed order-statistics"> <tr class="order-statistics-row"> <div class="row"> <div class="col-lg-4"> Order ID: </div> <div ...

Mobile View Not Displaying Bootstrap Column

I'm currently working on creating a two-column layout, one for text and the other for an image. Everything appears correctly on desktop view, but on mobile devices, the image column is not showing up. How can I adjust it so that on mobile devices, the ...

Updating an existing Observable asynchronously using the pipe method

My scenario involves working with an Observable that is subscribed to via the async-pipe. <ng-container *ngIf="invitations$ | async as invitations"> I initialize this Observable in the ngOnInit function: this.invitations$ = this.getInvitat ...

Learn how to maintain floating labels in a floating state even after text input using only CSS

Figured out how to make labels float above form input fields when focused, but struggling with keeping them floating when text is entered and field is unfocused. Been searching for CSS examples online, but none seem to clarify how to achieve the desired e ...

What could be causing my jQuery handler to not capture my form submission?

I am developing a Ruby web application and using JQuery and AJAX to send/receive data. However, I am facing an issue where pressing the enter key does not submit the form. What should I do to ensure that my form submits successfully? Within my Foundation ...

Tips for identifying when a View has completed rendering?

I am facing a situation where I have multiple GWT widgets displayed within a single view. Within this view, the content is structured as follows: FlowPanel mainPanel = new FlowPanel(); RootPanel.get().add(mainPanel); Label label = new Label("test"); mai ...

Ensuring only one group is open at a time in jQuery when a new group is opened

I need assistance in getting this functionality to work properly. My goal is to have only the clicked group open, while closing all others that are currently open. Here's a specific example of what I am trying to achieve: var accordionsMenu = $(&apo ...

What is preventing form validation from functioning properly with both built-in and cross-field validators?

I've been facing issues while trying to develop a form with built-in validators and cross-field validator. Unfortunately, the functionality is not working as expected and I'm struggling to understand why. The form should contain four types of bu ...

AngularJS function orderBy reverses the array instead of sorting it

I encountered an issue where, after clicking the 'order button', the table does not order as expected. Instead, it reverses all the td elements. For example, 'A', 'C', 'B' becomes 'B', 'C', "A". I ...