3

I am using [(ngModel)] to display messages if validation using pattern is not matched, I am unable to display the error message. There is two validation one is for field as required and another is for the pattern error. One error is displaying that is the required one but another is not displaying when pattern is wrong. Thank you guys in advance for sharing your knowledge.

// login.html

     <div class="app-body">
      <main class="main d-flex align-items-center">
        <div class="container">
          <div class="row">
            <div class="col-md-8 mx-auto">
              <div class="card-group">
                <div class="card p-4">
                  <div class="card-body">
                    <!-- <form (ngSubmit)="onSubmit(f.value)" #f=ngForm> -->
                    <form #form="ngForm">
                      <h1>Login</h1>
                      <p class="text-muted">Sign In to your account</p>
                      <div class="input-group mb-3" [ngClass]="{'has-error': (!username.valid && username.touched), 'has-success': (username.valid && username.touched)}">
                        <div class="input-group-prepend">
                          <span class="input-group-text"><i class="icon-user"></i></span>
                        </div>
                        <input type="email" class="form-control" [(ngModel)]="user.username" placeholder="Username"
                          autocomplete="username" ngModel #username="ngModel" name="username" required>
                        <div *ngIf="username.errors?.required && (username.dirty || username.touched)" class="help-block" style="color: #813838">
                          Email is required!
                          <div *ngIf="username.errors?.pattern" class="help-block" style="color: #813838">
                              pattern is required!
                            </div>
                        </div>
                        
                      </div>  
                      <div class="input-group mb-4" [ngClass]="{'has-error': (!password.valid && password.touched), 'has-success': (password.valid && password.touched)}">
                        <div class="input-group-prepend">
                          <span class="input-group-text"><i class="icon-lock"></i></span>
                        </div>
                        <input type="password" [(ngModel)]="user.password" class="form-control" placeholder="Password"
                          autocomplete="current-password" #password="ngModel" ngModel name="password" required>
                        <div *ngIf="password.invalid && (password.dirty || password.touched)" class="help-block" style="color: #813838">
                          Password is required!
                        </div>  
                      </div>
                      <div class="row">
                        <div class="col-6">
                          <button type="submit" [disabled]="!form.valid" class="btn btn-primary px-4" (click)="onSubmit()">Login</button>
                        </div>
                        <div class="col-6 text-right">
                          <button type="button" class="btn btn-link px-0">Forgot password?</button>
                        </div>
                      </div>
                    </form>
                  </div>
                </div>
                <div class="card text-white bg-primary py-5 d-md-down-none" style="width:44%">
                  <div class="card-body text-center">
                    <div>
                      <h2>Sign up</h2>
                      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
                        labore et dolore magna aliqua.</p>
                      <button type="button" class="btn btn-primary active mt-3">Register Now!</button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </main>
    </div>

// login.ts

import { Component, OnInit } from '@angular/core';
import { NgForm, FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
import { getLocaleTimeFormat } from '@angular/common';
import { Router } from '@angular/router';

@Component({
  selector: 'app-dashboard',
  templateUrl: 'login.component.html'
})
export class LoginComponent implements OnInit {
  // regexEmail = /^(([^<>()\[\]\\.,;:\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,}))$/;
  regexEmail = /^(([^<>()\[\]\\.,;:\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,}))$/;
  user: any = {};
  pass: any = {};
  form: FormGroup;
  constructor(private router: Router, private formBuilder: FormBuilder
    ) {

  }
ngOnInit() {
    this.form = new FormGroup({
      'username': new FormControl("", [Validators.required, Validators.pattern(this.regexEmail)]),
      'password': new FormControl("", [Validators.required])
    });
  }
onSubmit() {
    console.log(this.user.username);
    console.log(this.form.value);
this.user = this.form.value.username !== null ? this.user = this.loginForm.value.username : this.user = "";
    this.pass = this.form.value.password !== null ? this.pass = this.loginForm.value.password : this.pass = "";
    if (this.user === localStorage.getItem('username') && this.pass === localStorage.getItem('password')) {
      this.router.navigate(['/dashboard']);
      alert("LOG IN SUCCESS!");
    }
    else {
      this.onValidate();
      alert("Username and Password did not match!");
      this.loginForm.reset();
      // this.onValidate()
    }
 }
}
1
  • The first message is displaying but the pattern check message is not displayed. Commented Oct 12, 2018 at 16:31

2 Answers 2

3

Make changes in input field:

 <div class="input-group mb-3" [ngClass]="{'has-error': (!username.valid && username.touched), 'has-success': (username.valid && username.touched)}">
 <div class="input-group-prepend">
    <span class="input-group-text"><i class="icon-user"></i> 
    </span>
</div>
<input name="username" type="email" class="control-label" [(ngModel)]="user.username" placeholder="Username" autocomplete="username" #username="ngModel" required />
<div *ngIf="username.invalid && username.errors.required && (username.dirty || username.touched)" class="help-block" style="color: #813838">Email is required!</div>

for more details you can read the official documentation Form Validation

Sign up to request clarification or add additional context in comments.

Comments

0

For email validation you need to add another <div> for disaplying pattern error like this :

<div *ngIf="username.invalid && username.errors.pattern && (username.dirty || username.touched)" class="help-block" style="color: #813838">Email is Not Vliad!</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.