,可以通过以下几种方式实现:
required
属性可以标记输入字段为必填项。例如:<input type="text" required />
import { useFormik } from 'formik';
const MyForm = () => {
const formik = useFormik({
initialValues: {
name: '',
email: '',
},
validationSchema: Yup.object({
name: Yup.string().required('Name is required'),
email: Yup.string().email('Invalid email').required('Email is required'),
}),
onSubmit: values => {
// 处理表单提交
},
});
return (
<form onSubmit={formik.handleSubmit}>
<input
type="text"
name="name"
value={formik.values.name}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
/>
{formik.touched.name && formik.errors.name ? (
<div>{formik.errors.name}</div>
) : null}
<input
type="email"
name="email"
value={formik.values.email}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
/>
{formik.touched.email && formik.errors.email ? (
<div>{formik.errors.email}</div>
) : null}
<button type="submit">Submit</button>
</form>
);
};
import React, { useState } from 'react';
const MyForm = () => {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [nameError, setNameError] = useState('');
const [emailError, setEmailError] = useState('');
const handleSubmit = e => {
e.preventDefault();
// 检查必填条件
if (name === '') {
setNameError('Name is required');
} else {
setNameError('');
}
if (email === '') {
setEmailError('Email is required');
} else {
setEmailError('');
}
// 处理表单提交
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={name}
onChange={e => setName(e.target.value)}
/>
{nameError && <div>{nameError}</div>}
<input
type="email"
value={email}
onChange={e => setEmail(e.target.value)}
/>
{emailError && <div>{emailError}</div>}
<button type="submit">Submit</button>
</form>
);
};
以上是在React.js表单中进行必需的输入的几种实现方式。根据具体的需求和项目情况,你可以选择适合的方式来实现表单验证。
领取专属 10元无门槛券
手把手带您无忧上云