'Reactjs Form Validations-for input type number the text field in constantly showing single value even after giving backspace from the keyboard

Unable to Clear the value which is entering in the input field even after clicking backspace it is not clearing. one value is remaining constant in the input field

import * as React from "react";
import { Button, Form } from "react-bootstrap";
function Adminform() {
const [docId, setdocId] = React.useState("");
const errorHandle = (name, value) => {
const errors = {}
if (name === "docID") {
if (value === '') {
errors.docID = "Doctor ID Required"
}
else {
setdocId(value)
}
}
setError(errors)
}
return (
<div className="center">
<div className="select">
<h2>Register Your Appointment</h2>
<Form method="POST">
<div>
<label htmlFor="docID">Enter Hospital Name:</label>
<input required type="text" id="docID" name="docID"
onKeyPress={(event) => {
if (!/[0-9]/.test(event.key)) {
event.preventDefault();
}
}}
value={docId} onChange={(e) => errorHandle(e.target.name, e.target.value)}
placeholder="Doctor ID" />
<p style={{ color: "red" }}>{error.docID}</p>
</div>
</Form>
</div>
</div>
)
}
export default Adminform

Before Entering the values Entered the Random value Even after clicking backspace one value remaining constant in the text field



Solution 1:[1]

You are not completely handling the input value. Since you apply the check that if value === '', then just set the error. Just console the value in errorHandle function, you will see you will get the empty string, but since you are not setting the '' in state, it input value is not updated and remains the last value. You can do this:

const errorHandle = (name, value) => {
        setdocId(value);
        const errors = {};
        if (name === 'docID') {
            if (value === '') {
                // Set the error
            } else {
                setdocId(value);
            }
        }
    };

Don't add check for empty value. Just update the state. You can check if value is empty then set the error.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nouman Rafique