反应密码验证 onChange

Posted

技术标签:

【中文标题】反应密码验证 onChange【英文标题】:React password validation onChange 【发布时间】:2021-01-11 17:51:23 【问题描述】:

我正在为我的应用程序使用 React-typescript。我创建了一个全局输入组件,我可以在其中导入任何组件。我创建了一个带有emailpassword 验证的表单。对于电子邮件验证,我使用了 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>
  );

【问题讨论】:

【参考方案1】:

您可以检查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
  ;

【讨论】:

我输入时它不显示:( 我希望当用户开始输入时它会显示password is too short,你明白我的意思吗:D。不是在提交后 另外,你的逻辑不起作用,如果我输入超过 8 个字符仍然会抛出错误 你检查正确了吗? -> codesandbox.io/s/email-validation-forked-fhkdk?file=/src/… 只是遇到了奇怪的问题,即使我发现了错误,但如果确认密码相同,我仍然可以提交表单

以上是关于反应密码验证 onChange的主要内容,如果未能解决你的问题,请参考以下文章

密码和确认密码字段验证 angular2 反应形式

反应采取错误验证的多步骤形式

在反应中,我如何强制浏览器要求保存密码? [复制]

使用 ReactJS 实现忘记密码/电子邮件验证 django rest

客户端的客户端密码验证失败,授权代码流中的客户端密码无效

Django 表单:无法显示验证错误