I wrote a javascript function to validate that the user input data is not empty. The function called “isNotEmpty()” identifies that the text box is empty. But however the main function returns a true statement to the JSP page. Thus the form gets submitted.
The alert no 2&3 fires according the input from the form. but the Alert No1 dose not fires in any circumstances.
Please check on this and assist me.
Thank you.
var firstName;
var data = new Array();
function formEntryValidationTest() {
firstName = document.forms["regForm"]["firstName"];
data[0] = isNotEmpty(firstName);//check the first name is empty
for(var i=0;i<data.length;i++) {
if(data[i]=="false")
{
alert("Check"); //alert No-1
return false;
}
}
}
// this is the function to check whether the input is not empty
function isNotEmpty(obj) {
if(obj.value!="") {
alert("true"); //alert No-2
return "true";
}
else
{
alert("false");//alert No-3
return "false";
}
}
You’re returning the string
"false"rather than the boolean valuefalse, which in JavaScript evaluates to a “truthy” value.Change the return statements in
isNotEmptytoreturn true;andreturn false;and the condition informEntryValidationTesttoif (!data[i]).Also, the condition you check in
isNotEmptyis too strict. It will return true forundefinedandnull, which may be the reason your code isn’t working. Change it to something like this:Then pass the input value directly rather than passing the input object itself: