Alerts run regardless of conditions (Not part of courses)

This is not related to any courses here. I have asked this question in a few places and have not received any help I have some code that will run when a button is clicked on another page. The code looks for the student email and password, what I am trying to do is if email is right and the password is wrong then alert that the password is wrong. If the password is right, and email is wrong then alert the user about the email being wrong. If both password and email are wrong then alert that both are wrong. My problem right now is even if the password and email are right, I am still getting the alert that the email is wrong, and the alert that both are wrong

import { Component, OnInit, NgZone } from '@angular/core';
import { Router } from '@angular/router';
import { CrudService } from 'src/app/service/crud.service';
import { FormGroup, FormBuilder } from '@angular/forms';


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

  loginForm: FormGroup;
  register: FormGroup;
  Student: any = [];

  studentId: any;

  constructor(
    public formBuilder: FormBuilder,
    private router: Router,
    private ngZone: NgZone,
    private crudService: CrudService
  ) {
    this.register = this.formBuilder.group({})

    this.loginForm = this.formBuilder.group({
      Email: [''],
      Password: ['']
    })
  }
  ngOnInit(): void {

    this.crudService.GetCredintials().subscribe(res => {
      console.log(res)
      this.Student = res;
    });

  }

  onLogin(): any {
    var emailInput = (<HTMLInputElement>document.getElementById('emailInput')).value.trim();
    var passInput = (<HTMLInputElement>document.getElementById('passInput')).value.trim();
    var emailFormat = "^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$";
  
    if(!emailInput.match(emailFormat)){
        alert("Please enter a valid email!");
    }

    if(passInput ===''){
      alert("Password field can not be empty!");
    }

    for (let i = 0; i < this.Student.length; i++) {

      if (emailInput == this.Student[i].email) {
        console.log('email success');
        if (passInput == this.Student[i].password) {
          console.log('pasword success');
          //get the id
          console.log(this.Student[i]._id);
          this.studentId = this.Student[i]._id;
          localStorage.setItem("studentId", this.Student[i]._id);
          }
        } 
        else if (emailInput == this.Student[i].email && passInput !== this.Student[i].password){
          alert('Password is incorrect for this email!');
          console.log('password fail');
        }
      else if (emailInput !== this.Student[i].email && passInput == this.Student[i].password) {
        alert("Email is incorrect for this password!");
        console.log('email fail');
      }
      else if (emailInput !== this.Student[i].email && passInput !== this.Student[i].password) {
        alert("Both password and email are incorrect!");
      }
      else{
        console.log("successful login");
      }
    }
  }
  onRegisterClick(): any {
    this.ngZone.run(() => this.router.navigateByUrl('/register-page'))
  }

}

Hi,
I’m not familiar with Angular, but I think the problem comes with the .match() method. .match() returns an array with all matching substrings found in a regular expression.
But you’re not passing a regular expression to the method and you’re not applying it to a string. So if this match method is the JS match method rather than anything built in from Angular, your if clause won’t evaluate to anything truthy which means that it’s negation will always be true.

Appreciate the reply. That was just a test you could say, I was looking for anything other then using comparisons that might work. The code I have now is

import { Component, OnInit, NgZone } from '@angular/core';
import { Router } from '@angular/router';
import { CrudService } from 'src/app/service/crud.service';
import { FormGroup, FormBuilder } from '@angular/forms';


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

  loginForm: FormGroup;
  register: FormGroup;
  Student: any = [];

  studentId: any;

  constructor(
    public formBuilder: FormBuilder,
    private router: Router,
    private ngZone: NgZone,
    private crudService: CrudService
  ) {
    this.register = this.formBuilder.group({})

    this.loginForm = this.formBuilder.group({
      Email: [''],
      Password: ['']
    })
  }
  ngOnInit(): void {

    this.crudService.GetCredintials().subscribe(res => {
      console.log(res)
      this.Student = res;
    });

  }

  onLogin(): any {
    var emailInput = (<HTMLInputElement>document.getElementById('emailInput')).value.trim();
    var passInput = (<HTMLInputElement>document.getElementById('passInput')).value.trim();
    var emailFormat = "^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$";
  
    if(!emailInput.match(emailFormat)){
        alert("Please enter a valid email!");
    }

    if(passInput ===''){
      alert("Password field can not be empty!");
    }

    for (let i = 0; i < this.Student.length; i++) {

      if (emailInput == this.Student[i].email) {
        console.log('email success');
        if (passInput == this.Student[i].password) {
          console.log('pasword success');
          //get the id
          console.log(this.Student[i]._id);
          this.studentId = this.Student[i]._id;
          localStorage.setItem("studentId", this.Student[i]._id);
          
          this.ngZone.run(() => this.router.navigateByUrl('/course-list'))
          }
        } 
        else if (emailInput == this.Student[i].email && passInput !== this.Student[i].password){
          alert('Password is incorrect for this email!');
          console.log('password fail');
        }
      else if (emailInput !== this.Student[i].email && passInput == this.Student[i].password) {
        alert("Email is incorrect for this password!");
        console.log('email fail');
      }
      else if (emailInput !== this.Student[i].email && passInput !== this.Student[i].password) {
        alert("Both password and email are incorrect!");
      }
      else{
        console.log("successful login");
      }
    }
  }
  onRegisterClick(): any {
    this.ngZone.run(() => this.router.navigateByUrl('/register-page'))
  }

}

