Search code examples
reactjsbootstrap-4react-bootstrap

Validation is not working for these and unable to write something in the forum


I am using this form from the react bootstrap. But when i am trying to validate it is not working. Can some one please help here and thanks in adavance.

but when i am trying to validate the username, email and phone, I am unable to do it also unable to write something in the forum, can some one please help me where i made exact error

  import React, { useEffect, useState } from 'react'
import { Button, Col, Form, Row } from 'react-bootstrap';

const AddressValidation = () => {
  const initialValues = { username: "", email: "", password: "" };
  const [formValues, setFormValues] = useState(initialValues);
  const [formErrors, setFormErrors] = useState({});
  const [isSubmit, setIsSubmit] = useState(false);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormValues({ ...formValues, [name]: value });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    setFormErrors(validate(formValues));
    setIsSubmit(true);
  };

  useEffect(() => {
    console.log(formErrors);
    if (Object.keys(formErrors).length === 0 && isSubmit) {
      console.log(formValues);
    }
  }, [formErrors]);
  const validate = (values) => {
    const errors = {};
    const regex = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/i;
    if (!values.username) {
      errors.username = "Username is required!";
    }
    if (!values.email) {
      errors.email = "Email is required!";
    } else if (!regex.test(values.email)) {
      errors.email = "This is not a valid email format!";
    }
    if (!values.username) {
      errors.username= "usernameis required";
    } else if (values.username.length < 4) {
      errors.username= "username must be more than 4 characters and combination of 3 letters";
    } else if (values.username.length > 10) {
      errors.username= "username cannot exceed more than 10 characters";
    }
    return errors;
  };

  return (
    <div className="container">
     <pre>{JSON.stringify(formValues, undefined, 2)}</pre>
     <Form onSubmit = { handleSubmit }>
            <h1> Payment Validation  Form</h1>
            <Row className="mb-3">

                <Form.Group as={Col} controlId="formGridUsername">
                <Form.Label>User Name</Form.Label>
                <Form.Control type="text" placeholder="Enter User Name"  value={ formValues.username}
                    onChange = {handleChange}/>
                </Form.Group>

                <Form.Group as={Col} controlId="formGridEmail">
                <Form.Label>Email</Form.Label>
                <Form.Control type="email" placeholder="Enter email" value={ formValues.email} 
                     onChange = {handleChange} />
                </Form.Group>
               
             <Form.Group as={Col} controlId="formGridPhone">
                <Form.Label>phonenumber</Form.Label>
                <Form.Control type="number" placeholder="Enter email" value={ formValues.phonenumber} 
                     onChange = {handleChange} />
                </Form.Group>

                
            </Row>

            <Form.Group className="mb-3" controlId="formGridAddress1">
                <Form.Label>Address</Form.Label>
                <Form.Control placeholder="1234 Main St" />
            </Form.Group>

            <Form.Group className="mb-3" controlId="formGridAddress2">
                <Form.Label>Address 2</Form.Label>
                <Form.Control placeholder="Apartment, studio, or floor" />
            </Form.Group>

            <Row className="mb-3">
                <Form.Group as={Col} controlId="formGridCity">
                <Form.Label>City</Form.Label>
                <Form.Control />
                </Form.Group>

                <Form.Group as={Col} controlId="formGridState">
                <Form.Label>State</Form.Label>
                <Form.Select defaultValue="Choose...">
                    <option>Choose...</option>
                    <option>Stockholm</option>
                    <option>Mälmo</option>
                </Form.Select>
                </Form.Group>

                <Form.Group as={Col} controlId="formGridZip">
                <Form.Label>Zip</Form.Label>
                <Form.Control />
                </Form.Group>
            </Row>

            <Form.Group className="mb-3" id="formGridCheckbox">
                <Form.Check type="checkbox" label="Check me out" />
            </Form.Group>

            <Button variant="primary" type="submit">
                Submit
            </Button>
     </Form>
    </div>
  );
}

export default AddressValidation

Solution

  • You need to add the name property to your inputs. Otherweise you get an empty name property from event.target:

    <Form.Control
      name="username"
      type="text"
      placeholder="Enter User Name"
      value={formValues.username}
      onChange={handleChange}
    />
    

    Your validation seems to work. When I try to submit, I can read the error messages in console:

    {username: 'usernameis required', email: 'Email is required!'}