Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add custom validation to template-driven form without creating new directive (max-characters)

I have a template-driven form. I need to add custom validator, which will detect max characters in input and show an error message and if we receive an error message, button 'ok' must be disabled. I have 5-7 inputs and in the code example, I provide just 2 to show syntax.

I tried max-characters = 10 but that attribute disallows typing more than 10. In my case, user can type whatever he wants characters (more than 10) but after he types 10th, it should be error message and button must be disabled.

Unfortunately, I'm new in template-driven forms and my task is to do it only in template-forms. Guys, please could someone explain to me the best way to make my form with inputs and custom validator works? Any help will helpful.

<form
    class="my_ex_form"
    #myExForm="ngForm"
    novalidate>
    <div class="input">
      <label class="required">One</label>
      <input
        ngxTrim='keyup'
        required
        #one="ngModel"
        name="one"
        maxlength="64"
        [(ngModel)]="ex.name"
        placeholder="Enter...">
      <span *ngIf="one.value?.length >= 10" class="error-text">Max length 10 characters.</span>
    </div>
   <div class="input">
      <label class="required">Two</label>
      <input
        ngxTrim='keyup'
        required
        #two="ngModel"
        name="two"
        maxlength="10"
        [(ngModel)]="ex.nameTest"
        placeholder="Enter...">
      <span *ngIf="two.value?.length >= 10" class="error-text">Max length 10 characters.</span>
    </div>
    <div>
     <button
        type="submit"
        [disabled]="someOtherInputsValue || someOtherCheckboxesValue"
        class="btn btn-short"
        (click)="validate(myExForm)">
        ok
      </button>
    </div>
</form>

like image 649
MargeKh Avatar asked Sep 18 '25 19:09

MargeKh


1 Answers

you can use a reference variable and use manually setError, see that in the example, my reference variable is "input1", and I make equal to a "ngModel", this allow us use input1.invalid, or input1.control.setErrors() some like

<input #input1="ngModel" [(ngModel)]="value" 
   (input)="input1.control.setErrors(input1.value.length>10?'max length':null)">
{{input1.invalid}}

If we want we can make a function

checkControl(control:NgModel)
  {
    if (control.control.value && control.control.value.length>10)
      control.control.setErrors({error:"Max length exceded"})
    else
    control.control.setErrors(null)
  }

And our form is like

<form #myform="ngForm">
<input #input1="ngModel" name="input1" [(ngModel)]="value1" 
   (input)="checkControl(input1)">
{{input1.invalid}}
<input #input2="ngModel" name="input2" [(ngModel)]="value2" 
   (input)="checkControl(input2)">
{{input2.invalid}}
</form>
{{myform.invalid}}

See stackblitz

like image 69
Eliseo Avatar answered Sep 22 '25 00:09

Eliseo