Zain Khan
Zain Khan

Reputation: 1814

Reactive Forms MinLength Validation Is Not Showing Error

I' using ReactiveForms in my Angular App. I want if user put less than 7 numbers so error message should be show there but unfortunately it's not working if there is any mistake or solution so please provide me. Thanks

Service.ts

PhoneNo: ['', [Validators.required, Validators.minLength(7)]],

html

<input class="full-width has-padding has-border" formControlName="PhoneNo" type="tel" placeholder="Mobile *" />
        <img src="../../../../assets/img/required-img.png" class="required-img"
          *ngIf="service.formModel.get('PhoneNo').touched && service.formModel.get('PhoneNo').errors?.required"
          title="This fields is mandatory" data-toggle="tooltip" />
          <label *ngIf="service.formModel.get('PhoneNo').touched && service.formModel.get('PhoneNo').errors?.minLength">Minimum 7 characters required</label>

Upvotes: 4

Views: 12599

Answers (5)

me-and-viy
me-and-viy

Reputation: 109

the reason why it's not working - you should write maxlength in lowercase, not camelcase. same goes to minlength

Upvotes: 0

pete85
pete85

Reputation: 151

This is well misleading from Angular side. Inside the component you set validators in the following way:

[Validators.minLength(2)]

Then, you would expect the following to work:

errors?.minLength

for whatever reason they decided to use the following format for error messages inside templates though:

errors?.minlength

The only thing you have to do is replace L with l

Upvotes: 15

vijay kumar
vijay kumar

Reputation: 71

Minimum 9 characters required

user error key as minlength not minLength

Upvotes: 6

John
John

Reputation: 11399

You have maxLength as an attribute in your html. You should remove it

Instead of

<input class="full-width has-padding has-border" formControlName="PhoneNo" type="tel" placeholder="Mobile *" maxlength="7" />

Do this

<input class="full-width has-padding has-border" formControlName="PhoneNo" type="tel" placeholder="Mobile *">

Also, <input> and <img> should not have an enclosing tag at the end <img/> should be <img>

Instead of using minLength and maxLength together, you can create a regexp for it instead

PhoneNo: ['', [Validators.required, Validators.pattern(^[\s\S]{7}$)]],

Also remember to use service.formModel.get('PhoneNo').errors?.pattern instead of .errors?.minLength in order to display the label.

EDIT @malbarmawi was kind enough to make a demo here: https://stackblitz.com/edit/angular-forms-pattern-bernj2. He also has another approach to solve the same problem himself.

Upvotes: 3

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24424

add maxLength validators , this will restrict the enter characters to 7 characters 👇

PhoneNo: ['', [Validators.required, Validators.maxLength(7) , Validators.minLength(7)]],

demo 🔥🔥

Upvotes: 2

Related Questions