Home > Software engineering >  How can I validate an angular form
How can I validate an angular form

Time:01-19

I have this inscription form. I tried to validate it but in vain. inputs are saved in my database despite they are empty I want to have these validations:

  • All inputs are required
  • email address should be valid
  • name should be composer by only letters
  • Password should have minimum 8 characters, at least 1 uppercase letter, 1 lowercase letter and 1 number

I want to have a message under evey invalid input.(in <div id="na"></div> for example).How can I do this please?

HTML file

<h2 >Inscription</h2>
<div >
<div >
</div>
<div >
<div >
<form [formGroup]="angForm" (ngSubmit)="postdata(angForm)" autocomplete="off">
<div >
<label for="name">Nom</label>
<input type="text" name="name" formControlName="name" autocomplete="off" id="name" 
 placeholder="Nom">
</div>
<div id="na"></div>
<div >
<label for="email">Email</label>
<input type="email" name="email" formControlName="email" autocomplete="off" id="email" 
 placeholder="Email">
</div>
<div id="mail"></div>
<div >
<label for="Password">Mot de passe</label>
<input type="password" name="Password" formControlName="password" autocomplete="off" 
id="password"  placeholder="Mot de passe">
</div>
<div id="pwd"></div>
<button type="sumit" >Enregistrer</button>
</form>
</div>
</div>
<div >
</div>
</div>

Type script file

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, FormBuilder, Validators, NgForm } from '@angular/forms';
import { first } from 'rxjs/operators';
import { Router } from '@angular/router';
import { ApiService } from '../api.service';
@Component({
selector: 'app-inscription',
templateUrl: './inscription.component.html',
styleUrls: ['./inscription.component.css']
})
export class InscriptionComponent implements OnInit {
angForm: FormGroup;
constructor(private fb: FormBuilder,private dataService: ApiService,private router:Router) {
this.angForm = this.fb.group({
email: [],
password: [],
name: [],
mobile: []
});
}
ngOnInit() {
}
postdata(angForm1:any){this.dataService.userregistration(angForm1.value.name,angForm1.value.email,angForm1.value.password)
.pipe(first())
.subscribe(
data => {
this.router.navigate(['login']);

},
error => {
});
}
 get email() { return this.angForm.get('email'); }
 get password() { return this.angForm.get('password'); }
 get name() { return this.angForm.get('name'); }
 }

thanks in advance

CodePudding user response:

this.angForm = this.fb.group({
email: ['', Validators.required, Validators.email],
password: ['', Validators.required, Validators.minLength(8), Validators.pattern("(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}")],
name: ['', Validators.required, Validators.pattern('^[a-zA-Z ]*$')],
mobile: [null, Validators.required, Validators.minLength(10), Validators.maxLength(10)]
});
This is the syntax for Validations.

In HTML, before closing of form-group div write
 <span 
       *ngIf="(angForm.name.touched || submitted) && 
                angForm.name.errors?.required">
                                Name is required
                            </span>

 <span 
       *ngIf="((angForm.password.touched || submitted) && 
                angForm.password.errors?.required )|| (angForm.invalid && submitted)">
Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters </span>

same applies for email, mobile error msg in HTML.

Please refer for reactive form validation. https://www.freecodecamp.org/news/how-to-validate-angular-reactive-forms/

CodePudding user response:

response to Rothitha If you don't want to use the "auxiliar variable" submitted you can use in submit.

submit(form:FormGroup)
{
   if (form.invalid)
      form.markallAsTouched()
   else
   {
      ..doSomething..
   }
}

