Krisna
Krisna

Reputation: 3423

React password validation onChange

I am using React-typescript for my app. I have created one global input component, where I can import to any component. I have created one form with email & password validation. For email validation I have use Regex and it works fine. My password and confirm password validation it works fine. Now I have decided that If user put less than 8 character I will catch the error. For that I have used Regex. That logic also works fine. I want to display the password length in handleChange function when user will type, until they don't type more than 8 characters I will show the error. After submit the form it will show both input field password did not match. But I can't get find the logic when I can add the error in handle change. I share my code in codesandbox.

This is my form validation code

import React, { useState } from "react";
import "./styles.css";
import { TextInput } from "./input";

export default function App() {
  const [formState, setFormState] = useState({
    email: ``,
    password: ``,
    passwordConfirmation: ``,
    loading: false,
    accountCreationSuccessful: false,
    errorPasswordMessage: ``,
    errorEmailMessage: ``,
    passwordLength: ``
  });

  //destructure the state
  const {
    email,
    password,
    passwordConfirmation,
    loading,
    accountCreationSuccessful,
    errorPasswordMessage,
    errorEmailMessage,
    passwordLength
  } = formState;

  const isPasswordValid = (password: any, passwordConfirmation: any) => {
    if (!password || !passwordConfirmation) return false;
    return password === passwordConfirmation;
  };

  const isEmailValid = (value: any) => {
    const emailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return emailRegex.test(value);
  };

  const passLengthValidation = (value: any) => {
    const re = new RegExp(`^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,32}$`);
    return re.test(value);
  };

  const sendForm = (payload: any) => {
    return fetch(
      "https://run.mocky.io/v3/03659a5b-fed5-4c5f-b8d0-4b277e902ed3",
      {
        method: `POST`,
        headers: {
          Accept: `application/json`,
          "Content-Type": `application/json`
        },
        body: JSON.stringify(payload)
      }
    );
  };

  const handleChange = (e: any) => {
    setFormState({
      ...formState,
      [e.target.id]: e.target.value
    });
    //In here I want to display the error.when user will type short password
  };

  const onSubmit = async (e: any) => {
    e.preventDefault();

    setFormState({
      ...formState,
      errorPasswordMessage: isPasswordValid(password, passwordConfirmation)
        ? ``
        : `Upps sorry Password did not match 😔`,
      errorEmailMessage: isEmailValid(email)
        ? ``
        : `Upps sorry wrong email  😔`,
      passwordLength: passLengthValidation(password) ? `` : `too short password`
    });

    if (
      !isPasswordValid(formState.password, formState.passwordConfirmation) ||
      !isEmailValid(formState.email) ||
      !passLengthValidation(password)
    ) {
      return;
    }

    const response = await sendForm({
      email: formState.email,
      password: formState.password
    });

    if (response.ok) {
      setFormState({
        ...formState,
        accountCreationSuccessful: true,
        email: ``,
        password: ``,
        passwordConfirmation: ``
      });
    }
  };

  return (
    <div>
      <TextInput
        type="text"
        value={email}
        onChange={handleChange}
        id="email"
        label="Email"
        required
        error={errorEmailMessage}
      />
      <TextInput
        type="password"
        value={password}
        onChange={handleChange}
        id="password"
        required
        label="password"
        isPassword
        error={passwordLength} 
        // In here I want to display if the password is did not match  or password is too short(when user start typing). i know it should be conditional 
      />
      <TextInput
        type="password"
        value={passwordConfirmation}
        onChange={handleChange}
        id="passwordConfirmation"
        required
        label="Confirm password"
        isPassword
        error={errorPasswordMessage}
      />
      <button
        type="submit"
        name="action"
        onClick={onSubmit}
        disabled={!formState.email}
      >
        {formState.loading ? `loading...` : `save`}
      </button>
    </div>
  );
}

Upvotes: 0

Views: 5913

Answers (1)

Prateek Thapa
Prateek Thapa

Reputation: 4938

You could check the id for password field and check e.target.value for password value and show error message accordingly.

const handleChange = (e: any) => {
    let passwordError = ''
    
    if (e.target.id === 'password' && password.length < 7) {
      passwordError = 'Password should be more than 8 characters'
    }
    
    setFormState({
      ...formState,
      [e.target.id]: e.target.value,
      errorPasswordMessage: passwordError
    });
    //In here I want to display the error.when user will type short password
  };

Upvotes: 2

Related Questions