Exceed maximum character message not display if user enter more than 5 characters

Discussão em 'Angular' iniciado por justin, Agosto 31, 2025.

  1. justin

    justin Guest

    I am trying to check user's input of subject is an empty or exceed max character. If user not which should display: Required Information message. If user enter over 5 character and it should display Exceed Maximum Character. I do not know why no exceed max character message display if user enter more than 5 characters right away on the code.

    Here is HTML file

    <form class="add-form"
    [formGroup]="addForm"
    novalidate>
    <div class="add-form__group">
    <label for="subject"
    class="add-form__label">
    Subject
    </label>
    <input class="add--form__input"
    [class.add-form__input--error]="(hasError('subject') || hasError('subject', 'maxlength'))"
    formControlName="subject"
    id="subject"
    name="subject"
    type="text"
    placeholder="Enter a Subject Line"/>

    <ng-container *ngIf="(hasError('subject') || hasError('subject', 'maxlength'))">
    <p class="add-form__error-label"
    *ngIf="addForm.get('subject').errors.required">
    Required Information
    </p>
    <p class="add-form__error-label"
    *ngIf="addForm.get('subject').errors.maxlength">
    Exceeds Maximum Character
    </p>
    </ng-container>
    </div>
    </form>


    TS file

    export class AddFormComponent implements OnInit {
    constructor(private fb: FormBuilder) {
    /** On Init */
    public ngOnInit(): void {
    this.initAddForm();
    }

    public addForm: FormGroup;
    /** Checks If Controller has Error */
    public hasError(controlName: string, error: string = 'required'): boolean {
    const controller: FormControl = this.addForm.get(controlName) as FormControl;
    return controller.hasError(error) && controller.touched;
    }

    private initAddForm(): void {
    this.addForm = this.fb.group({
    subject: ['', [Validators.required, Validators.maxLength(5)]],
    });
    }
    }

    Continue reading...

Compartilhe esta Página