Customizing input element styling with Angular Reactive Forms validation rules

My current reactive form setup is as follows:

this.loginForm = this._fb.group({
  email: ['', [Validators.required, Validators.pattern('^[A-Za-z0-9._%+-]<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="99b2d9fef4f8f0f5b7faf6f4">[email protected]</a>$')]],
  password: ['', Validators.required]
});

Regarding the HTML structure:

<!------------------------- PASSWORD FIELD ------------------------->
<div class="uk-margin">
  <input type="password" class="uk-input"
         placeholder="Enter Password" formControlName="password">

  <!----- VALIDATION WARNINGS ----->
  <div *ngIf="loginForm.get('password').touched">
    <div *ngIf="loginForm.get('password').hasError('required')">
      <div class="uk-text-danger"> Password is required.</div>
    </div>
  </div>
</div>

In terms of CSS styling:

.ng-valid[required] {
   border: 5px solid #42A948;
 }

.ng-invalid[required] {
   border: 5px solid red; 
 }

The ng-valid/invalid CSS rules are not changing the input field border color as expected. I'm unsure what I might be doing incorrectly. Can anyone provide assistance?

Update:

https://i.sstatic.net/W3jX8.png

Answer №1

ng-invalid and ng-valid classes are automatically applied, but you have the freedom to adjust the CSS to better suit your needs.

ng-valid.ng-touched {
  border: 5px solid #42A948;
}

ng-invalid.ng-touched {
  border: 5px solid red;
}

Answer №2

To implement conditional classes based on errors, you can utilize [ngClass]. Here is an example:

<!------------------------- PASSWORD FIELD ------------------------->
    <div class="uk-margin">
      <input
        type="password"
        class="uk-input"
        placeholder="Enter Password"
        formControlName="password"
        [ngClass]="{'has-error': loginForm.get('password').touched && loginForm.get('password').hasError('required')}">

      <!----- VALIDATION WARNINGS ----->
      <div *ngIf="loginForm.get('password').touched">
        <div *ngIf="loginForm.get('password').hasError('required')">
          <div class="uk-text-danger"> Password is required.</div>
        </div>
      </div>
    </div>

Make sure to define the styles in your CSS for uk-input.has-error:

uk-input.has-error{
  /* Add your custom styles here */
}

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

The click event in jQuery is being blocked by the use of "display:none

Currently, I have implemented a search box feature with search suggestions: <input id="searchBar" /> <div id="searchSuggestion"></div> The searchSuggestion div is dynamically updated using jQuery ajax whenever an input is entered (imple ...

Embedding PHP script within HTML code can enhance website functionality and

I am completely new to PHP and have never worked with it before. I'm interested in running a PHP script from within an HTML file on a Linux system. Can anyone guide me through the process? Below is the code from my HTML file: <!DOCTYPE HTML PUBLI ...

Make the background extend all the way down to the bottom of the page, whether it scrolls or

I am seeking a solution to have the background extend to the bottom of the page, while accommodating both short and long pages. <html> <body> <div id="container">Container of variable height</div> </body> </htm ...

Unable to activate nb-checkbox from Nebular theme in Angular due to unspecified issue

I recently started using the Nebular theme and encountered an issue with a checkbox that isn't functioning properly. HTML <nb-checkbox [value]="checked" (change)="toggle($event)"></nb-checkbox> TypeScript toggle(checked: any) { ...

Sort posts alphabetically by their first letter using jQuery

Currently, I am dealing with a collection of products sourced from WooCommerce and displayed as custom posts through the Elementor page builder at this link: My attempt to incorporate an alphabetical filter using a plugin has not been successful, most lik ...

Fixing W3 Validation Errors in your Genesis theme through CSS requires a few simple steps. Let's

As a newcomer to this forum, I kindly ask for understanding regarding my current issue. Upon checking my website vocaloid.de/Wordpress/ using the W3C CSS validator, I discovered several parsing and value errors. In an attempt to solve this, I disabled all ...

Ways to use the v-if directive to render conditionally based on a property, even if the object may be undefined

Keep in mind that the parent variable is a firebase reference that has already been defined. Using it like this works fine: v-if="parent['key'] == foo" However, when trying to access a child element like this: v-if="parent['key'].ch ...

What's the reason for the align-self: flex-end CSS property not working as expected on a flex div element?

I am trying to align the "Click me" button to the left of the div that contains it. Here is my code: render = () => { return ( <Wrapper> <Body> <span>Title</span> <Desc ...

Vue Labyrinthine Design theme

Looking for some guidance from experienced developers out there! I'm currently exploring how to incorporate Mazeletter as a background feature for each page in an app project I've been working on. This is all new territory for me, so any assista ...

Tips for creating a concise summary of written content

I am interested in creating an AI-powered summary generator for text input within a textarea element. Below is the HTML code snippet I have been working with: <textarea id="summary">Enter your text here</textarea> If you hav ...

When I type text into the form field, JavaScript causes a disruption in the form

I'm attempting to implement a dual-stage user onboarding procedure. Initially, users will input the industry they belong to and then provide a description. Upon clicking submit, my intention is to conceal that portion of the form and reveal the "Creat ...

Each time I use console.log to display a user's radio button choice, the output is consistently lagging by one step

It seems that I am experiencing an issue where the console.log output for a user's radio button selection is always one step behind. This occurs even though I have initially set the default radio button selection to "all". For example, when a user cli ...

Creating a versatile Nuxt build that can be used across multiple environments

In the development of my Nuxt application, I am faced with the task of setting up two distinct environments - staging and production. Besides these, the local environment is also considered as staging. As part of this setup, I need to create specific comma ...

Is it possible to implement the 'opacity' feature on the homepage of my HTML website?

I am currently working on my website and I would like to display a notice to members when they open the site. This notice should only appear once, right above the HTML homepage, as the homepage content may vary for different members. I plan to use 'op ...

Vue: Customize data based on userAgent

As a newcomer to VUE, I am attempting to dynamically modify the disabled value based on the userAgent in order to display or hide the paymentMethod: data() { return { paymentMothods: [ { name: 'Visa che ...

Perform the Checkbox action when it is marked

How to trigger href from input checkbox when it is checked Example of Checkbox Input Code: <input type="checkbox" value="{{$todo -> id}}" name="{{$todo -> ToDoName}}"> JavaScript Code: /* Custom todo list plugin */ $(".todo-list").todolis ...

The event listener for 'ended' is triggering multiple times

I am in the process of developing a music app, and my goal is to have the next song automatically play when the current one ends. However, I am facing an issue where the EventListener seems to be triggered multiple times in succession - first once, then tw ...

Loop through the geometry's index and set each value

I have managed to create the pattern shown in the image successfully. Currently, I am looking for a way to automate this process. Specifically, every second square needs to be mirrored. If you have any suggestions on an easier approach, please share them ...

The CSS menu dropdown fails to function properly on desktop view when there is longer content present

I attempted to merge two different navigation bars, one sticky and the other responsive. The goal was to combine https://www.w3schools.com/howto/howto_js_navbar_sticky.asp with https://www.w3schools.com/howto/howto_js_responsive_navbar_dropdown.asp Curr ...

Having trouble with a basic node.js server test - no results being shown

I am a beginner in the world of node.js and I'm curious about the most effective way to test this type of code. Currently, I have all the code in one file within a netbeans node.js project. Despite having no errors during compilation, I am not receivi ...