I created a simple form in angular. I used two validations. The required validation works fine, but the minLength is not working.
Here is the html code:
<form [formGroup]="preferenceForm" (ngSubmit)="onSubmit()">
<div class="mb-3">
<label for="overs" class="form-label">Number of overs</label>
<input type="number" formControlName="overs" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.overs.errors }"
id="overs" placeholder="Overs..">
<div *ngIf="submitted && f.overs.errors" class="invalid-feedback">
<div *ngIf="f.overs.errors.required">First Name is required</div>
<div *ngIf="f.overs.errors.minlength">Choose at least 3 overs</div>
</div>
</div>
<div class="mb-3">
<label for="players" class="form-label">Number of players per team</label>
<input type="number" formControlName="players" class="form-control"
[ngClass]="{ 'is-invalid': submitted && f.players.errors }" id="overs" placeholder="Players..">
<div *ngIf="submitted && f.players.errors" class="invalid-feedback">
<div *ngIf="f.players.errors.required">First Name is required</div>
<div *ngIf="f.players.errors.minlength">Choose at least 3 players</div>
</div>
</div>
<div class="mb-3">
<div class="form-check">
<input class="form-check-input" formControlName="lastMan" type="checkbox" value="" id="last-man"/>
<label class="form-check-label" for="last-man"> Last Man Standing</label>
</div>
</div>
<div class="text-center b-3">
<button type="submit" class="btn btn-light">Let's Start</button>
</div>
</form>
and here is my component code:
export class NewMatchComponent implements OnInit {
public preferenceForm: FormGroup;
public submitted = false;
constructor(private formBuilder: FormBuilder, private appService:
AppService) {
}
ngOnInit(): void {
this.preferenceForm = this.formBuilder.group({
overs: [8, [Validators.required, Validators.minLength(3)]],
players: [8, [Validators.required, Validators.minLength(3)]],
lastMan: [true]
});
}
// tslint:disable-next-line:typedef
get f() {
return this.preferenceForm.controls;
}
onSubmit(): void {
console.log(this.preferenceForm.value);
this.submitted = true;
if (this.preferenceForm.invalid) {
return;
}
// const formData = this.preferenceForm.value;
// this.appService.createNewMatch(formData.overs,
formData.players, formData.lastMan);
}
}
I used the validators correctly, I also used minlength in form, still not working.