Home > database >  React.JS Validating Two Inputs
React.JS Validating Two Inputs

Time:05-11

I am currently in the process of learning React JS. I have a register file that allows the user to register. I want to validate that the two fields match each other before passing the information to the server in that register file. My code is shown below for a visual view. I did some searching around and noticed a fundamental term called "handlechange" was thrown around a lot, but I wasn't sure how to use that with my "onchange" event. Any advice will be appreciated.

import React, { useState } from 'react';
import Axios from 'axios';
import './Register.css';

function Register() {
   const [firstName, setFirstName] = useState('');
   const [lastName, setLastName] = useState('');
   const [email, setEmail] = useState('');
   const [password, setPassword] = useState('');

   const register = () => { 
       Axios.post('http://localhost:3001/user/register', {
       firstName: firstName,
       lastName: lastName,
       email: email,
       password: password
     }).then((response) => {
       console.log(response);
     });
   };

   return (
     <div className='Register'>
     <h1>Registration</h1>
  <div className='RegisterForm'>
    <input type='text' name='firstName' placeholder='First Name' onChange={(event) => {setFirstName(event.target.value); }} />
    <input type='text' name='lastName' placeholder='Last Name' onChange={(event) => {setLastName(event.target.value); }} />
  </div>
  <div className='RegisterForm'>
    <input type='text' name='email' placeholder='Email'/>
    <input type='text' name='emailConfirmation' placeholder='Confirm Email' onChange={(event) => {setEmail(event.target.value); }} />
  </div>
  <div className='RegisterForm'>
    <input type='password' name='password' placeholder='Password'/>
    <input type='password' name='passwordConfirmation' placeholder='Confirm Password' onChange={(event) => {setPassword(event.target.value); }} />
  </div>
  <div className='RegisterForm'>
    <button onClick={register}>Register</button>
  </div>
</div>
 )
}

export default Register;

CodePudding user response:

If you want to validate fields, then just before the axios call , compare the fields/ values that are required, and if they match then call the axios api else just throw the error that is required to be shown on the UI for user.

//Add validation inside the function
 const register = () => { 
    // check if firstName and LastName is not empty 
    // or any other validation you want - add it here.
      if(firstName === "" || LastName ===""){ 
           // alert the user for invalid values
            alert(" FirstName and LastName cannot be empty");
       }
       else  {
       Axios.post('http://localhost:3001/user/register', {
       firstName: firstName,
       lastName: lastName,
       email: email,
       password: password
     }).then((response) => {
       console.log(response);
     });
    }

   };


  • Related