cucuru
cucuru

Reputation: 3698

it works, it was a mistake somewhere else. Create a custom validator

I'm customizing my form and creating my own validator. But I'm doing wrong, because it always crashes:

**my-component.ts**
export function ageRangeValidator(min: number, max: number): ValidatorFn {
  return (control: AbstractControl): { [key: string]: boolean } | null => {
     if (control.value !== undefined && (isNaN(control.value) || control.value < min || control.value > max)) {
      return { 'ageRange': true };
     }
   return null;
 };
}

@Component({
  selector: 'my-component',
  templateUrl: './my-component.html',
  styleUrls: ['./my-component.scss'] 
})

export class MyComponent implements OnInit {

  form: FormGroup;

  constructor(private fb: FormBuilder) {
  }

  ngOnInit() {
    this.form = this.fb.group({
       name: ['', [Validators.required],
       age: ['', [Validators.required, ageRangeValidator(20, 30)]]

  }
}

When create the form, I it crashes

Error: formGroup expects a FormGroup instance. Please pass one in.

   Example:


<div [formGroup]="myGroup">
  <input formControlName="firstName">
</div>

In your class:

this.myGroup = new FormGroup({
   fistName: new FormControl()
});

if I remove the validator in the form definition, it works.

What are I'm doing wrong?

Upvotes: 0

Views: 63

Answers (2)

MoxxiManagarm
MoxxiManagarm

Reputation: 9124

Your age is a string, in your validator you are comparing numbers. Please make sure to use the correct type. Why are you not using number input fields and max+min validators?

Upvotes: 0

Abdul Aleem
Abdul Aleem

Reputation: 361

// in your form 
age   : ['', [Validators.required, this.ageRangeValidator, Validators.maxLength(100)]],
// function in same class
  public ageRangeValidator(control: FormControl) { 
    const isValid = control.value > 30  && control.value < 30;
    return isValid ? null : { ageRange: true };
  }

Upvotes: 1

Related Questions