Javascript form validation - multiple form fields larger than 0
function negativeValues(){
var myTextField = document.getElementById('digit');
if(myTextField.value < 0)
{
alert("Unable to submit as one field has a negative value");
return false;
}
}
Above is a Javascript piece of code where every time a field id 'digit' has a value that's less than 0, than an alert box appears either onsubmit or onclick in the submit button.
There are about 50 fields in the form that should be considered 'digit' fields where they shouldn't be anything less than 开发者_运维百科0. What should I change with this Javascript to ensure that all 'digit' like fields have this alert box pop up?
I cannot use jquery/mootools for validation - it has to be flat Javascript.
Thanks.
var form = document.forms[0]; // first form in the document
form.onsubmit = function () {
for (var i=0; i<this.elements.length; i++)
if (Number(this.elements[i].value) < 0) {
alert("Unable to submit as one field has a negative value"); // complain
return false; // and prevent submission
}
}
Do not give ID="digit", ids need to be unique. Instead give a class="digit" or name="digit[]" which in PHP will give you an array on the server.
Here is a typical validation using forms access
function validate(theForm) {
var el = theForm.elements;
for (var i=0,n=el.length;i<n;i++) {
if (el[i].className=="digit" && parseInt(el[i].value,10)<0) {
alert('This field must contain a value > 0');
el[i].focus();
return false;
}
}
return true; // allow submission
}
assuming
<form onsubmit="return validate(this)">
Alternatives for the className== would be
if (el[i].className.indexOf('digit')!=-1
if the className could be manipulated from elsewhere.
You can use ID="digit1" ID="digit2" and
if (el[i].id.indexOf('digit')==0
精彩评论