Reputation: 27
I build form validation with the code below. It`s work but If some of required field is filled var msg contains undefinied value.
For example if username is filled but password not var msg contains 'undefinied' Field is requred
How to avoid that ?
Here is the code:
var i = 0;
var error_msg = [];
var msg = ;
var errors = {
'username' : 'Field is required',
'password' : 'Field is requred',
'city' : 'City is required'
etc...... etc...
};
for(var x in errors) {
i++;
if(!$('#'+x).val()) {
error_msg[i] = errors[x];
}
}
if(error_msg.length > 0) {
for(var x = 0; x < errors_msg.length; x++) {
msg += errors_msg[x] +"\n";
}
}
Upvotes: 0
Views: 473
Reputation: 4698
One thing I see is:
var msg = ;
Should(could) be
var msg = "";
Did you also try to:
alert($('#'+x).length);
To see if jQuery finds the element? (if it returns 0, then its not found)
Upvotes: 4
Reputation: 46745
OK, besides the obviously broken for in
loop and the missing assignment of msg
.
This is your actual problem:
var error_msg = []; // new empty array
for(var x in errors) {
i++; // i starts with 1 this way!
// other code
}
So you're never setting the 0
th index. Yes arrays start with index 0
. So if you set an index that's bigger then the current length of the array, JavaScript will insert the missing elements before that index.
In your case, JavaScript will insert the default undefined
at index 0
since the first index you set is 1
.
Fixing
var error_msg = [];
for(var x in errors) {
if (errors.hasOwnProperty(x)) { // see note below
if(!$('#'+x).val()) {
error_msg.push(errors[x]); // append to the array
}
}
}
var msg = error_msg.join('\n'); // no need for an if, will be empty if there are no errors.
Note: See hasOwnProperty
Upvotes: 2
Reputation: 413737
This is not your problem, and so this is not really an answer, but comments don't support code very well:
if(error_msg.length > 0) {
for(var x = 0; x < errors_msg.length; x++) {
msg += errors_msg[x] +"\n";
}
}
For future reference, you never need to write that code:
msg = errors_msg.join('\n');
does the same thing.
Upvotes: 0