However, it still acts the same way

Hmm, the relevant passage is untouched…
You were wondering why the alerts pop up, right?

Not sure if I follow. The alerts pop when the conditions are met like they should, but they also pop up in the user enters the correct email and password

but the user can still log in if they are correct

Because this:

doesn’t return anything valid. The match method isn’t applied correctly.

str.match(regex) <-- must be a regex (which it isn't)
^
|
must be a string (which it isn't)

Maybe you’re looking for .test() instead. That returns a bool. (But you still need a regex and a string for that.)

So, this runs just fine. If I am missing any of the regex I get the alert. I am not worried about that alert

var emailFormat = “[1]+@[a-zA-Z0-9.-]+$”;

if(!emailInput.match(emailFormat)){
    alert("Please enter a valid email!");
}

these are the alerts I am having trouble with

for (let i = 0; i < this.Student.length; i++) {

      if (emailInput == this.Student[i].email) {
        console.log('email success');
        if (passInput == this.Student[i].password) {
          console.log('pasword success');
          //get the id
          console.log(this.Student[i]._id);
          this.studentId = this.Student[i]._id;
          localStorage.setItem("studentId", this.Student[i]._id);
          
          this.ngZone.run(() => this.router.navigateByUrl('/course-list'))
        } else if (emailInput == this.Student[i].email && passInput !== this.Student[i].password){
          alert('Password is incorrect for this email!');
          console.log('password fail');
        }
      } else if (emailInput !== this.Student[i].email && passInput == this.Student[i].password) {
        alert("Email is incorrect for this password!");
        console.log('email fail');
      }
      else if (emailInput !== this.Student[i].email && passInput !== this.Student[i].password) {
        alert("Both password and email are incorrect!");
      }
      else{
        console.log("successful login");
      }
    }

  1. a-zA-Z0-9+_.- ↩︎

Ok, I don’t know what these imported methods do.
What does console.log(res) log?
I don’t yet understand why you loop over whatever is stored this.Student when you’re just trying to validate one input at a time?

Appreciate your help, but I think I have come to a solution. It does not do everything I want it to do, but I think it will keep the code simpler and cleaner. Instead of trying to check with email and password is wrong, I went with is

else if (emailInput !== this.Student[i].email ||  passInput !== this.Student[i].password ){
          alert('Password or email is incorrect for the user');
          console.log('password and email failed');
        }

This way I can show an error if either are wrong instead of trying to look if the password or email is wrong

1 Like

I am back, unforunatley, the soultion did not work and I realized why. That if, and all those other else/ifs cant be in the for loop. So, I am trying something like this

const user = this.Student.find((student:any =>student.email === emailInput && student.password === passInput);

But I get an error on the arrow saying "expected ’ , ’ " I am unsure of how to handle this error, and google has not brought up anything helpful yet

This is the full file again

import { Component, OnInit, NgZone } from '@angular/core';
import { Router } from '@angular/router';
import { CrudService } from 'src/app/service/crud.service';
import { FormGroup, FormBuilder } from '@angular/forms';


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

  loginForm: FormGroup;
  register: FormGroup;
  Student: any = [];

  studentId: any;

  constructor(
    public formBuilder: FormBuilder,
    private router: Router,
    private ngZone: NgZone,
    private crudService: CrudService
  ) {
    this.register = this.formBuilder.group({})

    this.loginForm = this.formBuilder.group({
      Email: [''],
      Password: ['']
    })
  }
  ngOnInit(): void {

    this.crudService.GetCredintials().subscribe(res => {
      console.log(res)
      this.Student = res;
    });

  }

  onLogin(): any {
    var emailInput = (<HTMLInputElement>document.getElementById('emailInput')).value.trim();
    var passInput = (<HTMLInputElement>document.getElementById('passInput')).value.trim();
    var emailFormat = "^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$";
    
    const user = this.Student.find((student:any =>student.email === emailInput && student.password === passInput);

      if (user) {
        // we have user in database
        console.log("successful login");
    } else {
        console.log("login failed");
    }
  
    if(!emailInput.match(emailFormat)){
        alert("Please enter a valid email!");
    }

    if(passInput ==''){
      alert("Password field can not be empty!");
    }
     
    

    for (let i = 0; i < this.Student.length; i++) {

      if (emailInput == this.Student[i].email) {
        console.log('email success');
        if (passInput == this.Student[i].password) {
          console.log('pasword success');
          //get the id
          console.log(this.Student[i]._id);
          this.studentId = this.Student[i]._id;
          localStorage.setItem("studentId", this.Student[i]._id);
          
          this.ngZone.run(() => this.router.navigateByUrl('/course-list'))

        } 
      } 
    }
  }
  onRegisterClick(): any {
    this.ngZone.run(() => this.router.navigateByUrl('/register-page'))
  }

}