2

For a Angular 2 application, I wrote a custom validator TypeScript class like below,

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

export class AlphaNumericValidator {
    static invalidAlphaNumeric(control: FormControl): { [key: string]: boolean } {
        if (control.value.length && !control.value.match(/^[a-z0-9]+$/i)) {
            return { invalidAlphaNumeric: true };
        }
        return null;
    }
}

I am applying this validator for a Model Driven Form,

'name': [this.exercise.name, [Validators.required, AlphaNumericValidator.invalidAlphaNumeric]],

And Here is the HTML,

<label *ngIf="exerciseForm.controls.name.hasError('invalidAlphaNumeric') && (exerciseForm.controls.name.touched || submitted)" class="alert alert-danger validation-message">Name must be alphanumeric</label>

I notice that whenever I am typing a character in input, the above TypeScript class code called, but every time it's return Null.

Is there any issue on typeScript class?

Thanks!

user584018
  • 8,077
  • 12
  • 50
  • 108

1 Answers1

0

use

!/^[a-z0-9]+$/i.test(control.value)

to get a boolean result

Günter Zöchbauer
  • 558,509
  • 191
  • 1,911
  • 1,506