1

How can I implement my custom Validator in Angular 2?

I found this plunker:

constructor(private fb: FormBuilder) {
    this.form = fb.group({
        'singleSelection': ['Rio', [App.validateCity]] // initial value as string
        'multipleSelection': [['Red','Blue'], [App.validateColor]]  // initial value as array
    });
}

static validateCity(c: FormControl) {
    if (c.value !== 'New York') {
        return { citySucks: true };
    }
    return null;
}

static validateColor(c: FormControl) {
    if (c.value.indexOf('Green') < 0) {
        return {badColor: true};
    }
    return null;
}

But, I think it would be better to implement an interface Validator, like class MinLengthValidator. But, I don't know how to use it!

1 Answer 1

1

// Control handling

          this.form = fb.group({
            'singleSelection': ['Rio', this.text({min: 10})]
          });

// Text function to handle min value

           public static text(config = {}): ValidatorFn {
             return (control: Control): {} => {
                if(!control) {
                   return null;
                }

              let c: string = control.value;

            if(config.min) {
              if(c.length < config.min) {
                  return {
                  "This field must have at least " + config.min + " characters."
                  };
               }
             }
           }}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.