Andrew Graham-Yooll
Andrew Graham-Yooll

Reputation: 2258

Custom Angular Validators- Passing an Argument

I have followed Josh Moroney's tutorial on creating a custom validator. I got it working, being able to call

newForm.ts

new FormControl(question || '', 
    Validators.compose([AgeValidator.ageIsValid])
);

AgeValidator.ts

interface ValidationResult {
  [key: string]: any;
}

export class AgeValidator {
  static ageIsValid(control: AbstractControl): ValidationResult {
    console.log('this is control', control);
    console.log('this is control.value', control.value);

    if (isNaN(control.value)) {
      return {
        notValid: true,
        message: 'this is not a number'
      };
    }
    if (control.value % 1 !== 0) {
      return {
        notValid: true,
        message: 'cant be zero'
      };
    }

    if (control.value < 18) {
      return {
        notValid: true,
        message: 'cant be less than 18'
      };
    }
    if (control.value > 120) {
      return {
        notValid: true,
        message: 'Must be less than 120'
      };
    } else {
      return null;
    }
  }
}

Is it possible to add an argument into .ageIsValid method, such that I can specify the age that is valid? For example,

new FormControl(question || '', 
    Validators.compose([AgeValidator.ageIsValid(18)])
);

What I have tried:

1) Getting rid of static and using .ageIsValid like any other method. Result: TS Error

2) Passing an argument like above. Result: Error

Anything else I can try?

Upvotes: 1

Views: 71

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657486

You can use a class with an instance method (instead of static)

class AgeValidator {
  constructor(private someParam) {}
  ageIsValid(control: AbstractControl): ValidationResult {
    // use someParam here
  }
}
var ageValidator = new AgeValidator('foo')
new FormControl(question || '', 
    Validators.compose([ageIsValid.ageIsValid.bind(ageValidator)])
);

or a function that returns a function

static ageIsValid (someParam) {
  return (control: AbstractControl): ValidationResult => {
    // use someParam here
  }
}
new FormControl(question || '', 
    Validators.compose([ageIsValid('foo')])
);

Upvotes: 1

Related Questions