The custom validation feature in Angular 4 is failing to function as expected

Currently, my focus is on Angular 4 where I have developed a custom validator for checking CGPA values (to ensure it is between 2.0 and 4.0). Although the predefined `Validators.required` works fine, my custom validator seems to be not triggering as expected in the component.ts file.

Below is the implementation of the CGPA Validator:

 function ValidCgpa(cgpa: FormControl): {[s: string]: boolean}  {
  let num = Number(cgpa);

  if(num < 2.0 || num > 4.0)  {
    return {invalidCgpa: true};
  }
 }

Usage of Custom CGPA Validator:

this.educationalDetailsForm = new FormGroup({
  cgpa: new FormControl('', Validators.compose([Validators.required, ValidCgpa]))
});

Here's the corresponding HTML Code snippet:

<input type="text" formControlName="cgpa" placeholder="CGPA">

<div *ngIf="educationalDetailsForm.hasError('ValidCgpa','cgpa') && educationalDetailsForm.get('cgpa').touched">
   Enter a number greater than 2.0 and less than 4.0 for CGPA
</div>

Answer №1

Your validator implementation seems to be incorrect. Perhaps you could consider the following approach (untested):

export function ValidateCGPAFormat(regex: RegExp): ValidatorFn {
  return (control: AbstractControl): {[key: string]: any} => {
    const cgpaValue = Number(control.value);
    if(cgpaValue < 2.0 || cgpaValue > 4.0)  {
       return {invalidCGPA: true};
    }
  };
}

Answer №2

Utilize this method

Implementing a Custom Validator

import { AbstractControl } from '@angular/forms';

export function ValidateGpa(control: AbstractControl) {
  const num = Number(control.value);
  if (num < 0 || num > 4.0) {
    return { invalidGpa: true };
  }
  return null;
}

Incorporate in HTML

<h1>Enter GPA and Verify</h1>
<input type="text"  [formControl]="gpa">
<br>
<div *ngIf="gpa.errors?.invalidGpa">Invalid GPA value</div>

In TypeScript File

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { ValidateGpa } from './validators/valid-gpa.validator';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {

  gpa = new FormControl('', [Validators.required, ValidateGpa]);
}

Experiment with this demo on stackblitz

Answer №3

My preference would be to conduct the validations directly on the HTML, shown in the code snippet below:

<input type="number" required name="cgpa" [(ngModel)]="cgpaValue" #cgpa="ngModel">

<div *ngIf="cgpa.touched && (!cpga.valid || cpga.value < 2 || cpga.value > 4 )">
    CGPA must be greater than 2.0 and less than 4.0 
</div>

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

When trying to import a module in Angular, an error is encountered while using Scully

Exploring the utilization of Scully within my Angular project has presented me with a challenge. In Angular, Modules must be imported in order to use them effectively. However, when attempting to execute Scully through the command line: npm run scully --sc ...

Utilizing Angular 9's inherent Ng directives to validate input components within child elements

In my current setup, I have a text control input component that serves as the input field for my form. This component is reused for various types of input data such as Name, Email, Password, etc. The component has been configured to accept properties like ...

Error: The class you are attempting to access is

Currently, I am utilizing Vite.js along with TypeScript. My TypeScript file is located in 'src/vmodel/VGraph'. Within the index.html file, I import the aforementioned file as follows: <script type="module" src="/src/vmodel/VGrap ...

Angular 6 - Deleting the node_module package to streamline local project modifications

After reviewing our options, we have decided to implement ng2-smart-table for the table grid in our current project. However, we've encountered some limitations with its functionality that do not fully meet our project requirements. As a result, we a ...

Having trouble with Nextjs API Integration - encountering error 404

I'm currently facing a major issue and I've hit a dead end. I've been spending days trying to connect my local nextjs 14 app to the CVENT API, but I keep receiving a persistent 404 error. Here's what is displayed in the frontend console ...

Why is it necessary to redefine the interface and its class in Typescript after initially defining the interface with implements?

