Home > Software design >  angular email validation with array
angular email validation with array

Time:10-11

I'm trying to check if the user-entered email is present in the array or not. if it is present the button and message change to Sign In! and Welcome back.

Initial: Before entering email

After entering the correct email

The button and message changes but if I change the email another time....After changing email the message and button still remain the same. (i.e) The button shows Sign In when the email is changed.

app.component.html

<form>
<div >
  <label for="exampleInputEmail1">Email address</label>
  <input type="email" [(ngModel)]="email" (ngModelChange)="mailvalid()"  name="email" aria-describedby="emailHelp" placeholder="Enter email">
  <small id="emailHelp" >We'll never share your email with anyone else.</small>

  
</div>
<div >
  <label for="exampleInputPassword1">Password</label>
  <input type="password"  id="exampleInputPassword1" placeholder="Password">
</div>

<span>{{msg}}</span>
<button  tabindex="0">
<span>{{button}}</span>

app.component.ts

import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {



title = 'Resume';
button="SignUp !"
email = "";

msg="It seems like your Email Does Not Exist.....";
mails: Array<string> = ["[email protected]"];
ngOnInit()
{
this.mailvalid();
}

mailvalid()
{
for(let i=0;i<1;i  )
{
  if(this.email==this.mails[i])
  {
    this.button="SignIn !";
    this.msg="Welcome back !! ";
  }
}
}
}

CodePudding user response:

Your mailValid() just change button and message value when it enters in the if. So to change back when change the email, you need to set the values again too.

Try to use something like

mailValid() {
//Returns undefined if not present in the array
const insertedMail = this.mails.find(element => element == this.mail);

if (insertedMail != null) {
 this.button="SignIn !";
 this.msg="Welcome back !! ";
} else {
 this.button = "SignUp !"
 this.msg = "It seems like your Email Does Not Exist.....";
}
}

CodePudding user response:

it would be great if we change our markup on our template file and based on this simple component function boolean decision.

// Example
mail = '';
mails = [];
mailIsValid() { return (this.mails.indexOf(x => x == this.mail) !== -1) ? true : false }
  • Related