Reputation: 836
I am new in Angular. I am trying to learn it by doing. I tried reactive form validation as follows. It doesn't work. I can't see what is wrong:-
TS:-
export class LoanTypesComponent implements OnInit {
addLoanTypesForm!: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit(): void {
this.addLoanTypesForm = this.fb.group({
'loanName' : new FormControl('', [Validators.required,
Validators.maxLength(10), Validators.minLength(4)]),
'loanType' : new FormControl('', Validators.required),
'terms' : new FormControl(),
'loanDescription' : new FormControl()
});
}
}
HTML:-
<form [formGroup]="addLoanTypesForm">
<div class="form-group">
<input type="text" formControlName="loanName"> <br/>
<div class="text-danger" *ngIf="addLoanTypesForm.get('loanType')?.hasError('minlength') && addLoanTypesForm.get('loanType')?.touched ">This field minLength is 4 </div>
<div class="text-danger" *ngIf="addLoanTypesForm.get('loanType')?.hasError('maxlength') && addLoanTypesForm.get('loanType')?.touched ">This field max length is 10 </div>
<div class="text-danger" *ngIf="addLoanTypesForm.get('loanType')?.hasError('required') && addLoanTypesForm.get('loanType')?.touched ">This field is required </div>
</div>
<input type="text" formControlName="loanType"> <br/>
<div *ngIf="addLoanTypesForm.get('loanType')?.hasError('required') && addLoanTypesForm.get('loanType')?.touched ">This field is required </div>
<input type="checkbox" formControlName="terms"> Accept Terms! <br/>
<textarea fromControlName="loanDescription"></textarea><br/>
<button [disabled]="!addLoanTypesForm.valid" (click)="addLoanType()">Add Loan</button>
I always only one error This field is required. For min and max length validation never shows. As my submit button is disabled until the from is valid, I can see the button remain disable until I fill the condition. But the validation message never shows. What is wrong in my code?
Upvotes: 0
Views: 586
Reputation: 322
As previous commenter wrote: "you mixed it up loanType with loanName, when you create validation messages in UI"
Solution is:
<div class="text-danger" *ngIf="addLoanTypesForm.get('loanName')?.hasError('minlength') && addLoanTypesForm.get('loanName')?.touched ">This field minLength is 4 </div>
<div class="text-danger" *ngIf="addLoanTypesForm.get('loanName')?.hasError('maxlength') && addLoanTypesForm.get('loanName')?.touched ">This field max length is 10 </div>
<div class="text-danger" *ngIf="addLoanTypesForm.get('loanName')?.hasError('required') && addLoanTypesForm.get('loanName')?.touched ">This field is required </div>
If you wouldn't like to handled error messages manually i have a great package for it: https://www.npmjs.com/package/ngx-form-validations
Try it, i hope like it.
Upvotes: 0
Reputation: 3538
Because loanType
has only required
validations. loanName
has a min
and max
validation. It will work fine if addLoanTypesForm.get('loanName')
is checked instead of addLoanTypesForm.get('loanType')
.
Upvotes: 1