Reputation: 880
I'm trying to implement angular validators inside my form following tutorials, but the validation is ignored. Here is my code:
view
<div class="form-group row">
<label for="inputLocalita" class="col-sm-2 col-form-label col-form-label-sm">Località</label>
<label *ngIf="!edit" class="col-sm-10 col-form-label col-form-label-sm grey" id="inputLocalita">{{immobile.localita}}</label>
<div *ngIf="edit" class="col-sm-10">
<input type="text" class="form-control form-control-sm" id="inputLocalita" formControlName="localita" placeholder="Località">
</div>
<div *ngIf="imm.controls.localita.errors && (imm.controls.localita.dirty || imm.controls.localita.touched)">
<p *ngIf="imm.controls.localita.errors.required">Field is required</p>
<p *ngIf="imm.controls.localita.errors.minlength">Field must be 8 characters long</p>
</div>
</div>
controller
ngOnInit() {
this.imm = new FormGroup({
comune: new FormControl(),
provincia: new FormControl(),
comuneObj: new FormControl(),
cap: new FormControl(),
indirizzo: new FormControl(),
civico: new FormControl(),
localita: new FormControl([
Validators.minLength(4),
Validators.required]),
destinazioneUso: new FormControl(),
destinazioneUsoAltro: new FormControl(),
destinazioneUsoPrincipale: new FormControl(),
destinazioneUsoSecondaria: new FormControl(),
});
Am I missing something? Thanks for the hints.
Upvotes: 1
Views: 13440
Reputation: 38161
You are messing usage of formControl
. While creating a custom FormControl
, use the below syntax(see API of FormControl):
// for single validator
customControl = new FormControl('value', Validators.maxLength(5));
// for multiple validators(with Validators.compose)
customControl = new FormControl('value', Validators.compose([Validators.minLength(4), Validators.required]));
// or(without Validators.compose)
customControl = new FormControl('value', Validators.compose([Validators.minLength(4), Validators.required]));
Changing your formGroup code to either of the below way will solve your problem:
Option1: Creating a formGroup without using new FormControl()
this.imm = new FormGroup({
comune: [],
provincia: [],
comuneObj: [],
cap: [],
indirizzo: [],
civico: [],
localita: ['', Validators.compose([Validators.minLength(4), Validators.required])],
destinazioneUso: [],
destinazioneUsoAltro: [],
destinazioneUsoPrincipale: [],
destinazioneUsoSecondaria: [],
});
Option2: Correct the formControl part syntax.
this.imm = new FormGroup({
comune: new FormControl(),
provincia: new FormControl(),
comuneObj: new FormControl(),
cap: new FormControl(),
indirizzo: new FormControl(),
civico: new FormControl(),
localita: new FormControl('', Validators.compose([Validators.minLength(4), Validators.required])),
destinazioneUso: new FormControl(),
destinazioneUsoAltro: new FormControl(),
destinazioneUsoPrincipale: new FormControl(),
destinazioneUsoSecondaria: new FormControl(),
});
Upvotes: 1