React function Component Validation

7.2k views Asked by At

I am a beginner in react. I was working on the react function component with forms using hooks. Can anyone please tell how can I apply validation on email text when it is invalid or empty, and disable the continue button if the form is not valid.

import React, { useState } from "react";
const ForgotPassowrd = () => {
const [emailId, setemailId] = useState("");
const forgotPasswordClick = (event) => {};
return (
<div>
    <div className="NewPassword-form form_wrapper">
        <div className="form-body">
        <form action="#">
        <div>
        <div className="form-group">
                <label htmlFor="password">Email-Id</label>
                <div className="input-group">
                    <input type="text" className="form-control" value={emailId} onChange={(event)=> 
                    setemailId(event.target.value)}/>
                </div>
            </div>
            <button type="button" onClick={forgotPasswordClick} className="btn btn-lg 
            btn-block">Continue</button>
            </div>
          </form>
          </div>
        </div>
     </div>
    ); 
    };
   export default ForgotPassowrd;
2

There are 2 answers

0
Sunny Prakash On

Try below. I have added inline comments for better understanding. Comment your queries if you have any.

// Regex to check valid email
const validEmail = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/g

import React, { useState } from "react";
const ForgotPassowrd = () => {
const [emailId, setemailId] = useState("");
//State to disable/enable continue button
const [disableBtn, setDisableBtn] = useState(false);
const forgotPasswordClick = (event) => {};
const handleSubmit = e => {
    e.preventDefault();
    // Do whatever you want to do after you click submit button
}
const handleChange = e => {
    setemailId(event.target.value);
    setDisableBtn(validEmail.test(e.target.value));
}
return (
    <div>
    <div className="NewPassword-form form_wrapper">
        <div className="form-body">
        {/* Remove action and use onSubmit handler*/}
        <form onSubmit={handleSubmit}>
        <div>
        <div className="form-group">
                <label htmlFor="password">Email-Id</label>
                <div className="input-group">
                     {/* Introduced name attribute to help you with handleSubmit handler*/}
                    <input name="email" type="text" className="form-control" value={emailId} onChange={(event)=> 
                    setemailId(event.target.value)}/>
                </div>
            </div>
            <button onClick={forgotPasswordClick} className="btn btn-lg 
            btn-block" disabled={disableBtn}>Continue</button>
            </div>
          </form>
          </div>
        </div>
     </div>
    ); 
};
export default ForgotPassowrd;
0
Asif Mushtaq On
    **Try it.This may be helpfull for you! If you can any queries comment below.**
    
    
          const LoginV2 = ({}) => {
    // state
    
    const [loginForm, setLoginForm] = useState({
    email: undefined,
            password: undefined,
            emailValid: false,
            passwordValid: false,
          });
          const [error, setError] = useState({ email: undefined, password: undefined });

// state update        
          const handleLoginForm = (e) => {
            checkValidity(e.target.name, e.target.value);
            setLoginForm({ ...loginForm, [e.target.name]: e.target.value });
          };
// validation function        
          const checkValidity = (inputName, inputValue) => {
            switch (inputName) {
              case "email":
                let pattern = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
                loginForm.emailValid = pattern.test(inputValue);
                break;
              case "password":
                loginForm.passwordValid = inputValue.length >= 6;
                break;
              default:
                break;
            }
          };
 // form submit       
          const onSubmitLoginForm = () => {
            console.log(loginForm);
            if (!loginForm.emailValid) {
              setError(prevError => {
                  return { 
                      ...prevError, 
                      email: "Invalid Email Address" 
                    }
              }); 
            }
            if (!loginForm.passwordValid) {
              setError(prevError => {
                  return {
                ...prevError,
                password: "Password must be at least six characters long"
              }
            }); 
            }
        
          return (
            <div class="row">
              <div class="form">
                <div class="col span-1-of-2">
                  <div class="username">
                    <p class="login-para text-align-center">LOG IN VIA EMAIL</p>
                    <form method="post" action="#" class="login-form">
                      {error.email && (
                        <div class="alert alert-danger">
                          <p>
                            {" "}
                            <strong> {alertText} </strong> {error.email}
                          </p>
                        </div>
                      )}
        
                      {error.password && (
                        <div class="alert alert-danger">
                          <p>
                            {" "}
                            <strong> {alertText} </strong> {error.password}
                          </p>
                        </div>
                      )}
        
                      <div class="info-box">
                        {icon && <i class="fas fa-user-alt login-icon"></i>}
                        <input
                          type="text"
                          name="email"
                          placeholder="Your Email"
                          onChangeText={(e) => handleLoginForm(e)}
                          inputValue={loginForm.email}
                        />
                      </div>
        
                      <div class="info-box">
                        {icon && <i class="fas fa-user-alt login-icon"></i>}
                        <input
                          type="password"
                          name="password"
                          placeholder="Your Password"
                          onChangeText={(e) => handleLoginForm(e)}
                          inputValue={loginForm.password}
                        />
                      </div>
        
                      <div class="buttons">
                        <input type="checkbox" />
                        <label class="remember" for="#">
                          Remember me
                        </label>
                       <div class="form-btn-disabled" onClick={onSubmitLoginForm} 
                       > 
                         LOGIN NOW 
                       </div>
                      
                      </div>
                    </form>
                  </div>
                </div>
              </div>
            </div>
          );
        };
        export default LoginV2;