我正在制作一个简单的客户登记表,作为验证的一部分,我需要确保包含正确的邮政编码。我知道正则表达式是解决此问题的最简单方法,但当输入类型为数字时正则表达式不起作用。我必须将输入类型设置为该项目的数字。我发现了一些关于制作自定义验证器组件的文章,但它们看起来都很复杂。我只需要在错误代码少于 5 位或超过 5 位时弹出。 谢谢大家的帮助。
import React from 'react'
import { useState } from 'react'
import './App.css'
import './FormInput/FormInput'
import FormInput from './FormInput/FormInput'
function App() {
const [values, setValues] = useState({
name:"",
email:"",
zipcode:""
});
const inputs = [
{
id:1,
name:"name",
type:"text",
placeholder:"Name",
error: "Must be at least 3 characters",
label:"Name",
pattern: "^.{3,25}$",
required: true
},
{
id:2,
name:"email",
type:"email",
placeholder:"Email",
error:"Must be a valid Email",
label:"Email",
required: true
},
{
id:3,
name:"zipcode",
type:"number",
placeholder:"Zipcode",
error:"Must be a valid Zipcode",
label:"Zipcode",
pattern: "^[0-9]{5,5}$",
required: true
}
]
const handleSubmit = (e) => {
e.preventDefault();
}
const onChange = (e) => {
setValues({...values, [e.target.name]: e.target.value});
}
console.log(values);
return (
<div className='app'>
<h2>Customer Form</h2>
<form onSubmit={handleSubmit}>
{inputs.map((input) => (
<FormInput key={input.id} {...input}
value={values[input.name]}
onChange={onChange}/>
))}
<button>Submit</button>
</form>
</div>
)
}
export default App;
import "./formInput.css";
import { useState } from "react";
const FormInput = (props) => {
const {label, error, onChange, id, ...inputProps} = props;
const handleFocus = (e) => {
setFocused(true);
}
return (
<div className="formInput">
<label>{label}</label>
<input {...inputProps}
onChange={onChange}/>
<span>{error}</span>
</div>
)
}
export default FormInput;
您可以使用 React hook 表单来做到这一点。
import { Form} from "react-bootstrap";
import { useForm } from "react-hook-form";
function App() {
const{register,formState:{errors}} = useForm();
const validationRules = {
zipCode: {
pattern:{value:^[0-9]{5,5}$,message :"Must be a valid Zipcode",
},
}
return (
<Form.Group className="col mb-3">
<Form.Label>zipCode</Form.Label>
<Form.Control
type="text"
{...register("zipCode", validationRules.zipCode)}
/>
{errors.zipCode && <span className="text-danger">{errors.zipCode.message}</span>}
)
}