tasutep
tasutep

Reputation: 141

Why is this custom validator not working?

Created a new file numbers-not-allowed. Name my be misleading but its just for testing before actual implementation.

If the input value is not hi then error should occur. What am i doing wrong.

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

export function NumbersNotAllowed(control: AbstractControl) {
    if (control.value !== 'hi') {
      return { containsNumber: true };
    }
    return null;
  }

In the ts file

     import { NumbersNotAllowed } from '../validators/numbers-not-allowed'; 
        ngOnInit() {
            this.contactForm = this.formBuilder.group({
              fullName: ['', [Validators.required, Validators.maxLength(70)], NumbersNotAllowed],
        }
        //for convience easy access to form fields
         get c() { return this.contactForm.controls }

    onSubmit() {
        console.log(this.contactForm.value);
        this.submitted = true;
        if (this.contactForm.invalid) {
          return;
        }
      }
}

Html template. The rest of the validation works except the custom one.

 <form [formGroup]="contactForm" (ngSubmit)="onSubmit()" class="apply-form">
       <div *ngIf="c.fullName.hasError('containsNumber')" data-tip="Error from custom validator"></div>
       <div *ngIf="c.fullName.touched">
       <div *ngIf="c.fullName.hasError('maxlength')" data-tip="Full name cannot be larger than 70 characters"></div>
       </div>
      <input formControlName='fullName' (focus)="nameInput()"
      [ngClass]="{'face error-border': (c.fullName.errors?.required && c.fullName.touched) 
      || c.fullName.errors?.required && submitted && c.fullName.pristine}"
      placeholder="Your Full Name" type="text" tabindex="1">
 </form>

Upvotes: 0

Views: 348

Answers (3)

Sucharitha Suchi
Sucharitha Suchi

Reputation: 328

I have some simple custom validation using Regular Expressions this helps when number of validations increasing for the inputs. I have applied it on your code , sharing the link.Check if it helps https://stackblitz.com/edit/angular-9omtlr?file=src%2Fapp%2Fapp.component.ts

Upvotes: 1

ashish.gd
ashish.gd

Reputation: 1768

Move your custom validator to the sync validators array. Example:

Form control syntax is

controlName: ['initalvalue', [sync validators], [async validtors]];

current code:

fullName: ['', [Validators.required, Validators.maxLength(70)], NumbersNotAllowed],

fix:

fullName: ['', [Validators.required, Validators.maxLength(70), NumbersNotAllowed],

Upvotes: 0

Ashish Ranjan
Ashish Ranjan

Reputation: 12960

Yiu have added the "NumbersNotAllowed" validator as an async validator, add it inside the array in second argument of "fullName" FormControl

ngOnInit() {
    this.contactForm = this.formBuilder.group({
        fullName: ['', [Validators.required, Validators.maxLength(70), NumbersNotAllowed]]
    })
}

Upvotes: 0

Related Questions