Angular: setErrors not displaying message
11,260
It looks like your error message text is commented out:
<!--Phone Number does not exist.-->
Try this:
<span class="help-block" *ngIf="(ersaForm.get('phone').touched || ersaForm.get('phone').dirty ) && ersaForm.get('phone').invalid">
<span *ngIf="ersaForm.get('phone').hasError('customVal')">
Phone Number does not exist
</span>
</span>
Related videos on Youtube
Author by
rgoal
Updated on June 04, 2022Comments
-
rgoal almost 2 years
I am trying to display set te error message inside my custom control with lo luck..the message is always empty! what am I missing? onSelectedCC(event: any)//this called to turn on/off phone validator
HTML
<div class="form-group col-xs-3 col-md-3" [ngClass]="{ 'has-error':(ersaForm.get('phone').touched || ersaForm.get('phone').dirty ) && !ersaForm.get('phone').valid }"> <label for="phoneLabel" class="control-label">Phone</label> <input type="tel" formControlName="phone" pattern="^[0-9-+s()]*$" class="form-control" id="phoneLabel" placeholder="Phone"> <span class="help-block" *ngIf="(ersaForm.get('phone').touched || ersaForm.get('phone').dirty ) && ersaForm.get('phone').errors"> <span *ngIf="ersaForm.get('phone').errors.customVal"> <!--Phone Number does not exist.--> </span> </span>
TS(custome control is working but message is empty)
return (c: AbstractControl): { [key: string]: boolean } | null => { let dataForm = c.parent; c.setErrors(null); var phoneVal = ""; if (c.value.length != 10) { c.setErrors({ 'incorrect phone format': true }); return { 'customVal': true }; } if (c.value != undefined && val == -1 && val != '') { c.setErrors({ 'Phone Number does not exist.': true }); return { 'customVal': true }; }; return null; }; } this.ersaForm = this._fb.group({ phone: '', }); onSelectedCC(event: any)//this called to turn on/off phone validator { const phoneControl = this.ersaForm.get('phone'); let cc = event.value.name; if (cc == '1111' ) { phoneControl.setValidators([Validators.required, phoneCheck(this.customVal)]); } else { phoneControl.clearValidators(); } phoneControl.updateValueAndValidity(); }
-
rgoal about 5 yearssame issue...message is not displayed .. I commented the message because i needed to be set from the custom validation ..also had to take out a single quote to get it compiling *ngIf="ersaForm.get('phone').hasError(customVal)"
-
rgoal about 5 yearsI get this error" Cannot read property 'setErrors' of null"..keep in mind c.value does return the correct value for the phone control..