In Angular, assign an error to a form control and mark it as invalid within a form group custom validator, all without the need to use

How can I set the minTemperature error for the temperature form control in a custom validator within this form group? I want it to be marked as invalid when the value is less than 26 degrees Celsius or less than 80 degrees Fahrenheit, based on the selected unit.

Custom Validator

getTemperatureAndUnitValidator(): ValidatorFn {
    return (form: FormGroup): { [key: string]: any } => {
      const temperatureControl = form.controls['temperature'];
      const selectedTemperatureControl = form.controls['temperatureUnit'];
      const temperature = temperatureControl.value;

      if (selectedTemperatureControl.value.code === 'F' && temperature < 80) {
        return { minTemperature: true };
      } else if (
        selectedTemperatureControl.value.code === 'C' &&
        temperature < 26
      ) {
        return { minTemperature: true };
      }
      return null;
    };
}

Form Group

this.heatIndexForm = new FormGroup(
      {
        temperature: new FormControl(null, [
          Validators.required,
          Validators.pattern(/^-?[0-9]\d*(\.\d+)?$/),
        ]),
        humidity: new FormControl(null, [
          Validators.required,
          Validators.min(0),
          Validators.max(100),
          Validators.pattern(/^-?[0-9]\d*(\.\d+)?$/),
        ]),
        temperatureUnit: new FormControl(new Temperature('Celsius', 'C')),
      },
      { validators: this.heatIndexService.getTemperatureAndUnitValidator() }
    );

Validation Error in HTML

<div class="validation-error"
            *ngIf="temperatureUnit.value.code === 'F' &&
            heatIndexForm.get('temperature').hasError('minTemperature') &&
            heatIndexForm.controls['temperature'].dirty &&
            heatIndexForm.controls['temperature'].value">
            Temperature must be 80&deg;F or higher!
          </div>
  <div class="validation-error"
            *ngIf="temperatureUnit.value.code === 'C' &&
            heatIndexForm.controls['temperature'].hasError('minTemperature') &&
            heatIndexForm.controls['temperature'].dirty &&
            heatIndexForm.controls['temperature'].value">
            Temperature must be 26&deg;C or higher!
          </div>

I attempted to implement this in the custom validator but it's not functioning correctly. The validation error isn't being triggered in the template and the input isn't displaying a red border. I am using pInputText which has a built-in red border that should apply when the input is invalid.

return {temperatureControl: { minTemperature: true }}

I prefer not to use .setErrors.

Answer №1

If you encounter a custom error related to the formGroup, make sure to utilize the following code:

<div class="validation-error" *ngIf="heatIndexForm.errors?.minTemperature">
   {{heatIndexForm.value.selectedTemperatureControl.code=='F'?
                'Temperature must be 80&deg;F or higher!':
                'Temperature must be 26&deg;C or higher!'}}
</div>

Include a class in the input like this:

<input [class.ng-invalid]="heatIndexForm.errors?.minTemperature &&
                           heatIndexForm.get('temperatureUnit').touched">
..
</input>

Keep in mind that your validator function can return a complex object, for example:

{minTemperature:true,errorText:'Temperature must be 80&deg;F or higher!'}
//and 
{minTemperature:true,errorText:'Temperature must be 26&deg;C or higher!'}

To display only

{{heatIndexForm.errors?.errorText}}

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

Problem with memory management in ThreeJS

After developing a ThreeJS app using the canvas renderer to meet project requirements, I encountered a memory and garbage collection issue. As part of the application logic, numerous meshes are created for animations on sections of a flat 2D donut or ring ...

What steps can be taken to resolve the Angular error stating that the property 'bankCode' is not found on type 'User' while attempting to bind it to ng model?

I'm encountering an issue with my application involving fetching values from MongoDB and displaying them in an Angular table. I've created a user class with properties like name and password, but I keep getting errors saying that the property doe ...

While Ajax POST is functional on desktop, it does not seem to work on Phonegap applications or Android

I am facing an issue with a global function that does not seem to work properly in the PhoneGap Desktop app or Chrome Mobile on Android. Surprisingly, it works perfectly fine only in the Chrome PC version. The function is called using an onClick event, a ...

Executing a function should be delayed until all necessary information is obtained from the REST Api

