angular 4 custom validator is not working

angular custom validator
angular validators
multiple custom validators angular 6
angular custom validator with parameter
custom validator angular not working
angular 7 form validation
angular 4 form validation on submit
custom regex validator angular

i'm working on angular 4 and created a custom validator for cgpa validation (if the cgpa is less tahn 2.0 or greater than 4.0) in the component.ts file but its not triggering but the predefined Validators.required is working properly.

Cgpa Validator:

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

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

Custom Cgpa Validator Calling

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

HTML Code

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

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

I think the way you implemented the validator is wrong, try something like this (not tested):

export function ValidCgpa(nameRe: RegExp): ValidatorFn {
  return (control: AbstractControl): {[key: string]: any} => {
    const num = Number(cgpa.value);
    if(num < 2.0 || num > 4.0)  {
       return {invalidCgpa: true};
    }
  };
}

[How-to] Implement custom form validators with Angular, Form validation is always a hot topic whenever I teach Angular. People usually You can find the full code for that example in that StackBlitz. Like the built-in validators, you do not need to call threeNumbers, just pass it as a reference to this.fb.group:. You do not need the bind call, as Angular calls this internally.

Use this way

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;
}

In html

<h1>Type here and Check</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]);
}

Try this example in stackblitz

Validating form input, In this example, the name control sets up two built-in validators— Validators.​required and Validators.minLength(4) —and one custom validator,  Although this Angular 4 form is declared, at this point it doesn’t know of any Angular 4 supported inputs. Angular 4 is not that invasive to register each input HTML element to the nearest form ancestor. The key that allows an input element to be noticed as an Angular 4 element and registered to the NgForm component is the NgModel directive.

I would prefer doing the validations on the HTML direct as follows:

<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>

Custom Form Validation in Angular, In this post we'll go over how to create a custom validator in Angular for both template-driven and reactive forms. It's on our list, and we're working on it! For validation in template-driven forms, directives are used, so let's go If the errors property of the FormControl / NgModel is not empty then the form  You could create the function for your custom validator inside your component file directly if the validator won’t be used elsewhere, but here we’ll assume re-use and create a validator in a separate file. The Custom Validator Function. For this example, we’ll create a validator that checks if an url entered starts with https and contains

Cross field validation does not work using "validators" key but works , Just play by switching from validators to validator as key to define custom validators. What is the motivation / use case for changing the behavior? Forms are part of almost every web application out there. Angular strives for making working with forms a breeze. While there are a couple of built-in validators provided by the framework, we often need to add some custom validation capabilities to our application’s form, in order to fulfill our needs.

Custom validator's message not showing · Issue #602 · json-schema , I have added a a custom validator and message to one of my form fields: for sf-​message can be found here: https://github.com/OptimalBPM/angular-schema-  An Angular custom validator does not directly take extra input parameters aside from the reference of the control. To pass extra parameters, you need to add a custom validator inside a factory

Angular Form Validation, For the above example, we want to write a custom validation function that validates if there are no spaces in the username. While technically we can write this  Angular: How to implement conditional custom validation. not if the validation input is changed. Now it will work, follow the red border color that indicates invalid field and see that it

Comments
  • Number(cgpa) should be Number(cgpa.value), or simpler: +cgpa.value. Adding logs in the code, or using the debugger makes that very easy to find. A validator is summposed to return null, not undefined, when there is no error, too.
  • thats right, but he says that the validator isn't being invoked, so the line is wrong, but that is not the problem
  • Other than that, the code is correct. If it's not invoked, then a complete example is needed. See plnkr.co/edit/XxZw1icOBLUDLtHgVy7V?p=preview. But my guess is that the OP thinks it's not invoked because the error message doesn't appear.