Sometimes, we want to check if an input field is required using JavaScript.
In this article, we’ll look at how to check if an input field is required using JavaScript.
Check if an Input Field is Required Using JavaScript
To check if an input field is required using JavaScript, we can check if the required
attribute of each input field is set.
For instance, if we have:
<form id="register">
<label>Nickname:</label>
<input type="text" name="name" required="" />
<br>
<label>Email:</label>
<input type="email" name="email" required="" />
<br>
<label>Password:</label>
<input type="password" name="password" required="" />
<br>
<label>Again:</label>
<input type="password" name="password-test" required="" />
<br>
<input type="submit" value="Register" />
</form>
Then we write:
$('form#register').find('input').each(function() {
if (!$(this).prop('required')) {
console.log("not required");
} else {
console.log("required");
}
});
We have a form that has a few input elements.
Then we get all the input elements in the form with $('form#register').find('input')
.
Next, we call each
with a callback that gets the value of the required
attribute with:
$(this).prop('required')
And we negate that to check if a field isn’t required.
If the required
attribute isn’t present, then we log 'not required'
.
Otherwise, we log 'required'
.
Conclusion
To check if an input field is required using JavaScript, we can check if the required
attribute of each input field is set.