Angular 2 (Reactive forms) Listing all validation rules (like pattern, minlength, maxlength) in a form control whether or not in an error object

Viewed 2906

I am creating a component where I need to list all the validation rules of an input.

home.component.html

<input-validation>
   <input type="text" class="form-control" formControlName="name">
</input-validation>

home.component.ts

export class HomeComponent implements OnInit {
    public myForm: FormGroup;

    constructor(private _fb: FormBuilder) { }

    ngOnInit() {
        this.myForm = this._fb.group({
            name: ['', [ <any>Validators.minLength(5), <any>Validators.pattern('^[0-9]*$')]],
            address: this._fb.group({
                street: ['', <any>Validators.required],
                postcode: ['8000']
            })
        });

    }
}

For template driven forms I am using

_rawValidators

property of FormControlName.

But I noticed that _rawValidators does always returns empty array for Reactive forms.

As you can see in above example formControlName="name" has two validators here minlength and pattern. Now unless you starts writing in this input, the errors object of FormControl is null.

So if anyone could help me to understand how ReactiveForms works(validates) or where it stores all its validators would be much appreciable.

Thanks

2 Answers

Not sure if this is what you're looking for, but the validator property on AbstractControl returns a single function which is composed of all validation logic. If you call that function and pass in the control you want to validate, it will apply all validation and return an object containing information about each validator that failed, or null if no validators failed.
For example, on an input with a minlength="3" validator, the following is the return value when you only enter 2 characters:

{"minlength":{
    "requiredLength":3,
    "actualLength":2
  }
}

Whereas it returns the following when a required validator fails:

{"required": true}
Related