I am new to ReactJS Hooks. I searched out for a clear controlled form validation example but didn't get one. So I decided to write a simple question that anyone can easily understand it.
Assume I have a two input fields, type number and type text
const [values, set_values] = useState({first_input:'',second_input:''});
const handle_change = (e) => {
let name = e.target.name
let value = e.target.value;
values[name] = value;
set_values(values);
}
const test_validation () => {
// I used to do it this way
if(document.getElementsByName('first_input')[0].value==''){
alert("first input is required")
}
}
return(
<div>
<input onChange={handle_change} name='first_input' type='number' />
<input onChange={handle_change} name='second_input' type='text' />
<input type='submit' onClick={test_validation} />
<div/>
)
Is it wrong to use pure JS to check the input's value and set conditions or is it preferred to use React validation forms?
I tried to set required attribute on input element tag so it can't be skipped but didn't work.
I need to alert() warning message for the required filed or highlight or focus on it.
document.getElementByIdis JS so it should work fine, although I can agree that part isn't a very good practice.