javascript validation with an array

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";
    }
}

Answers


You're returning the string "false" rather than the boolean value false, which in JavaScript evaluates to a "truthy" value.

Change the return statements in isNotEmpty to return true; and return false; and the condition in formEntryValidationTest to if (!data[i]).

Also, the condition you check in isNotEmpty is too strict. It will return true for undefined and null, which may be the reason your code isn't working. Change it to something like this:

function isNotEmpty(value){
  return value ? value.length > 0 : false;
}

Then pass the input value directly rather than passing the input object itself:

data[0] = isNotEmpty(firstName.value);

Need Your Help

SDL error LNK1120 & LNK2019

c++ visual-studio sdl-2 lnk2019

I'm trying to compile a simple SDL example from a book and I'm getting these errors. I'm near positive everything is linked correctly, because I was able to get other SDL examples to compile fine. ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.