I am working on a simple customer intake form, and as part of the validation I need to make sure that a proper zipcode has been included. I know regex would be the easiest way to solve this issue, but regex doesn’t work when the input type is number. I HAVE to have the input type as number for this project. I’ve found some articles talking about making a custom validator component, but they all look so compliated. I just need my error code to pop up if it has under 5 digits or over 5 digits.
Thank you for all the help.
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;
2
Answers
You can do that by using React hook form.
If you prefer to stay with React Base. try this. You can change the regex pattern as you want (zipcodeRegex). also styles.
you can find regex in here. regex for zip-code
hope this will help