Home > database >  How can I get validator function parameter?
How can I get validator function parameter?

Time:10-27

this.form = this.formBuilder.group({
  value: ['', [Validators.required, Validators.minLength(4)]]
});

I want to get the 4 from Validators.minLength(4).

How can I get this?

CodePudding user response:

You can refer to this stackblitz URL for your above issue I've given a details answer. https://stackblitz.com/edit/angular-ivy-gjcu4t?file=src/app/app.component.html

TypeScript

export class AppComponent implements OnInit {
    name = 'Angular '   VERSION.major;

    formDummy: FormGroup = this.fb.group({
     val: [
     '',
     Validators.compose([Validators.required, Validators.minLength(4)]),
    ],
  });

  constructor(private fb: FormBuilder) {}
  ngOnInit(): void {
     this.formDummy.get('val').patchValue('12');
     console.log(this.formDummy.controls['val'].errors.minlength);
    
      console.log('ActualLength ',
      this.formDummy.controls['val'].errors.minlength.actualLength);
     
      console.log('requiredLength ',
      this.formDummy.controls['val'].errors.minlength.requiredLength
  );
 }
}

HTML Code for show errors

 <hello name="{{ name }}"></hello>
  <p>Start editing to see some magic happen :)</p>

<form [formGroup]="formDummy">
  <input type="text" formControlName="val" placeholder="Enter number here" />
  <br />

  Value => {{ formDummy.get('val')?.value }}
  <br />
  RequireLength {{ formDummy.get('val')?.errors.minlength.requiredLength }}
  <br />
  ActualLength {{ formDummy.get('val')?.errors.minlength.actualLength }}
</form>

CodePudding user response:

Disclamer: I'm not prety sure if this can help you

As you can get the "validator" and a validator is a function, you can "check" agains an "on-fly" formControl

const error=this.form.get('value').validator(
    new FormControl('1')
)
if (error && error.minlength)
   console.log(error.minlength.requiredLength)
  • Related