Reputation: 307
I have a form, with a minimum of characters and a maximum, the problem is that if the minimum is 2 characters and I put one I get the mat-error but when giving save it lets you save it with only one character.
<mat-form-field>
<input matInput #input1 maxlength="300" minlength="2"
placeholder="Nombre"
formControlName="name">
<mat-hint align="end">{{input1.value?.length || 0}}/300</mat-hint>
<mat-error>
Minimo 2 caracteres máximo 300
</mat-error>
</mat-form-field>
The save button:
<button class="mat-raised-button mat-primary" (click)="save()">Save</button>
The save function:
save() {
this.dialogRef.close(this.form.value);
}
https://stackblitz.com/edit/angular-jkjrsd-8flxvt
Upvotes: 0
Views: 152
Reputation: 333
Validation should be in form control. You have to remove from HTML maxlength="300" minlength="2"
and set form validation in form group like:
.ts
formGroup = new FormGroup({
name: new FormControl('', [Validators.maxLength(300), Validators.minLength(2), Validators.required])
});
.html
<form (ngSubmit)="onSubmit()" [formGroup]="formGroup">
<mat-form-field>
<input matInput #input1 placeholder="Nombre" formControlName="name">
<mat-hint align="end">{{input1.value?.length || 0}}/300</mat-hint>
<mat-error>
Minimo 2 caracteres máximo 300
</mat-error>
</mat-form-field>
<button type="submit" [disabled]="!formGroup.valid">Save</button>
</form>
Upvotes: 0
Reputation: 857
use Form submit
<form [formGroup]="form" (ngSubmit)="save()" class="example-form">
<mat-form-field>
<input matInput #input1 maxlength="300" minlength="2"
placeholder="Nombre"
formControlName="name">
<mat-hint align="end">{{input1.value?.length || 0}}/300</mat-hint>
<mat-error>
Minimo 2 caracteres máximo 300
</mat-error>
</mat-form-field>
<button type="submit"> save</button>
In component.ts
save(){
if(this.form.valid){
console.log('saved')
}
else{
console.log('invalid form')
}
}
example stackblitz
Upvotes: 1