Home > Software engineering >  required attribute not working in react js form for validation
required attribute not working in react js form for validation

Time:11-27

required is not working. I have tried using required="required" or required={true}.

Can someone explain why or how to easily fix that?

import React, { useState } from 'react';

export const Login = () => {
const [username, setUsername] = useState("");

const handleSubmit = async (e) => {
    e.preventDefault();

    console.log("test")
}

return(
                <form className={styles["form-parent"]}>
                    {/* Title */}
                    <h1 className={styles["form-title"]}>Login</h1>

                    {/* Username */}
                    <div className={styles["form-input-group"]}>
                        <label> <b>Username:</b></label>
                        <input className={styles["form-input"]} type="text" name="username"
                            title="Enter your username in this field" required
                            value={username}
                            onChange={(e) => setUsername(e.target.value)}
                        />
                    </div>

                    {/* Login button */}
                    <div className={styles["form-input-group"]}>
                        <input className={styles["form-button"]} type="submit" value="Log In"
                            title="Click here to login"
                            onClick={(e) => handleSubmit(e)}
                        />
                    </div>

                </form>
);
}

I have been struggling on this for past 2 days now and internet has not been of much help.

CodePudding user response:

You should set form onSubmit event

add: <form onSubmit={(e) => handleSubmit(e)}>

instead of your button input onClick event

delete: onClick={(e) => handleSubmit(e)}

CodePudding user response:

It seems that this line:

onClick={(e) => handleSubmit(e)}

Can be as simple as:

onSubmit={handleSubmit}

Because the event object is passed to the call back function by default.

Here is an example over simplified from posted code, and runs in the below snippets for convenience.

Hopefully this will help by showing the validating status change in real time.

const Login = () => {
  const [username, setUsername] = React.useState("");
  const [message, setMessage] = React.useState("");

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!username) return;
    //            
  • Related