I want to create a chart showing data for each month over the course of 12 months. The data for each month will be retrieved from a REST API. Here is my approach: $.getJSON(link, function(data){ // store data in a variable } Repeat this process 12 t ...

Template does not reflect changes made to filters in real-time

I've been working on filtering my "PriceList" collection and sorting is functioning perfectly. However, I'm experiencing some issues with implementing filters and search functionality. When I click on custom filter buttons, the template doesn&apo ...

Contrasting router and router-deprecated in angular2

After upgrading from version "beta.17" to "2.0.0-rc.1", I am a bit confused about when to use router and when to use router-deprecated. Can someone help clarify this for me? ...

Methods for transferring data from an AJAX function

I have a database containing various links that I would like to retrieve and store within an array. I attempted to achieve this using the following code: var amz = new Array(); function CreateAmazonArray() { $.ajax({ url: "php/amazon_affilia ...

Is it possible to create an HTML form to edit XML data?

I'm currently working on developing a JavaScript plugin that will allow users to easily edit XML files. The idea is to take an XML string representing an object, generate an HTML form dynamically for editing the values, and then save the changes back ...

Issues with patching values in Angular 5 reactive forms when dealing with nested input fields

Currently, I am utilizing Angular 5 along with reactive forms. My form is being dynamically generated based on JSON data provided by the backend. While my structure works well with radio buttons, I encounter an issue when dealing with nested checkboxes at ...

Quick way to determine the size of an array

Here is an array I am working with: var arr = [{a:1, ...},{a:1, ...},{c:2, ...},{a:3, ...},{a:1, ...}] I am trying to find out the length of the array where arr[x].a != 1. Can anyone suggest a better approach than using a for loop and push method? P.S I ...

What is the purpose of Access-Control-Allow-Headers in an HTTP response and why is it important to include it?

I've been working through a tutorial on using express and have come across the following routes: module.exports = function(app) { app.use(function(req, res, next) { res.header( "Access-Control-Allow-Headers", "x-ac ...

Configuring TypeScript for Firefox to recognize specific types such as browser.storage

As per the documentation from Mozilla, I should be able to utilize browser.storage.sync.get in my extension. However, I am encountering some challenges in getting TypeScript to recognize that I can use browser. I have attempted the following (which has wo ...

Exploring the Depths of Observables in Angular2 Guards

I have a Guardian overseeing a specific route. Within the canActivate method, I am trying to perform two HTTP requests, with the second request being dependent on the response of the first one. However, it seems like the second request is not being trigger ...

Steps for creating a personalized popup window

Is there a way to create a custom dialog box that includes images, input fields, and more, similar to the design on this website? Any suggestions on what tools or methods I could use to achieve this? ...

Implementing Angular 8 with Apache: Configuring htaccess for main domain and subdomain applications

I have encountered a perplexing issue with my 2 Angular applications. Both apps function flawlessly when placed in the root directory of a domain on an Apache webserver (hoster). However, I am now facing a challenge as I attempt to relocate them to: App1 ...

Escaping the setTimeout loop

I'm struggling to find a solution for breaking out of a setTimeout loop. for (var i = 0; i < 75; i++) { setTimeout(function (i) { return function () { console.log("turn no. " + i); if (table.game.playerWon) { con ...

Utilizing jQuery for easy drag-and-drop functionality in web development

I have two lists which are currently using jQuery for functionality. An example can be found here. I need the same basic functionality but with some modifications: Instead of just getting all sortable items by clicking "Get items," I want to be able to dr ...

Is there a way to extract the text that lies between two closed HTML

Looking for a solution using jQuery. <pre><marker id="markerStart"></marker> aaaaa <span style='font-family:monospace;background-color:#a0a0a0;'>bbb</span>bb cc<marker id="markerEnd"></marker>ccc </pr ...

Creating Unique Identifiers in ExpressJS

I am currently utilizing mongoose to display admin and user information on a dashboard, but I am encountering difficulty rendering the id of a user. Below is the code I am using: function ensureAuthenticated(req, res, next){ if(req.isAuthenticated()){ ...

"Implementing an infinite scroll feature using AJAX and PHP to dynamically load

Currently, I am in the process of loading a significant number of products on a single page and have decided to use an OnScroll loading approach. The following is the method that I am implementing: <ul id="productContainer"> </ul> JQuery: $ ...