0

In a component with an input, I pass an array of such objects for validation:

export class ValidatorItem { validator: ValidatorFn; errorText: string; } 

in component:

 ngOnChanges(changes: SimpleChanges): void { if ('validators' in changes) { this.formModel = this.formBuilder.group({ value: ['', Validators.compose(this.validators.map(v => v.validator))], }); } } 

that is, I need to get an errorText message depending on which validator fell. How can i do this?

2
  • 1
    Please go through this link. Validations Commented Dec 28, 2022 at 7:32
  • 2
    A validator is a function that return null (if all is Ok) or, generally, an object if there're an error. you simply ask about one property of this object. e.g. Validators.email return an object {email:'error'}, Validators.required return an object {required:true}and so on. so you ask about control.errors?.email or about control.errors?.required. Commented Dec 28, 2022 at 10:34

1 Answer 1

0

I've had the same question and stumbled upon this thread, so might as well answer here, if anyone else finds this.

My loginForm object like this:

this.loginForm = this.formBuilder.group({ username: ['', [Validators.required, Validators.minLength(3)]], password: ['', Validators.required] }); 

If a user submits my login form, the login() function is fired. It checks the state of this.loginForm.invalid, if the form is invalid we check for errors.

The function here checks and shows the error directly, but you could also refactor it into a function.

async login() { if (this.loginForm.invalid) { const controls = this.loginForm.controls; if (Object.values(controls).some(control => control.hasError('required'))) { this.showNoticeFn("Please fill in all fields."); return; } if (controls['username'].hasError('minlength')) { this.showNoticeFn("Username is too short!"); return; } return; } // Login logic } 

We could also trigger this logic every time changes happen via ngOnChanges

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.