admin管理员组

文章数量:1327665

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?

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?

Share Improve this question edited Apr 16, 2013 at 14:44 LeonardChallis 7,7836 gold badges47 silver badges79 bronze badges asked Apr 16, 2013 at 14:39 user443346user443346 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. – Chad Commented Apr 16, 2013 at 14:41
  • Lol, indeed I failed hard in this situation... wow! – user443346 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. – Ian Commented Apr 16, 2013 at 14:47
  • @Ian correct, was I not clear about how I said that? – Chad 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 – Ian Commented Apr 16, 2013 at 14:57
Add a ment  | 

5 Answers 5

Reset to default 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

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

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/en-US/docs/JavaScript/Guide/Working_with_Objects

<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>

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;

本文标签: jqueryCheck array length javascriptStack Overflow