1

I am deriving a custom validation method for validating ranges as shown below:

static ratingRange=(min:number,max:number) =>
  {
     return (control:AbstractControl):Promise<ValidationErrors|null>=>
     {
          return new Promise(resolve=>
           {
             if (control.value !== undefined && (isNaN(control.value) 
            || control.value < min || control.value > max))
                              return resolve({InvalidRange:true});
             else return resolve(null);    
           }
          );
      }

it is executing the validation as expected without any issue.

However for testing purpose i wanted to rewrite the validation method using ValidatorFn factory as shown below.(Intention was not to return a promise object)

static CustomRangeValidator (min:number,max:number): ValidatorFn
  {
     return (control:AbstractControl):{[key:string]:boolean}=>
     {
        if (control.value !== undefined && (isNaN(control.value) 
           || control.value < min || control.value > max))
                       return {InvalidRange:true}
        else return null;   
     }
  }

But i am getting

'Expected validator to return Promise or Observable.'

Is there a way to refactor my function call without returning a Promise object?

1 Answers1

1

my solution

this.myForm = new FormGroup({
    'controlName': new FormControl(value, 
               [/* this array for validation functions which will not return promises */], 
               [/*this array for function which returns promises*/])
})

/// in your case but your function in the first array 
Khaled Ahmed
  • 1,044
  • 8
  • 20
  • Do you mean default Validators like Valaidators.required,etc does not require Promise and Custom Validator require Promise object? – user9184448 Jan 12 '18 at 14:26
  • no i meant you can customize your validators and you can specify if require promise or not and if it requires promise put it in the second array, and the first one otherwise – Khaled Ahmed Jan 12 '18 at 18:01
  • The difference is aync validation vs sync validation: https://stackoverflow.com/questions/41434362/angular-2-3-1-async-custom-validator-promise-doesnt-resolve – Faraji Anderson Jan 12 '18 at 18:23