You can apply the required
attribute to your inputs. When one of the inputs in a form has this attribute but has not been filled at the moment the Submit button is clicked, the form will not be submitted. Instead, the invalid
event will be fired on all inputs whose values are missing. You can use it to let the user know what needs to be filled in.
Here is a minimal example using React:
const { useState } = React;
function Input(props) {
const [invalid, setInvalid] = useState(false);
const handleInvalid = event => {
event.preventDefault();
console.log('Invalid');
setInvalid(true);
};
const handleChange = () => setInvalid(false);
const className = invalid ? 'invalid' : '';
return (
<div className={className}>
<input {...props} onInvalid={handleInvalid} onChange={handleChange} />
{props.type === "checkbox" && (
<label htmlFor={props.id}>
{props.label}
</label>
)}
</div>
);
}
function Form() {
const handleSubmit = event => {
event.preventDefault();
console.log('Submit');
};
return (
<form onSubmit={handleSubmit}>
<Input name="name" placeholder="Name" required />
<Input type="checkbox" name="accept" id="accept" label="I accept Terms of Usage" required />
<button>Submit</button>
</form>
);
}
ReactDOM.render(<Form />, document.getElementById('root'));
.invalid input[type=text], .invalid input:not([type]) {
border: 2px solid red;
}
.invalid label {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root"></div>
You can read more about client-side form validation here. Spoiler: requiring a field is not the only thing you can do by just using HTML attributes.