1

Been thinking of implementing an asychronous custom validator for a form with the sole purpose of communicating with a microservice to extract information out of a person's ID number (like age, date of birth, gender, race, etc) and of course whether the ID number is valid or not based on the country they send through.

So if a person enters their ID number and selects a country, a request is fired off to a microservice, and if they haven't set their gender for instance, it automatically populates it, to which they can change it afterwards if need be.

Questions

  1. Is it good/OK practice to set other form control values in a validator according to the following scenario?
  2. If so, how would I go about modifying the other form control values?

Any help would be appreciated :)

1
  • 1
    A validator should never set any values of a form, it should only validate. Commented Jul 18, 2017 at 6:46

1 Answer 1

1

Like I said in the comment, a validator should never set or update a value of a form control, group or array. It should only validate.

What you can do however is use the .valueChanges to listen to changes to the form, and in the callback check if a certain control is valid or not, updating some other control accordingly.

Here's an example:

this.form.get('someControl').valueChanges(() => {

  if (this.form.get('someControl').valid) {
    this.form.get('someOtherControl').setValue(true);
  }
});
Sign up to request clarification or add additional context in comments.

4 Comments

Out of curiosity, is it documented somewhere that it's frowned upon to add logic like this in a validator, since it's a pretty unusual scenario? It does make sense that you seperate the logic completely though, will probably end up marking your answer as correct
Not that I'm aware of, but the name itself makes it pretty clear. And I think it's mentioned somewhere in the official style guide that you should create "pure" functions, meaning that they don't have any side effects. A validator function that modifies some other control would break that pattern, therefore it should only validate and then you would do the other thing somewhere else.
Yea makes sense, thanks for the prompt feedback mate :)
Glad to help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.