问题描述
我正在为我的应用程序使用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}\])|(([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: ``,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
};