簡體   English   中英

響應密碼驗證 onChange

[英]React password validation onChange

我正在為我的應用程序使用 React-typescript。 我創建了一個全局輸入組件,我可以在其中導入任何組件。 我創建了一個帶有emailpassword驗證的表單。 對於電子郵件驗證,我使用了 Regex,它工作正常。 我的密碼和確認密碼驗證工作正常。 現在我決定如果用戶輸入少於 8 個字符,我會發現錯誤。 為此,我使用了正則表達式。 這個邏輯也很好用。 我想在用戶輸入時在 handleChange 函數中顯示密碼長度,直到他們輸入的字符不超過 8 個我才會顯示錯誤。 提交表單后,它將顯示兩個輸入字段密碼不匹配。 但是當我可以在句柄更改中添加錯誤時,我找不到邏輯。 我在codeandbox 中分享我的代碼。

這是我的表單驗證代碼

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM