Paolo.
Paolo.

Reputation: 27

How can I validate an angular form

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:

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 class="text-center">Inscription</h2>
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6 col-md-offset-3">
<div class="jumbotron">
<form [formGroup]="angForm" (ngSubmit)="postdata(angForm)" autocomplete="off">
<div class="form-group mb-3">
<label for="name">Nom</label>
<input type="text" name="name" formControlName="name" autocomplete="off" id="name" 
class="form-control input-sm" placeholder="Nom">
</div>
<div id="na"></div>
<div class="form-group mb-3">
<label for="email">Email</label>
<input type="email" name="email" formControlName="email" autocomplete="off" id="email" 
class="form-control input-sm" placeholder="Email">
</div>
<div id="mail"></div>
<div class="form-group mb-3">
<label for="Password">Mot de passe</label>
<input type="password" name="Password" formControlName="password" autocomplete="off" 
id="password" class="form-control input-sm" placeholder="Mot de passe">
</div>
<div id="pwd"></div>
<button type="sumit" class="btn btn-success">Enregistrer</button>
</form>
</div>
</div>
<div class="col-md-3">
</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

Upvotes: 0

Views: 431

Answers (2)

Eliseo
Eliseo

Reputation: 57909

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 class="invalid-feedback-->
    <div class="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

Upvotes: 0

rohitha gourabathuni
rohitha gourabathuni

Reputation: 61

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 class="text-danger"
       *ngIf="(angForm.name.touched || submitted) && 
                angForm.name.errors?.required">
                                Name is required
                            </span>

 <span class="text-danger"
       *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/

Upvotes: 2

Related Questions