0

My requirement is to display maxlength error message for input field if it exceeds the maxlength.

This is working for input type number. Error message is displaying if the input field exceeds maxlength.

This is not working for input type text field. Error message is not displaying instead of that it is restricting the user to enter the values more that the given maxlength.

Can anyone suggest me the solution for this issue.

Thank You, Java4you.

2
  • 1
    Please add some code to your question. Commented Feb 20, 2018 at 11:11
  • I think there is string length some what but not sure Commented Feb 20, 2018 at 11:11

1 Answer 1

2

I would recommand to use ReactiveForms and set the validator for max-length.

In your module:

import { ReactiveFormsModule } from '@angular/forms'
...
@NgModule({
   imports: [
       ...
       ReactiveFormsModule
   ]
   .....
})

Then go over to your component and inject formbuilder

import { FormBuilder } from '@angular/forms';
...
export class MyFormComponent {
   public fb: FormGroup;
   public constructor(private formBuilder: FormBuilder) {
       this.fb = this.formBuilder.group({
           myControlWithMaxLength: ['', Validators.maxLength(128)]
       });
   }
}

Now in your template do the following

<form [formGroup]="fb" novalidate>
   <input type="text" formControlName="myControlWithMaxLength" />
   <span *ngIf="fb.controls['myControlWithMaxLength'].hasError('maxLength')">Max length is 128!</span>
</form>

To keep the template cleaner you can write getters in your component instead.

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

2 Comments

I am not using form to validate my input field. My input field is separate not in form submittion
Then I advice you to change the current implementation to either use reactive-forms or model-driven-forms. Is not a good approach to manually validate content when there is a system built to do it for you.

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.