React Check if Input is Empty
React to validate user input and check if it is empty or not. In React, there are different ways to achieve this, depending on the type of input and the library you are using. In this article, we will explore some of the methods to check if an input is empty in React, such as using the trim() method, the length property, and the useForm hook. We will also see some examples of how to display error messages and disable buttons based on the input value




Thanks for your feedback!
Your contributions will help us to improve service.
How to Validate Empty Input Fields in React using React Hook Form
To check if an input field is empty in ReactJS, you can access the input's value using the value property and compare it with an empty string. If the value equals an empty string, it means the input field is empty.
This can be achieved by implementing a change event handler on the input field and checking the value inside the handler function. If the value is empty, you can perform the desired actions or validations accordingly.
React Js Check if Input Field is Empty Example
xxxxxxxxxx
<script type="text/babel">
const { useState } = React;
function App() {
const [inputValue, setInputValue] = useState('');
const handleInputChange = (event) => {
setInputValue(event.target.value);
};
const handleSubmit = (event) => {
event.preventDefault();
if (inputValue.trim() === '') {
// Input is empty
alert('Input is empty!');
return;
}
// Input is not empty
console.log('Input is not empty:', inputValue);
};
return (
<div className="container">
<h3>React Js Check if Input Field is Empty</h3>
<form onSubmit={handleSubmit}>
<input
type="text"
value={inputValue}
onChange={handleInputChange}
/>
<button type="submit">Submit</button>
</form>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>
Output of Empty Field Validation in React Js
How to Check Input Field is Empty or Not in Javascript?
Sometimes, we need to check if the input field is empty or not before performing any action. In this Example, we will learn how to check if input is empty in JavaScript using different methods.
Javascript Check if Input is Empty
xxxxxxxxxx
<script>
function checkInput() {
var userInput = document.getElementById('userInput').value;
var submitButton = document.getElementById('submitButton');
if (userInput.trim() === '') {
submitButton.disabled = true;
} else {
submitButton.disabled = false;
}
}
function submitForm() {
alert('Form submitted!');
// Add your form submission logic here
}
</script>