I need to validate the fields below, users can enter 0, but not in both fields, and neither one of the fields can be empty.
I am trying to do this:
if((document.getElementById("NumberOfOpenings").value.trim() == "" || document.getElementById("NumberOfOpenings").value.trim() == 0) && (document.getElementById("NumberOfEntrances").value.trim() == "" || document.getElementById("NumberOfEntrances").value.trim() == 0)) {
// instruct user to only enter 0 in one but not both fields, and make sure field is not left black.
} else {
// carry on
}
}
Could I get some basic help on this question? Does the code look correct?
Thank you
5
Answers
Modified version of code that should fix your issues:
First of all, make the code easier to read by copying the values into variables so you don’t have to keep writing the verbose calls to
getElementById()
.Then you can combine the 3 conditions.
Try storing the id´s on variables and using else if
This question seems to me more like a approach problem rather than JS help. So, Here is a simple easy to understand code (pseudo code almost) where there is a error thrown based on the values entered or not.
You could add in some custom form validation logic.
Here is an example of a form where either field may be submitted. Since I made the
<input>
element a[type="number"]
input, empty values are not allowed.