How to validate email and CPF at angular 5?

Asked

Viewed 1,941 times

2

Dear, I would like to know how I can validate the e-mail and CPF in angular 5.

I made the basic code:

<mat-form-field class="full-width">
    <input matInput placeholder="E-mail" [formControl]="emailFormControl" [(ngModel)]="email">
    <mat-error *ngIf="emailFormControl.hasError('email') && !emailFormControl.hasError('required')">
        Por favor entre com um endereço de e-mail valido
    </mat-error>
    <mat-error *ngIf="emailFormControl.hasError('required')">
        E-mail é
        <strong>requirido</strong>
    </mat-error>
</mat-form-field>

<mat-form-field class="full-width">

    <input matInput placeholder="CPF" [formControl]="cpfFormControl" [(ngModel)]="cpf">
    <mat-error *ngIf="cpfFormControl.hasError('required')">
        CPF é
        <strong>requirido</strong>
    </mat-error>
</mat-form-field>

<button mat-button type="submit" class="btn btn-primary btn-lg btn-block button-size" (click)="Logar()">Enviar</button>
  • You want to validate the CPF mask only or validate whether the CPF is correct by the validation calculation?

  • Hello, I would like to validate if the CPF is correct by the validation calculation.

  • Welcome to Stackoverflow. I created a basic project at Stackblitz here to facilitate the demonstration of any response, feel free to make Fork.

  • The project is not working

2 answers

2

I particularly like to use Reactive Forms for Angular development. The example of validation that I will present is using Reactive Forms.

Create the Validator that Angular will use for validation. In my case I created the following class with CPF Validator. Remember that the method must return { key: value } when you have error and null when not.

export class GenericValidator {
   constructor() {}

   /**
    * Valida se o CPF é valido. Deve-se ser informado o cpf sem máscara.
   */
   static isValidCpf(): ValidatorsFn {
     return (control: AbstractControl): Validators => {
       const cpf = control.value;
       if (cpf) {
         let numbers, digits, sum, i, result, equalDigits;
         equalDigits = 1;
         if (cpf.length < 11) {
          return null;
         }

         for (i = 0; i < cpf.length - 1; i++) {
           if (cpf.charAt(i) !== cpf.charAt(i + 1)) {
             equalDigits = 0;
             break;
           }
         }

         if (!equalDigits) {
           numbers = cpf.substring(0, 9);
           digits = cpf.substring(9);
           sum = 0;
           for (i = 10; i > 1; i--) {
             sum += numbers.charAt(10 - i) * i;
           }

           result = sum % 11 < 2 ? 0 : 11 - (sum % 11);

           if (result !== Number(digits.charAt(0))) {
             return { cpfNotValid: true };
           }
           numbers = cpf.substring(0, 10);
           sum = 0;

           for (i = 11; i > 1; i--) {
             sum += numbers.charAt(11 - i) * i;
           }
           result = sum % 11 < 2 ? 0 : 11 - (sum % 11);

           if (result !== Number(digits.charAt(1))) {
             return { cpfNotValid: true };
           }
           return null;
         } else {
           return { cpfNotValid: true };
         }
      }
    return null;
  };
}

In the creation of formGroup we must define the Validator that Angular will use.

export class formComponent implements OnInit {
  form: formGroup;

  constructor(private formBuilder: FormBuilder) {}

  ngOnInit() {
    this.form = this.formBuilder.group({
      cpf: this.formBuilder.control({ value: null, disabled: false}, GenericValidator.isValidCpf())
    })
  }
}

And then just mount the HTML to display the error. A very simple way to start would be:

<form>
    <div>
        <label>CPF</label>
        <input type="text" formControlName="cpf"/>
    </div>
    <div *ngIf="form.get('cpf').getError('cpfNotValid')"> 
      O cpf não é válido.
    </div>
</form>

0

Correct in size validation:

if (cpf.length !== 11) { return { cpfNotValid: true }; }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.