I have a form and unfortunately built it without the help of external libraries (which I am now cursing myself for not including). So my form validation isn't just form.validate() or something similar, it's going to have to be an archaic javascript method (time constraints means I cannot implement external libraries because it'd involve rebuilding the form).
All I want is to check all the fields have been filled in - no email validation or post-code validation etc.
I tried a simple version:
if((document.getElementById("fieldA").value != "") || (document.getElementById("fieldB").value != "")){
alert("form okay");
}else{
alert("form not okay");
}
but this doesn't work. The alternative to this would be to ne开发者_如何学Cst 45 if statements detecting each field individually but this is tedious and unfeasible.
you can loop trough elements in the form with
document.forms[0].elements
like
var d = document.forms[0].elements
var l = d.length;
for(var i = 0; i < l; i ++) {
var element = d[i];
var type = element.type;
var value = element.value;
var class = element.className;
}
dropdown:
document.forms[0].select.value
radiobuttons:
for (i=0;i<document.forms[0].radios.length;i++) {
if (document.forms[0].radios[i].checked) {
var value = document.forms[0].radios[i].value;
}
}
thanks to external libraries we don't need that to do ourselves these days;)
Your boolean logic is wrong - you want AND (&&
) not OR (||
) if you want to make all the fields required. As it stands, the validation only checks to see if one field has been filled in.
I think that Caspar's answer is excellent. As an addition to it, what we have on old forms is a function to get elements by class name (not written by us):
function getElementsByClassName(className, tag, elm){
var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
var tag = tag || "*";
var elm = elm || document;
var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
var returnElements = [];
var current;
var length = elements.length;
for(var i=0; i<length; i++){
current = elements[i];
if(testClass.test(current.className)){
returnElements.push(current);
}
}
return returnElements;
}
Then we put a class="validate" on each form element that needs validating and have this function run on form submit (where getFormElementValue is a function that handles the various different form elements as in Caspar's answer):
function validate(){
var elementArray = ( getElementsByClassName('validate') ) ;
for ( i=0; i<elementArray.length; i++){
if( getFormElementValue( elementArray[i] ) == '' ){
alert( 'Form not OK' );
return false;
}
}
}
The nice thing about this is that you can easily define which elements are compulsory and which are not without resorting to a list of names/IDs.
精彩评论