0

I have form with input field with default value. I want to add validation for that field to have exactly 5 characters.

<td>
    <input type="text" maxlength="5" ngModel 
    #number="ngModel" name="number" value="{{data.number}}" class="form-control">
</td>

The problem is that I cannot get that default value in order to validate as the value of input shows mi empty string "". If I change that value the proper value is visible. Is there a way to use validator in this case ?

SOLUTION:

    <td>
    <input type="text" maxlength="5" [(ngModel)]="data.number" 
    #number name="number" class="form-control">
</td>
3
  • minlength = 5 Commented Jul 5, 2018 at 7:58
  • But on start (when I have default value) my value from input is equals "". So I will have error Commented Jul 5, 2018 at 8:00
  • If I add required it will allow to insert no value. Commented Jul 5, 2018 at 8:12

1 Answer 1

1

You can make use of ReactiveForms module and simply add the desired validators. In your case something like this would work:

this.myForm = this.formBuilder.group({
      myInput: new FormControl('defaultValue',[Validators.minLength(5),Validators.maxLength(5)])
})

Template:

<form name="myForm" [formGroup]="myForm">
    <label>
    <div>My input</div>
    <input type="text" formControlName="myInput" [ngClass]="{'error': myForm.invalid}">
  </label>
</form>

Here's a working example.

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.