How to login validation in angular4?

Asked

Viewed 346 times

0

Dear friends, good afternoon, I would like to know how to show an invalid password or user message in angular 4.` Login Hello! Log in with your email

<div class="row">
    <div class="input-field col s12">
        <div class="form-group">
            <label for="input-email" class="sr-only">Digite seu email</label>
            <input [(ngModel)]="_user.email" id="usuario" class="form-control" placeholder="Digite seu email">
        </div>
        <div class="form-group">
            <label for="input-password" class="sr-only">Password</label>
            <input [(ngModel)]="_user.password" id="senha" type="password" class="form-control" placeholder="Senha">
        </div>
        <button type="submit" name="action" (click)="makeLogin()" class="btn btn-block btn-hero-success"> Entrar </button>
    </div>
</div>

import { Component, OnInit } from '@angular/core';
import { AuthService } from './auth.service';
import { Usuario } from './usuario';
import { User } from "./user";

@Component({
   selector: 'ngx-login',
   templateUrl: './login.component.html',
   styleUrls: ['./login.scss'],
})
export class LoginComponent implements OnInit {

   _user: User = new User();
   constructor(private _authService: AuthService) { }

   ngOnInit() {
       this.logout();
   }

   logout() {
       this._authService.userNoAuthenticated();
   }

   makeLogin() {
       this._authService.getUser(this._user);
   }
}

1 answer

1

Angular has a very good validator, Validators. Here’s an example of how to implement it:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { patternValidator } from 'app/shared/pattern-validator';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

  loginForm: FormGroup;

  ngOnInit() {
    this.createForm();
  }

  private createForm() {
    this.loginForm = new FormGroup({
      // tslint:disable-next-line
      email: new FormControl('', [Validators.required, patternValidator(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)]),
      password: new FormControl('', Validators.required),
    });
  }

  public login() {
    console.log(this.loginForm.value);
  }

}

To create the patternValidator:

import { AbstractControl, ValidatorFn, FormGroup } from '@angular/forms';

export function patternValidator(regexp: RegExp): ValidatorFn {
  return (control: AbstractControl): { [key: string]: any } => {
    const value = control.value;
    if (value === '') {
      return null;
    }
    return !regexp.test(value) ? { 'patternInvalid': { regexp } } : null;
  };
}

Enter a form tag with formGroup surrounding your form: . And your input must contain formControl and mdInput: .

Follow an example:

<md-card>
  <md-card-title>Connection</md-card-title>
  <md-card-content>
    <form [formGroup]="loginForm">
      <md-input-container [ngClass]="{'error': loginForm.controls['email'].errors && !loginForm.controls['email'].pristine}" dividerColor="{{loginForm.controls['email'].errors && !loginForm.controls['email'].pristine ? 'warn' : 'primary'}}">
        <input type="email" mdInput formControlName="email" placeholder="Email" required>
        <div *ngIf="loginForm.controls['email'].errors && !loginForm.controls['email'].pristine" class="error-msg">
          <div [hidden]="!loginForm.controls['email'].errors.required">Email is required.</div>
          <div [hidden]="!loginForm.controls['email'].errors.patternInvalid">Email is invalid.</div>
        </div>
      </md-input-container>
      <md-input-container [ngClass]="{'error': loginForm.controls['password'].errors && !loginForm.controls['password'].pristine}"
        dividerColor="{{loginForm.controls['password'].errors && !loginForm.controls['password'].pristine ? 'warn' : 'primary'}}">
        <input type="password" mdInput formControlName="password" placeholder="Password" required>
        <div *ngIf="loginForm.controls['password'].errors && !loginForm.controls['password'].pristine" class="error-msg">
          <div [hidden]="!loginForm.controls['password'].errors.required">Password is required.</div>
        </div>
      </md-input-container>
    </form>
  </md-card-content>
  <md-card-actions align="end">
    <button md-raised-button class="btn" [disabled]="loginForm.invalid" (click)="login()">Login</button>
  </md-card-actions>
</md-card>

I followed this example and it worked, I used Ionic 3. I changed only what I needed to adapt to my problem. This is the article link, hope it helps.

Browser other questions tagged

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