2
votes

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
_rawValidators is not a Angular thing, you should have used some code where validators are assigned to _rawValidators variable?Vega
What do you mean by _rawValidators is not a Angular thing, you should reference hereamansinghgusain

2 Answers

0
votes

From documentation

A FormControl constructor accepts three, optional arguments: the initial data value, an array of validators, and an array of async validators.

So you have you validator in an array. You can beforehand assign it to a variable and get it anywhere else. Like

this.validator1 = [ Validators.minLength(5), Validators.pattern('^[0-9]*$')]
...
console.log(this.validator1);
0
votes

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}