so I'm trying to display different validation messages depending on the validator on my form control.
Here's what I have set up so far:
this.Form = fb.group ({
'FooNumber': [null, Validators.compose([Validators.required, Validators.pattern('^[a-zA-Z0-9\\-_]*$')])]
});
In my html:
<input formControlName="FooNumber" (blur)="NoSpecialCharacters && !this.Form.get('FooNumber').valid" [ngClass]="!this.Form.get('FooNumber').valid ? 'inputRed': 'input'"/>
<div class="error-msg" *ngIf="!this.Form.get('FooNumber').valid" name="errorMsg"> This is a required field </div>
<div class="error-msg" *ngIf="NoSpecialCharacters && !this.Form.get('FooNumber').valid" name="errorMsg">Enter a valid number </div>
My question is, I want to show the message with ngIf "NoSpecialCharacters" for the Regex in the Validators.pattern() above but if the field was felt empty and user clicked on submit, it should show the other message , "Required field" message.
I was wondering, what's the best approach to having different error messages display depending on which validator goes off.
Do I need to create a custom validator to handle this scenario?
FormControl.valid
, inspectFormControl.errors
. Different validators will add different errors to that object, and you can base your condition on that to display different error messages. – Harry Ninh