2

How to Set Custom Validation Angular as i am getting undefined of controls

FormControl.setValidators(this.validateCall);

    validateCall(): ValidatorFn {
        return (control: FormControl): ValidationErrors | null => { // not getting control value here
            const val = control.value;
            if(val == null || val == undefined) {
                return {
                    atLeastOneRequired: {
                        valid: false
                    }
                }
            }
            return null;
        }
9
  • 1
    who is upvoting this? I mean the question is incomplete in terms of explanation! Commented Sep 18, 2019 at 7:33
  • where is index btw? Commented Sep 18, 2019 at 7:35
  • Please post the complete/relevant code to reproduce an issue Commented Sep 18, 2019 at 7:36
  • i have done changes please look Commented Sep 18, 2019 at 7:38
  • If possible then create a stackblitz (which is possible in this case), will help Commented Sep 18, 2019 at 7:39

2 Answers 2

2

Your custom validator seems incorrect. You should remove

 return (control: FormControl): ValidationErrors | null => { 

Also no need for the nested object in the error. So modify your validator to:

validateCall(ctrl: AbstractControl): ValidationErrors | null {
  const val = ctrl.value;
  if (!val || val === '') {
    return {
      atLeastOneRequired: true
    }
  }
  return null;
}

The way you are setting the validator to the formcontrol is correct, since according to your comment i did it here for common understanding actually I am using this on formControl not on the class. In some cases you might also need to manually call updateValueAndValidity on the form control after setting the custom validator.

STACKBLITZ

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

Comments

0

Reactive forms validation. form-validation

this.heroForm = new FormGroup({
'name': new FormControl(this.hero.name, [
  Validators.required,
  Validators.minLength(4),
  forbiddenNameValidator(/bob/i) // <-- Here's how you pass in the custom validator.
]),
'alterEgo': new FormControl(this.hero.alterEgo),
'power': new FormControl(this.hero.power, Validators.required)
});

2 Comments

But i want to set forbiddenNameValidator when certain condition pass not at the starting.
I have made a stackBlitz example: Reactive forms custom validation . Try to typing bobby first and last name

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.