Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: setErrors not displaying message

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();
}
like image 513
rgoal Avatar asked Oct 20 '25 05:10

rgoal


1 Answers

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>
like image 187
Tom Faltesek Avatar answered Oct 23 '25 00:10

Tom Faltesek