I am trying to validate an onchange but can't seem to get it working.
Essentially, I want to test that if the input matches the regex then we present a message under the input.
I am unsure where to put the validator, I wondered if anyone could point me in the right direction
Here is a sandbox.
https://codesandbox.io/s/blazing-hooks-gni5jy?file=/src/components/Dashboard/Dashboard.js
const Dashboard = () => {
const [number, setNumber] = useState(null);
// const [isValid, setIsValid] = useState(false);
// const validator = (value) => {
// if (!value) return false;
// const re = /\b\d{5}\b/g;
// return re.test(value.trim());
// };
const onChangeHandler = (event) => {
const value = event.target.value;
setNumber(value);
};
return (
<div>
<input value={number || ""} onChange={onChangeHandler} />
{/* {isValid ? <p>is valid</p> : null} */}
</div>
);
};
export default Dashboard;
CodePudding user response:
Set the state inside the validator
const [isValid, setIsValid] = useState(true);
const validator = (value) => {
if (!value) return false;
const re = /\b\d{5}\b/g;
const valid = re.test(value);
setIsValid(valid);
};
const onChangeHandler = (event) => {
const value = event.target.value;
setNumber(value);
validator(value);
};
CodePudding user response:
You will have to call the validator for it to work.
import React, { useState } from "react";
const Dashboard = () => {
const [number, setNumber] = useState(null);
const [isValid, setIsValid] = useState(false);
const validator = (value) => {
if (!value) return false;
const re = /\b\d{5}\b/g;
return re.test(value.trim());
};
const onChangeHandler = (event) => {
const value = event.target.value;
setNumber(value);
setIsValid(validator(value)); // Validating the input
};
return (
<div>
<input value={number || ""} onChange={onChangeHandler} />
{isValid ? <p>is valid</p> : null}
</div>
);
};
export default Dashboard;