I have an html form that resembles the following code. My problem is I want to validate based on multiple criteria... a number can either be 0 OR it must be greater than 700. I'm using an array for the input names which is making it tough for me to get a javascript solution working. How would one go about validating in this case with the multiple critera?
<form name="endingweights" method="post">
<input type="hidden" value="1" name="strain[]"></td><td><input type="number" step="any" name="ending[]" min="0" max="1500" required />
<input type="hidden" value="2" name="strain[]"></td><td><input type="number" step="any" name="ending[]" min="0" max="1500" required />
<input type="hidden" value="3" name="strain[]"></td><td><input type="number" step="any" name="ending[]" min="0" max="1500" required />
Got it to validate with the following javascript function.
<script>
function validateForm() {
var x = document.forms["endingweights"].elements["ending[]"];
for (var i = 0; i < x.length; i++) {
var aControl = x[i].value;
if (aControl>0 && aControl<700) {
alert("Incorrect Weight, must be 0 or greater than 700.");
x[i].focus();
return false;
}
}}
</script>
If you assign id
to your inputs, you'll be able to validate via javascript easier. That way you can check the value of the input when the form is submitted.
HTML:
<form name="endingweights" method="post">
<!-- hidden inputs -->
<input id="foo" type="number" min="0" max="1500" required>
<input id="bar" type="number" min="0" max="1500" required>
<input id="baz" type="number" min="0" max="1500" required>
<input type="submit" value="Submit">
</form>
JS:
var form = document.forms['endingweights'],
foo = document.getElementById('foo'),
bar = document.getElementById('bar'),
baz = document.getElementById('baz');
// validate inputs and form
form.addEventListener('submit', function(ev) {
// stop this from auto submitting
ev.preventDefault();
ev.stopPropagation();
// make sure constraints are followed
if ((foo.value !== 0 && foo.value <= 700) ||
(bar.value !== 0 && bar.value <= 700) ||
(baz.value !== 0 && baz.value <= 700))
{
alert("All input values must be either 0 or greater than 700");
return false;
}
// perform other validations if necessary
// submit form
form.submit();
}, false);
A demo jsfiddle !
The name
attribute is most useful on the server side when handling the submitted data, but id
works best when dealing with client-side validation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.