1

I'm trying to validate a form using javascript. Checking to see if the input value matches any value within an array before returning true.

Here's an example of what I have written so far. Yet this seems to not work.

<script type='text/javascript'>

function checkForm() 
{ 

var agent = document.getElementById('agent').value;

var myArray = new Array() 
  myArray[0] = 'First Agent';
  myArray[1] = 'Second Agent';
  myArray[2] = 'Third Agent';

if (agent != myArray) 
{
  alert("Invalid Agent");
  return false;
} 

else 
{
  return true;
}
}

<form>
<fieldset>
Agents Name*
<input type="text" size="20" name="agent" id="agent">
</fieldset>
</form>
Pero P.
  • 25,813
  • 9
  • 61
  • 85
user2433761
  • 11
  • 1
  • 1
  • 2
  • I'd recommend using the jQuery Validate https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&ved=0CDEQFjAA&url=http%3A%2F%2Fjqueryvalidation.org%2Fvalidate%2F&ei=lU2mUfD-JpK88wSjjoGQCw&usg=AFQjCNE43XLONaPQUHt0-BNtFoJG-FSa3Q&sig2=Rtm-Oa3AUbwRYDiWfwtyWA&bvm=bv.47008514,d.eWU plugin. I had a huge form that I needed to validate and this plugin made it quite easy to manage. – ckpepper02 May 29 '13 at 18:51

4 Answers4

3

You need to make a for structure to pass your entire array, when value matches you return true, otherwise return false. Something like this:

for (var i = 0; i < myArray.length; i++) {
    if (agent == myArray[i])
        return true;
}
return false;
Wellington Zanelli
  • 1,894
  • 3
  • 18
  • 43
0
function checkForm() {
    var agent = document.getElementById('agent').value;
    var myArray = ['First Agent', 'Second Agent', 'Third Agent'];
    if(myArray.indexOf(agent) == -1) //returns the index of the selected element 
    {
        alert("Invalid Agent");
        return false; // if you return false then you don't have to write the else statement
    }
    return true;
}
Niccolò Campolungo
  • 11,824
  • 4
  • 32
  • 39
-1

"agent != myArray" compares your string with an array, not with its contents. Look at this post: Determine whether an array contains a value

Community
  • 1
  • 1
lasote
  • 591
  • 2
  • 12
-2

With Underscore/lodash you could do:

if (_.indexOf(myArray,agent) == -1) 
{ 
   //alert invalid agent    
   ...
}
Jafin
  • 4,153
  • 1
  • 40
  • 52