0
votes

Custom validator I am currently using is:

static digitOnly(digit: string): ValidatorFn {
    return (control: AbstractControl): ValidationErrors | null => {
        const restrict = [];
        for (let i = 0; i < parseInt(digit); i++) {
            restrict.push('0');
        }
        const val = control.value;
        if (val === null || val === '') {
            return null;
        }
        if (restrict.toString().replace(/,/g,'') === val.toString()) {
            return { 'invalidNumber': true };
        }
       const pattern = new RegExp(`^[0-9]{${digit}}$`);
        if (!val.toString().match(pattern)) {
            return { 'invalidNumber': true };
        }
        return null;
    }
}

Descrption:

I want to add a custom validator to an input field which accepts GPA, the requirement is: entered value cannot be more than 400 or empty or 0 or 1

right now: my custom validator is working for the following conditions: validating 000 as invalid which is correct validating 0 or 1 or numeric single digit as invalid which is correct

only problem is that it is accepting values above 400

looking forward for a quick help.

1
I know how help you, I need to certificate if I misunderstood what you said. (“Numeric single digit as invalid which is correct”) so you have to check if the string input value is between [10, 400] and return valid isn’t it? (Invalid in all the other cases) - German Cosano
minimum character required are 3 e.g: 001 is valid, 1 is invalid I want the validator to make any number above 400 invalid - urbaneye

1 Answers

0
votes
import { Directive } from '@angular/core';
import { AbstractControl, NG_VALIDATORS, Validator } from '@angular/forms';

@Directive({
    selector: '[forbidden]',
    providers: [
        {
            provide: NG_VALIDATORS,
            useExisting: ForbiddenValidator,
            multi: true
        }
    ]
})

export class ForbiddenValidator implements Validator {

    /**
     * Verify if the value it is allowed or not
     * @param control form control which is evaluated
     */
    validate(control: AbstractControl): { [key: string]: any } | null {
        if (control.value.length < 3 || control.value === '')
            return { 'forbidden': true };

        let num = parseInt(control.value);
        return num > 400 ? { 'forbidden': true } : null;
    }
}

This would be your custom validator directive, then in your template:

<form #form="ngForm">
  <input nz-input id="property" name="property" [(ngModel)]="someVariable 
  (ngModelChange)="onChange()" forbidden #property="ngModel">

  <div *ngIf="property.invalid && property.errors.forbidden>
       Invalid value
  </div>
</form>