Search code examples
javascriptarraysjsonerror-suppression

How to compare Inputs and JSON data


I'm working on a school project and I need to validate some users without making a real Database. My problem is that when I compare the information entered in the inputs with the information storaged in JSON, it pops an error for every option that doesn't match. What I want is to reduce the multiple errors into only one (in case that the username or the password doesn't matches with the information storaged in JSON). Here is My JavaScript:

const form = document.querySelector('form');

form.addEventListener('submit', function(e){
	e.preventDefault();
    
    const emailInput = document.querySelector('#email').value;
	const pwdInput = document.querySelector('#pwd').value;

	const object = {
		email: emailInput,
		pwd: pwdInput
	};

fetch('users.json')
  .then(res => res.json())
	.then(data => {
		data.forEach(function(user) {

			const userInfo = JSON.stringify(user);
			const databaseInfo = JSON.stringify(object);


			if(userInfo === databaseInfo) {
					console.log('success');
			} else {
				console.log('err');
			}

		});
	})

	.catch(error => console.log('error'));

});

And here is the fake database made with JSON:

     [
      {"email": "James", "pwd": "1111"},
      {"email": "Peter", "pwd": "2222"},
      {"email": "Josh", "pwd": "3333"}
     ]

Solution

  • Using vanilla JavaScript :

    // This is only to simulate your fetch from JSON
    function fakeFetch () 
    {
      return Promise.resolve([
        {"email": "James", "pwd": "1111"},
        {"email": "Peter", "pwd": "2222"},
        {"email": "Josh", "pwd": "3333"}
      ]);
    }
    
    const form = document.querySelector('form');
    
    form.addEventListener( 'submit', function(e){
      e.preventDefault();
        
      const emailInput = document.querySelector('#email').value;
      const pwdInput = document.querySelector('#pwd').value;
    
      const object = {
        email: emailInput,
        pwd: pwdInput
      };
    
      fakeFetch()     
      .then( users => {
       
        // Check each user in users and try to find a match
        for ( let user of users )
        {
          // Destructuring email and password from the current user
          let { email, pwd } = user;
          
          // Comparing email and pwd from active user with the ones in object
          if ( email === object.email && pwd === object.pwd )
          {
            // Found, do something
            console.log( 'found!' );
            return;
          }
        }
        
        // Not found, do something else
        console.log( 'Not found...' );
        
      })
      .catch(error => console.log( error ) );
    
    });
    <form>
      <input type="text" id="email"/>
      <input type="test" id="pwd"/>
      <input type="submit"/> 
    </form>