我正在为我的应用程序使用React typescript。我创建了一个全局输入组件,可以在其中导入到任何组件。我用CCD_ 1&password
验证。对于电子邮件验证,我使用了Regex,它运行良好。我的密码和确认密码验证工作正常。现在我决定,如果用户输入的字符少于8个,我会发现错误。为此,我使用了Regex。这种逻辑也很好用。当用户键入密码时,我想在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
};