If we can better mannagement about errors (remove this ugly *ngIf="angForm.get('password').touched && angForm.get('password').touched" we can use a tecnica similar bootstrap mannage the error

We use a .css like

.invalid-feedback
{
   display:none
}
.ng-invalid.ng-touched ~ .invalid-feedback
{
  display: block;
}

And an html like

  <!--enclosed all under a div-->
  <div>

    <!--a label-->
    <label for="email">Email</label>

    <!--a input-->
    <input id="email" formControlName="email">

    <!--a div invalid-feedback">

      <!--if there're several validators use *ngIf-->
        <div *ngIf="angForm.controls.email.errors?.required">Email is required</div>
        <div *ngIf="angForm.controls.email.errors?.email">it's not a valid email</div>
    </div>

  </div>

See stackblitz

CodePudding user response:

thanks a lot rohitha I tried to use your code but I got these errors

Compiled with problems:X
ERROR
src/app/inscription/inscription.component.html:12:24 - error TS2339: Property 'name' does not exist on type 'FormGroup'.
12        *ngIf="(angForm.name.touched || submitted) &&
                      ~~~~
src/app/inscription/inscription.component.ts:8:14
8 templateUrl: './inscription.component.html',
               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component InscriptionComponent.
ERROR
src/app/inscription/inscription.component.html:12:40 - error TS2339: Property 'submitted' does not exist on type 'InscriptionComponent'.
12        *ngIf="(angForm.name.touched || submitted) &&
                                      ~~~~~~~~~
src/app/inscription/inscription.component.ts:8:14
8 templateUrl: './inscription.component.html',
               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component InscriptionComponent.
ERROR
src/app/inscription/inscription.component.html:13:25 - error TS2339: Property 'name' does not exist on type 'FormGroup'.
13                 angForm.name.errors?.required">
                       ~~~~
src/app/inscription/inscription.component.ts:8:14
8 templateUrl: './inscription.component.html',
               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component InscriptionComponent.
ERROR
src/app/inscription/inscription.component.html:21:25 - error TS2339: Property 'email' does not exist on type 'FormGroup'.
21        *ngIf="((angForm.email.touched || submitted) &&
                       ~~~~~
 src/app/inscription/inscription.component.ts:8:14
8 templateUrl: './inscription.component.html',
               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component InscriptionComponent.
ERROR
src/app/inscription/inscription.component.html:21:42 - error TS2339: Property 'submitted' does not exist on type 'InscriptionComponent'.

 21        *ngIf="((angForm.email.touched || submitted) &&
                                        ~~~~~~~~~
 src/app/inscription/inscription.component.ts:8:14
8 templateUrl: './inscription.component.html',
               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component InscriptionComponent.
ERROR
src/app/inscription/inscription.component.html:22:25 - error TS2339: Property 'email' does not exist on type 'FormGroup'.

22                 angForm.email.errors?.required )|| (angForm.invalid && submitted)">
                       ~~~~~
src/app/inscription/inscription.component.ts:8:14
8 templateUrl: './inscription.component.html',
               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component InscriptionComponent.
ERROR
 src/app/inscription/inscription.component.html:22:72 - error TS2339: Property 'submitted' does not exist on type 'InscriptionComponent'.
  22                 angForm.email.errors?.required )|| (angForm.invalid && submitted)">
                                                                      ~~~~~~~~
   src/app/inscription/inscription.component.ts:8:14
8 templateUrl: './inscription.component.html',
               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component InscriptionComponent.
    ERROR
    src/app/inscription/inscription.component.html:30:25 - error TS2339: Property 'password' does not exist on type 'FormGroup'.
     30        *ngIf="((angForm.password.touched || submitted) &&
                       ~~~~~~~~
      src/app/inscription/inscription.component.ts:8:14
8 templateUrl: './inscription.component.html',
               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
       Error occurs in the template of component InscriptionComponent.
        ERROR
        src/app/inscription/inscription.component.html:30:45 - error TS2339: Property 'submitted' does not exist on type 'InscriptionComponent'.
         30        *ngIf="((angForm.password.touched || submitted) &&
                                           ~~~~~~~~~
         src/app/inscription/inscription.component.ts:8:14
         8 templateUrl: './inscription.component.html',
               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          Error occurs in the template of component InscriptionComponent.
          ERROR
           src/app/inscription/inscription.component.html:31:25 - error TS2339: Property 'password' does not exist on type 'FormGroup'.
           31                 angForm.password.errors?.required )|| (angForm.invalid && submitted)">
                       ~~~~~~~~
            src/app/inscription/inscription.component.ts:8:14
            8 templateUrl: './inscription.component.html',
               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            Error occurs in the template of component InscriptionComponent.
             ERROR
              src/app/inscription/inscription.component.html:31:75 - error TS2339: Property 'submitted' does not exist on type 'InscriptionComponent'.

              31                 angForm.password.errors?.required )|| (angForm.invalid && submitted)">
                                                                         ~~~~~~~~~
              src/app/inscription/inscription.component.ts:8:14
               8 templateUrl: './inscription.component.html',
               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
               Error occurs in the template of component InscriptionComponent.
  • Related