反应密码验证 onChange

React password validation onChange

我正在为我的应用程序使用 React-typescript。我创建了一个全局输入组件,我可以在其中导入任何组件。我创建了一个带有 email & password 验证的表单。对于电子邮件验证,我使用了 Regex,它工作正常。我的密码和确认密码验证工作正常。现在我决定,如果用户输入的字符少于 8 个,我将捕获错误。为此,我使用了正则表达式。该逻辑也可以正常工作。我想在用户输入时在 handleChange 函数中显示密码长度,直到他们输入的字符不超过 8 个,我才会显示错误。提交表单后,它将显示两个输入字段密码不匹配。但是当我可以在句柄更改中添加错误时,我找不到逻辑。 我在 codesandbox.

中分享我的代码

这是我的表单验证码

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>
  );
}

您可以检查 password 字段的 ID 并检查 e.target.value 的密码值并相应地显示错误消息。

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
  };