In this mini deposit app I need to validate the input field for 3 different things. With error message that states "Can not be blank", "only numerical values", and "no negative numbers". I have the functionality but tried to implement validation and failed. This is the code without any validation.
function Deposit(){
const ctx = React.useContext(UserContext);
const [totalState, setTotalState] = React.useState(0);
let transactionState = 0; // state of this transaction
let status = `Current Balance $ ${totalState}`;
console.log("Render Account");
const handleChange = event => {
console.log(`handleChange ${event.target.value}`);
transactionState = Number(event.target.value);
};
const handleSubmit = (event) => {
setTotalState(totalState transactionState);
event.preventDefault();
};
const ATMDeposit = ({ onChange }) => {
return (
<label className="label huge">
Deposit Amount:
<input type="number" onChange={onChange}></input>
<input type="submit" className="btn btn-light" value="Deposit"></input>
</label>
);
};
return (
<Card
bgcolor="primary"
header="Deposit"
body={(
<>
<form onSubmit={handleSubmit}>
<h3>{status}</h3>
<ATMDeposit onChange={handleChange}> Deposit</ATMDeposit>
</form>
</>
)}
/>
)
}
I have implemented the validation code suggested, greatly appreciated, and now validation works! I only need to figure out why the functionality isn't working. The value gets taken from handleChange but it does not add it to setTotalState. I tried adding Number constructor in handleChange like I originally had but it did not work. This is what I have now.
function Deposit(){
const [show, setShow] = React.useState(true);
const [errors, setErrors] = React.useState([]);
const [num, setNum] = React.useState('');
const [totalState, setTotalState] = React.useState(0);
const ctx = React.useContext(UserContext);
let transactionState = 0; // state of this transaction
let status = `Current Balance $ ${totalState}`;
console.log("Render Account");
function validate(value){
const errorsList = [];
if (!value.trim()){
errorsList.push('Error: Cannot be empty');
}
if (/^[-0-9]*$/.test(value) === false){
errorsList.push('Error: only numbers');
}
if (/^[-0-9]*$/.test(value) === true && value < 0) {
errorsList.push('Error: negative values not allowed');
}
if (errorsList.length) {
setErrors(errorsList);
setTimeout(() => setErrors(''),3000)
return false;
}
return true;
}
const handleSubmit = () => {
if (!validate(num)){
setShow(false);
}
if (validate(num)) {
setTotalState(totalState transactionState);
event.preventDefault;
}
}
const handleChange = event => {
console.log(`handleChange ${event.target.value}`);
transactionState = setNum(event.target.value);
}
return(
<Card
bgcolor="primary"
header= "Make deposit"
status={errors}
body={(
<>
<h3>{status}</h3>
Deposit Amount<br/>
<input type="input" className="form-control" id="num" value={num} onChange={handleChange}></input><br/>
<button type="submit" className="btn btn-light" onClick={handleSubmit}>Deposit</button>
</>
)}
/>
)
}
CodePudding user response:
I would change errors to array
const [errors, setErrors] = React.useState([]);
and here is validation function
function validate(value){
const errorsList = [];
if (!value.trim()){
errorsList.push('Error: Cannot be empty');
}
if (/^[-0-9]*$/.test(value) === false){
errorsList.push('Error: only numbers');
}
if (/^[-0-9]*$/.test(value) === true && value < 0) {
errorsList.push('Error: negative values not allowed');
}
if (errorsList.length) {
setErrors(errorsList);
setTimeout(() => setError(''),3000)
return false;
}
return true;
}
validate("1!") // false
validate("123") // true
Hope this will help