interface Filter { rowAddRow: (treeData:Tree[],id:string,filterType:FilterType) =>Tree[] } class FilterAction implements Filter { // I must redeclare here to ensure the correct type for id rowAddRow(treeData:Tree[], id, filterType):Tree[] { ...

What is the best way to utilize moment.js for adding days while excluding weekends?

I have a requirement to set a default follow-up date that is two days ahead of the current date. The existing code for this functionality is as follows: const Notify = moment().add(2, 'days').toDate(); Now, I need to modify this code to exclude ...

"Issues with Ionicons displaying a 404 error in the latest Ionic

After updating npm today, I noticed that many Ionic icons from ionicons.com were returning a 404 error. I came across a workaround which involved modifying the angular.json file. However, I am concerned about encountering the same issue (and potentially ot ...

ngFor failing to properly update when new data is pushed

I am currently working on creating an array of reactive forms in Angular. Here is what I have set up: typesForms: FormGroup[] = []; In my HTML, I loop through this array like so: <form *ngFor="let type of typesForms; let i = index" [formGroup]="types ...

What is the best way to maintain the correct 'this' context for a function that is outside of the Vue

I'm struggling with my Vue component and encountering some errors. <script lang="ts"> import Vue from 'vue'; import { ElForm } from 'element-ui/types/form'; type Validator = ( this: typeof PasswordReset, rule: any, va ...

What steps should I take to correct the scoring system for multi-answer questions in my Angular quiz application?

When answering multiple-choice questions, it is important to select ALL of the correct options in order to increase your score. Selecting just one correct answer and then marking another as incorrect will still result in a score increase of 1, which is not ...

Angular 2 failing to properly set headers for HTTP requests

My header and http call setup is as follows: var headers = new Headers(); headers.set('Authorization','Bearer xxxxxxxxxxx'); this.http.get('http://localhost:8080/outputEndpoints', { headers: headers }). map(res => res ...

Should private members be kept confidential during program execution?

While Typescript's "private" members may not be truly private at runtime, traditional closures maintain the privacy of their members. Is there value in ensuring that private members remain private during runtime? ...

Exploring the benefits of event subscription nesting

One feature I'm currently utilizing is the Angular dragula drag and drop functionality, which enables me to effortlessly move around Bootstrap cards within the view. When an item is "dropped," it triggers the this.dragulaService.drop.subscribe() funct ...

Angular functions fail to update the loop variable

Using the documentSnapshot function in Firestore to verify the existence of a document. The function is executed in a loop up to a value of 5. However, even though the function runs 5 times, the value of 'i' always reflects the last value. The ...

Begin by executing the angular repository on your local machine

Is it possible to run the Angular repository found on GitHub at github.com/angular/angular locally through localhost? The README for the repository does not offer any guidance on running it locally. Running 'yarn' will build the site, but how do ...

What is the best way to convert Observable<Observable<{...}>[ ]> to Observable<{...}[ ]>?

I am currently working on merging two observable objects into a single observable to access data from both. These observables represent documents from separate collections in a NoSQL database, specifically a Cloud Firestore database. Both collections have ...

Vue 3 Composable console error: Unable to access properties of undefined (specifically 'isError') due to TypeError

I recently developed a Vue 3 / TypeScript Composable for uploading images to Firebase storage. The code snippet below illustrates the structure of the ImageUpload interface: interface ImageUpload { uploadTask?: UploadTask; downloadURL?: string; progr ...

Resetting the Angular2 poller in an ng-bootstrap accordion

I am currently utilizing a multi-dimensional array connected to a reactive poller that waits for a database state update. Interestingly, when I initially load the state once, the user interface functions as intended. However, a challenge arises when I act ...

React TypeScript - Module not found

Organizational structure: src - components - About.tsx In an attempt to optimize performance, I am experimenting with lazy loading: const About = React.lazy(() => import('components/About')); However, Visual Studio Code is flagging &ap ...