Reputation: 3407
I have this array of object:
[Object, Object]
0: Object
{
date: ""
number: undefined
}
1: Object
{
date: ""
number: undefined
}
It always said required if that value is not empty. Maybe someone can help me with much more knowledgeable about this.
Here's my code:
$(function(){
var len = $('#groupContainer > div').length;
var arr = [];
for(var i=0; i < len; i++){
var number = $('#number_' + [i + 1]);
var date = $('#date_' + [i + 1]);
console.log(number)
var a = number.map(function(){
return this.value;
});
var b = date.map(function(){
return this.value;
});
var newObj = {number: a[0], date: b[0]}
arr.push(newObj);
}
for(var c = 0; c < arr.length; c++)
{
var count = c + 1;
var message ="";
for(var d in arr[c])
{
if(arr[c].hasOwnProperty(d))
{
if(arr[c][d] == "")
{
message = d + ' is required!';
}
message += message + "\n";
}
}
alert('Group: ' + count + ' ' + message + '\n');
}
});
Upvotes: 1
Views: 58
Reputation: 123553
The check on emptiness appears to work correctly. Both fields in "Group 1" have a value and its message doesn't mention either as "required."
Though, you have an issue with how the message
is being built, reporting a single property at least twice:
"Group: 2 date is required!date is required!"
This is due to these modifications of message
:
if(arr[c][d] == "")
{
message = d + ' is required!';
}
message += message + "\n";
The first line modifying the message
, by using the assignment operator (=
), will discard any previous value that message
may have held.
var message = "something previous"
message = 'property' + ' is required!';
console.log(message); // "property is required!"
The other line then duplicates the contents of message
, appending it to itself:
// same as `message = message + message + "\n";`
message += message + "\n";
console.log(message); // "property is required!property is required!\n"
How you could revise this is to modify message
only when an empty field is found and concatenate onto the previous value with what's being added.
if(arr[c][d] == "")
{
message += d + ' is required!\n';
// ^ concatenate onto the previous `message` value
// including the `\n` here
}
// remove the other modification
Upvotes: 1
Reputation: 34237
From what i understand after our small comment dialog, you should implement a custom validation like the one in the following function
function isObjectNullOrEmpty(obj) {
if (!obj) {
return true;
}
var requiredKeys = ['name'];
for (var i in requiredKeys) {
var key = requiredKeys[i];
var value = obj[key];
if (value === undefined || value === null) {
return true;
}
if ((typeof value === 'string' || value instanceof String) && !value.trim()) {
return true
}
}
return false;
}
$(function () {
var object1 = {
name: ''
};
alert(JSON.stringify(object1) + ' \n\nresult : ' + isObjectNullOrEmpty(object1));
var object2 = {
name: 'asd'
};
alert(JSON.stringify(object2) + ' \n\nresult : ' + isObjectNullOrEmpty(object2));
});
Upvotes: 1