0

This is the first time I've tried to do data validation with Javascript and jQuery.

My array with errors is getting filled fine, but my problem is checking if this array is empty. In my situation it's always true. It will always alert me "errors leeg", even if the array is empty, checked with console.log(error):

<script type="text/javascript">
$(document).ready(function () 
{
    var error = [];
    $('#contactformulier').submit(function() {

      if($('input#namet').val().length == 0) {
          error['naam'] = 'Geen geldige naam ingevuld';
      } else{
          delete error['naam'];
      }

      if($('input#mailt').val().length == 0){
          error['mail'] = 'Geen geldig e-mailadres ingevuld';
      } else{
          delete error['mail'];
      }

      if($('textarea#message').val().length == 0){
          error['bericht'] = 'Geen geldig bericht ingevuld';
      } else{
          delete error['bericht'];
      }

      console.log(error);
      if (error.length < 1) {
        alert('errors leeg');
      }

      return false;
    });
});
</script>

Any suggestions?

5
  • 2
    You never add anything to the array. error['naam'] assigns a property on the array object, it does not put any elements in the array. Commented Apr 16, 2013 at 14:41
  • Lol, indeed I failed hard in this situation... wow! Commented Apr 16, 2013 at 14:43
  • @Chad And what does error[0] = "foo"; do? It adds a property to the array with the key "1" and value "foo". Arrays are Objects. Only when using numbers as the key does it affect the length property. Commented Apr 16, 2013 at 14:47
  • @Ian correct, was I not clear about how I said that? Commented Apr 16, 2013 at 14:55
  • Well, saying "it does not put any elements in the array" is weird to me. It just means it doesn't affect the length property and therefore a regular for loop can't be used as well. But the elements are still "in" the array, you just have to access it in a different way. I think it's obvious things were mixed up in the OP Commented Apr 16, 2013 at 14:57

5 Answers 5

5

You can only use numeric indices for arrays - at least if you want to use array functionality such as Array#length.

i.e.

var error = [];
error.push({ naam: "geen geldige naam" });
error.push({ mail: "geen geldige email" });
error.length == 2
Sign up to request clarification or add additional context in comments.

2 Comments

"at least if you want to use array functionality such as Array#length" - that's the important part :)
Thanks for your answer, with some explanation from the other answers I'll accomplished the result I wanted. Thanks guys!
1

That's because you're adding properties to your array instead of indexed items.

You can add items to an array using push():

error.push('Geen geldig bericht ingevuld');

And before you start validating, you clear the array:

error.length = 0;
// start validation logic

1 Comment

+1 for error.length = 0;. Exactly my thought. This way he will not have to use delete
0

The problem is that you mix up JavaScript types. What you think is an associative array, in JavaScript is an object with properties and methods.

So you need to define it with:

var error = {};

If a simple array emptiness can be checked with arr.length > 0, object "emptiness" (i.e. absence of properties/methods) can be checked with jQuery method $.isEmptyObject():

if ( $.isEmptyObject(error) ) { ... }

REF: https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects

Comments

0
<script type="text/javascript">
$(document).ready(function () 
{
    var error;
    var inError;
    $('#contactformulier').submit(function() {

      error = {};
      inError = false;

      if($('input#namet').val().length == 0) {
          error['naam'] = 'Geen geldige naam ingevuld';
          inError = true;
      }

      if($('input#mailt').val().length == 0){
          error['mail'] = 'Geen geldig e-mailadres ingevuld';
          inError = true;
      }

      if($('textarea#message').val().length == 0){
          error['bericht'] = 'Geen geldig bericht ingevuld';
          inError = true;
      }

      console.log(error);
      if (inError) {
        alert('errors leeg');
      }

      return false;
    });
});
</script>

Comments

0

As others have said, you can't take the length of an Object being used as an associative array, the .length property is for real arrays.

What you can do though, is ask how many keys there are:

var n = Object.keys(error).length;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.