Kristy Murphy
Kristy Murphy

Reputation: 25

React form validation for Zipcode when input type is number

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;

Upvotes: 0

Views: 122

Answers (2)

Thushitha Prabuddha
Thushitha Prabuddha

Reputation: 26

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

import { useState } from 'react'

function App() {
  const [zipcode, setZipcode] = useState('');
  const [error, setError] = useState('');

  const validateZipcode = (value) => {
    const zipcodeRegex = /^\d{5}(?:[-\s]\d{4})?$/;
    if (!value) {
      return 'Zipcode is required';
    }
    if (!zipcodeRegex.test(value)) {
      return 'Please enter a valid zipcode (12345 or 12345-6789)';
    }
    return '';
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    const validationError = validateZipcode(zipcode);
    setError(validationError);
    
    if (!validationError) {
      console.log('Valid zipcode:', zipcode);
    }
  };

  const handleChange = (e) => {
    setZipcode(e.target.value);
  };

  const formStyle = {
    maxWidth: '300px',
    margin: '20px auto',
    padding: '20px'
  };

  const inputStyle = {
    width: '100%',
    padding: '8px',
    marginBottom: '10px',
    border: error ? '2px solid red' : '1px solid #ccc',
    borderRadius: '4px'
  };

  const errorStyle = {
    color: 'red',
    fontSize: '14px',
    marginBottom: '10px'
  };

  const buttonStyle = {
    width: '100%',
    padding: '10px',
    backgroundColor: '#007bff',
    color: 'white',
    border: 'none',
    borderRadius: '4px',
    cursor: 'pointer'
  };


  return (
    <>
    <form onSubmit={handleSubmit} style={formStyle}>
      <input
        type="text"
        value={zipcode}
        onChange={handleChange}
        placeholder="Enter zipcode"
        style={inputStyle}
      />
      {error && <div style={errorStyle}>{error}</div>}
      <button type="submit" style={buttonStyle}>
        Submit
      </button>
    </form>
)
}

Upvotes: 1

Thushitha Prabuddha
Thushitha Prabuddha

Reputation: 26

You can do that by using React hook form.

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>}
    )


}

Upvotes: 0

Related Questions