Skip to content

Instantly share code, notes, and snippets.

@masonkmeyer
Created March 27, 2016 15:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save masonkmeyer/73a4fe5e26c26d274846 to your computer and use it in GitHub Desktop.
Save masonkmeyer/73a4fe5e26c26d274846 to your computer and use it in GitHub Desktop.
Use a regular expression to validate Angular2 controls.
import { AbstractControl } from 'angular2/common';
export class RegexValidators {
static pattern(pattern: RegExp) : (c: AbstractControl) => {[key: string]: any } {
return (control: AbstractControl): { [key: string]: any } => {
let v: string = control.value;
return pattern.test(v) ? null : { "pattern": { "requiredPattern": `^${pattern}$`, "actualValue": v } };
};
}
}
@masonkmeyer
Copy link
Author

The current Validators.patterns takes a string and wraps it like this:

let regex = new RegExp(`^${pattern}$`);

This code just passes the expression straight through. Ideally, this should be union typed in Angular2 to accept either a RegExp or a string.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment