how to validate dynamic row array values in javascript
pl. advise me how do i validate the array values in javascript. i am posting the code that i am currently using. the problem is that even after filling up all the values, i still keep getting the validation error message. pl. advise me where am i wrong
function chkdate() {
var x = docu开发者_高级运维ment.forms["main"]["date"].value;
if (x == null || x == "") {
document.forms["main"]["date"].focus();
document.forms["main"]["date"].style.background = 'red';
alert("Date Cannot be empty");
return false;
}
}
function chkempty() {
var len = document.forms["main"]["item[]"].length;
if (len == undefined) {
var ic = document.forms["main"]["item[]"].value;
var iq = document.forms["main"]["qty[]"].value;
var ip = document.forms["main"]["price[]"].value;
if (ic == null || ic == "") {
document.forms["main"]["item[]"].focus();
document.forms["main"]["item[]"].style.background = 'red';
alert("Item Cannot be empty");
return false;
}
if (iq == null || iq == "") {
document.forms["main"]["qty[]"].focus();
document.forms["main"]["qty[]"].style.background = 'red';
alert("Qty Cannot be empty");
return false;
}
if (ip == null || ip == "") {
document.forms["main"]["price[]"].focus();
document.forms["main"]["price[]"].style.background = 'red';
alert("Price Cannot be empty");
return false;
}
} else for (i = 0; i < len; i++) {
var ica = document.forms["main"]["item[]"][i].value;
var iqa = document.forms["main"]["qty[]"][i].value;
var ipa = document.forms["main"]["price[]"][i].value;
if (ica == null || ica == "") {
document.forms["main"]["item[]"][i].focus();
document.forms["main"]["item[]"][i].style.background = 'red';
alert("Item Cannot be empty");
return false;
}
if (iqa == null || iqa == "") {
document.forms["main"]["qty[]"][i].focus();
document.forms["main"]["qty[]"][i].style.background = 'red';
alert("Qty Cannot be empty");
return false;
}
if (ipa == null || ipa == "") {
document.forms["main"]["price[]"][i].focus();
document.forms["main"]["price[]"][i].style.background = 'red';
alert("Price Cannot be empty");
return false;
}
}
}
other details are:-
form name: main the input boxes item,qty and price are dynamic rows based on user's requirement. thanks all.
I suggest you as first point to use JQuery in conjunction with validate plugin.
Then for your case follow this example that works fine for me:
$("#testform").validate({
rules: {'qty[]': {required: true,minlength: 1},
//other rules here
},
messages: {
'qty[]': "Select at least one qty",
//other custom error msgs go here
}
});
<input name="qty[]" id="1" value="1" type="checkbox" />
<input name="qty[]" id="2" value="2" type="checkbox" />
<input name="qty[]" id="3" value="3" type="checkbox" />
N.B. that the name of the field of array values must be specified with quotes ('qty[]') or else you'll get a js error.
精彩评论