Skip to content

Instantly share code, notes, and snippets.

@rabeehebrahim
Last active October 28, 2022 06:10
Show Gist options
  • Save rabeehebrahim/489355fed5b2dc8c1bf0cee16bbfa127 to your computer and use it in GitHub Desktop.
Save rabeehebrahim/489355fed5b2dc8c1bf0cee16bbfa127 to your computer and use it in GitHub Desktop.
React Input Field Validation: if the value is empty in the form and user click submit, then show 'Name must not be empty' else show nothing.
import react, {useRef, useState} from "react";
const SimpleInput = (props) => {
const [enteredName, setEnteredName] = useState('')
const [enteredNameIsValid, setEnteredNameIsValid] = useState(true)
const nameInputChangeHandler = event => {
setEnteredName(event.target.value)
}
const formSubmissionHandler = event => {
event.preventDefault();
if(enteredName.trim() == ''){
setEnteredNameIsValid(false)
return;
}
setEnteredNameIsValid(true)
setEnteredName('')
}
return (
<form onSubmit={formSubmissionHandler}>
<div className='form-control'>
<label htmlFor='name'>Your Name</label>
<input type='text' id='name' onChange={nameInputChangeHandler} value={enteredName} />
{!enteredNameIsValid && <p style={{color: 'red', fontSize: '10px'}}>Name must not be empty</p>}
</div>
<div className="form-actions">
<button>Submit</button>
</div>
</form>
);
};
export default SimpleInput;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment