3

I have implemented a custom validation in my reactive form, basically, it will show an error when the length of the field reaches a certain limit.

this.formGroup = new FormBuilder().group({
     comment: [null, {
        validators: [ValidateCommentLength],
        updateOn: 'change'
      }]
  })

HTML

<textarea
            autocomplete="off"
            maxlength="3600"
            nxInput
            (ngModelChange)="valueChange($event)"
            type="text"
            [formControlName]="'comment'"
          ></textarea>
          <nx-error nxFormfieldError *ngIf="formGroup.get('comment').invalid" appearance="text">
            Maximum comment length is exceeded 
          </nx-error>
        </nx-formfield>

But the validation is not triggering on the first time of input change on the later changes it will work

UPDATE Validator

import { AbstractControl } from '@angular/forms';

const MAX_LENGTH =  2;

    export function ValidateCommentLength(control: AbstractControl) {
    
        if (control.value) {
            if (!control.value.replace(/\s/g, '').length) {
                return null;
            }
            const  remaining = MAX_LENGTH - control.value.length;
            if (!remaining || Math.sign(remaining) === -1) {
                return { CommentError: true };
           }
    
        }
        return null;
    }
9
  • Please add code for ValidateCommentLength Commented Apr 8, 2021 at 6:06
  • I reproduce your scenario, what's wrong? Commented Apr 8, 2021 at 6:06
  • @OwenKelvin added validator Commented Apr 8, 2021 at 6:17
  • @MehdiShakeri that's not correct I have custom form validator, Please check the updated question Commented Apr 8, 2021 at 6:20
  • @iambatman which library is nx-error from? Commented Apr 8, 2021 at 6:24

1 Answer 1

3

The problem

The problem is that nx-error will only show if the input is touched. But input is only touched when we blur out of the form

Solution

After the validator invalidates the input, trigger touched manually

export function ValidateCommentLength(control: AbstractControl) {
  if (control.value) {
    if (!control.value.replace(/\s/g, "").length) {
      return null;
    }
    const remaining = MAX_LENGTH - control.value.length;
    if (!remaining || Math.sign(remaining) === -1) {
      control.markAsTouched()
      return { CommentError: true };
    }
  }
  return null;
}

In the above I have just added control.markAsTouched() and now validation works as you expect

See Demo Here

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.