【问题标题】:React Password submit validationReact 密码提交验证
【发布时间】:2023-03-30 01:35:02
【问题描述】:

我正在为我的应用程序使用 React 打字稿。对于造型,我使用了styled-components。我创建了一个全局输入组件,其中类型为textpassword。我做了几个表单验证。我的电子邮件验证和密码确认验证工作正常。当用户键入时,我已经进行了一次密码长度验证,然后它将显示 password is too small 作为错误,我的逻辑工作正常,但是当我单击少于 8 个字符的提交按钮时,它仍然能够接受表单。如果少于 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 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) => {
    let passwordError = "";

    if (e.target.id === "password" && password.length < 7) {
      passwordError = "Password is too short";
    }

    setFormState({
      ...formState,
      [e.target.id]: e.target.value,
      passwordLength: passwordError //In here it display the error
    });
  };

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

    if (
      !isPasswordValid(formState.password, formState.passwordConfirmation) ||
      !isEmailValid(formState.email)
    ) {
      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} //Password lenght error
      />
      <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}
      >
        {loading ? `loading...` : `save`}
      </button>

      {accountCreationSuccessful && !loading ? (
        <p>You have succefully create and account ????????</p>
      ) : null}
    </div>
  );
}

【问题讨论】:

  • 目前不检查密码长度。在isPasswordValid() 函数中,还要检查password 的长度,如果小于8,则返回false ----> if (password.length &lt; 8) return false;
  • 谢谢你的朋友,但我认为这不是正确的答案
  • 你为什么这么认为?据我了解您的代码,您仅在密码字段触发onChange 事件时检查密码的长度,但在提交表单时没有类似的检查。
  • 那我想它会一直显示Upps sorry Password did not match
  • 我假设你想要this is what

标签: reactjs validation passwords


【解决方案1】:

我在沙盒上浏览了您的代码。您可以添加一个额外的签入禁用。

App.tsx

  <button
        type="submit"
        name="action"
        onClick={onSubmit}
        disabled={!formState.email || formState.password.length < 8}
      >

【讨论】:

    猜你喜欢
    • 2014-01-24
    • 2014-02-12
    • 2018-10-30
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    • 2016-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多