#Validating form using Angular v17

15 messages · Page 1 of 1 (latest)

teal hawk
#

html
<form (ngSubmit)="saveSalaire()"> <div> <label for="numEmp">Numéro d'employé:</label> <input type="text" id="numEmp" formControlName="numEmp" [value]="salaireRetraite.numEmp" /> </div> <button type="submit">Créer salaire</button> </form>

`export class SalaireRetraiteComponent implements OnInit {
salaireForm: FormGroup | undefined;
salaires: SalaireRetraite[] = [];
salaireRetraite: SalaireRetraite = {
id: 0,
numEmp: '',
numAssSoc: '',
salaireDeclare: '',
salairePlafonne: '',
salaireDifferentiel: ''
}
salaireRetraiteForm: FormGroup = this.fb.group({});

constructor(private fb: FormBuilder, private salaireRetraiteService: SalaireRetraiteService) {}

ngOnInit(): void {
this.salaireForm = this.fb.group({
numEmp: ['', [Validators.required, this.onlyNumbersValidator(), Validators.maxLength(10)]],
numAssSoc: ['', [Validators.required, this.onlyNumbersValidator(), Validators.maxLength(10)]],
salaireDeclare: ['', [Validators.required, this.onlyNumbersValidator(), Validators.maxLength(13)]],
salairePlafonne: ['', [Validators.required, this.onlyNumbersValidator(), Validators.maxLength(13)]],
salaireDifferentiel: ['', [Validators.required, this.onlyNumbersValidator(), Validators.maxLength(13)]]
});
this.salaireRetraiteService.getAllSalaires().subscribe((salaires) => {
this.salaires = salaires;
});
}

onlyNumbersValidator() {
return (control: AbstractControl) => {
const value = control.value;
if (!value) {
return null;
}

  const onlyNumbers = /^[0-9]+$/;
  if (!onlyNumbers.test(value)) {
    return { onlyNumbers: true };
  }
  return null;
};

}`

Please how can I control the input field to only accepts numbers with maxlength in the html part

#

Validating form using Angular v17

fathom portal
#

If you want your data to be a number (in the mathematical meaning of it, i.e. not a postal code or a phone number for example), then use an <input type="number">. If you want your data to be a string, composed only of digits, use the Validators.pattern() validator, using a regex that only accepts what you want.
Note that a Validator won't prevent the user to enter something invalid. It will only make the form control invalid. It's your job to display an error message if it's invalid, and to avoid submitting the form.

teal hawk
#

yes I want to display an error msg when the input field have another character than numbers (0 -> 9) and to prevent the user from submitting the form

fathom portal
#

I want to display an error msg
So you need something like

<div *ngIf="salaireForm.controls.numEmp.hasError('required')">The num emp is mandatory</div>

I created, and use, ngx-valdemort to help with validation error messages: https://ngx-valdemort.ninja-squad.com/

to prevent the user from submitting the form

saveSalaire() {
  if (!this.salaireForm.valid) {
    return;
  }
  // do the actual commit here
}
teal hawk
#

Yes the problem that when I write those lines in html, an error appears:
NG0303: Can't bind to 'ngIf' since it isn't a known property of 'div' (used in the '_SalaireRetraiteComponent' component template).
If the 'ngIf' is an Angular control flow directive, please make sure that either the 'NgIf' directive or the 'CommonModule' is included in the '@Component.imports' of this component.

#

I think it is due to standalone

fathom portal
#

The error message precisely tells you what to do. Read it carefully.

teal hawk
#

Oh thx I import in ts file but didn't put it in imports^^

#

thx a lot

#

Object is possibly 'undefined'.ngtsc(2532)
salaire-retraite.component.ts(12, 4): Error occurs in the template of component SalaireRetraiteComponent.
do I put ! after controls

fathom portal
#

Which line of the template causes this error?

teal hawk
#

<div *ngIf="salaireForm.controls.numEmp.hasError('required')">The num emp is mandatory</div>

#

the controls is underlined numEmp also

fathom portal
#

salaireForm: FormGroup | undefined; should be salaireForm: FormGroup<TheCorrectedTypeHere>. It should be initialized in the constructor, not in ngOnInit.
Read https://blog.ninja-squad.com/2022/04/21/strictly-typed-forms-angular/ to learn about typed forms.
Note that all the questions you had here are answered in our book, which is really cheap. You should probably read it. And there's a French version BTW. https://books.ninja-squad.com/angular