How to do validation that email is already exist or not in localStorage

979 Views Asked by At

I am trying to get the email value from input field to check if email is already exist or not.

From localStorage how to get the specific value in an array and validate the email.

Here is my code:

<!--HTML code-->
<div>
    <label for="email">Email:</label>
    <input type="email" name="email" id="email" formControlName="email">
</div>

<!--component.ts-->

onSubmit() { 
    this.user = Object.assign(this.user, this.checkoutForm.value);
    this.addUser(this.user); 
} 

addUser(user:any) {
    let users: any[] = [];
    if(localStorage.getItem('Users')) {
      users = JSON.parse(localStorage.getItem('Users') || '{}')
      users = [user, ...users];
    } else {
      users = [user];
    }
    localStorage.setItem('Users', JSON.stringify(users));
}
1

There are 1 best solutions below

0
Erik On

You can only get a complete item from you localStorage and on top of that you can only get strings from it. So instead of only getting one element you will get everything and want to keep the one element.

It depends on how your actual data looks, but this is an example of storing an array of numbers and getting element 2 from it:

localStorage.setItem('myItem', [1,2,3]);
+localStorage.getItem('myItem').split(',')[2]

Mind the '+' at the beginning of the second line to convert the value to a number.