[Fixed] No white space validator for Optional filed

Issue

Am using angular 10
below is my code for no space validator for Required field

static noWhitespace(control: AbstractControl) {
    let isWhitespace = (control.value || '').trim().length === 0;
    let isValid = !isWhitespace;
    return isValid ? null : { 'whitespace': true }
}

I have Modified code for optional But no luck ..

const isWhitespace = control.value.length > 0 && (control.value).trim().length === 0; 
const isValid = !isWhitespace; 
return isValid ? null : { 'whitespace': true };

This code works for Required field But not work for optional . Is it possible to do ? Thanks in advance

EDIT:

Am grtting below error

enter image description here

EDIT :

 <div class="form-group row">
                                            <label class="col-md-3 col-form-label" for="af-ain">AIN<span class="required-asterisk">*</span></label>
                                            <div class="col-md-9">
                                                <input type="text" id="af-ain" name="af-ain" class="form-control"
                                                    formControlName="ain" placeholder="AccountNumber/ID" autocomplete="ain">
                                                <ar-validation-message [control]="accountForm.controls.ain">
                                                </ar-validation-message>
                                            </div>
                                        </div>

Solution

You problem isn’t with this validator. The problem is in your html checking the control valid property while its control is undefined.
Look for line 9 in your aacount-edit.component.html file (you can see that in the error message) and add ? char right before the .valid.

e.g.

<p *ngIf="control?.valid">Hello world</p>

Leave a Reply

(*) Required, Your email will not be published