Validate empty object - javascript

I have an variable that devolves an empty object, and i need validate thas this variable have a value.
guardar: function() {
var value1 = Ext.getCmp('radio1').getValue();
if (value1 === {}) {
alert('It is necessary to select an option.');
return;
}
}
When it arrives in the debug line in the If statement, although the value of the variable is {}, when evaluating the condition the result is false.
¿Someone could help me about how can i do that validation?

If you get a object, then, do you need to proccess that object to verify if exist a property
Try this:
guardar: function() {
var value1 = Ext.getCmp('radio1').getValue();
if (typeof value1 === 'object' && Object.keys(value1).length === 0) {
alert('It is necessary to select an option.');
return;
}
}

guardar: function() {
var value1 = Ext.getCmp('radio1').getValue();
if (Object.keys(value1).length === 0) {
alert('It is necessary to select an option.');
return;
}
} // This Will Work as your requirement

You can't do value1 === {} for the same reason that {} === {} is false. The reason for this is javascript compares objects by reference, not by value. Which means it checks if the objects occupy the same memory location.
You can try something like
Object.prototype.isEmpty = function() {
for(var key in this) {
if(this.hasOwnProperty(key))
return false;
}
return true;
}
Then you can test if it's empty
if (value1.isEmpty()) {
alert('It is necessary to select an option.');
return;
}

function isEmpty(obj) {
for(var key in obj) {
if(obj.hasOwnProperty(key)){
return false;
}
}
return true;
}
var x = {};
if(isEmpty(x)){
alert('It is necessary to select an option.');
return;
}else{
}

Related

Foreach loop to check for a value

I have a foreach loop that loops through an array, then im running a callback function with the value of each item in the array as the parameter of the function, which is run once fore very item in the array. In the call back function i am trying to compare the value being passed with a string, but I always get a false nothing gets logged to console
This is my code
window.addEventListener('load', function() {
let occupation = ["urologist", "urologist", "staff", "nurse", "surgeon"]
occupation.forEach(function(occ) {
let ab = occ.textContent
let bc = ab.toLowerCase();
chkfun(bc)
})
function chkfun(val) {
if (val == "urologist") {
console.log("urologist")
}
if (val == "surgeon") {
console.log("surgeon")
}
if (val == "staff") {
console.log("staff")
}
if (val == "nurse") {
console.log("nurse")
}
}
}, false);
Your problem is with the line let ab = occ.textContent. occ contains the text content already. You can just do bc = occ.toLowerCase()
Also take a look at JavaScript Switch instead of doing a bunch of if's
You can call your function inside the forEach and it will be called with each element, there you can transform your value to lowercase and compare, also use a else if so the script will not test each value and stop as soon as it get a match. You can also add a else at the end for unknown elements
window.addEventListener('load', function() {
let occupation = ["Urologist", "urologist", "staff", "nurse", "surgeon","a"];
occupation.forEach(chkfun);
function chkfun(v) {
let val = v.toLowerCase();
if (val == "urologist") {
console.log("urologist")
} else if (val == "surgeon") {
console.log("surgeon")
} else if (val == "staff") {
console.log("staff")
} else if (val == "nurse") {
console.log("nurse")
} else {
console.log("element not found");
}
}
}, false);

Messed up my JavaScript return statements

I have a function defined like this:
var getPhoneNumber = function (list, phoneType) {
if (_.isEmpty(list)) {
return "Not Entered"
};
_.each(list, function(phoneNo){
if (phoneNo.name === phoneType) {
return phoneNo.value;
};
});
return "Not Entered";
}
list is an Array, while phoneType is a String. The problem is the function always returns the value Not Entered even if the list is not empty and has a phoneNo.name equal to phoneType. If I add a console.log in the if it shows that the condition is true and prints the console.log message but still returns Not Entered
return phoneNo.value; doesn't correspond to the function getPhoneNumber, but to the function passes as callback at _.each.
You should try something like this instead:
var getPhoneNumber = function (list, phoneType) {
var value = null;
_.each(list, function(phoneNo){
if (phoneNo.name === phoneType) {
value = phoneNo.value;
}
});
if(value !== null)
return value;
else
return "Not Entered";
}

Undefined counting as a variable -- messes up with my isObjEmpty() function

I am trying to post an object only if it's not empty. However I have code which causes properties to become undefined -- and when that happens, the obj is not empty anymore and the post still happens.
userSearchData = {};
$('#addContactForm').keyup(function()
{
var email = $(this).find('input[name="email"]').val();
var username = $(this).find('input[name="username"]').val();
var fullName = $(this).find('input[name="fullName"]').val();
userSearchData.email = email.length >= 3 ? email : undefined;
userSearchData.username = username.length >= 3 ? username : undefined;
userSearchData.fullName = fullName.length >= 3 ? fullName : undefined;
console.log(userSearchData);
if ( !isEmpty(userSearchData) )
{
console.log("Is empty")
$.post( '/post/addContact', { userSearchData: userSearchData }, function( data )
{
console.log( data );
});
}
});
It's a "search" form, so if a user types for example "Blabla" as the username, and then erases letters to make it "Bl", then the username variable gets undefined, so it's not being sent when doing the post (I console log the object on the server side and the undefined variables are not considered which is good).
How can I make my variables completely removed, instead of undefined when their length is below 3?
I could probably modify the isEmpty function to return false if all keys are undefined, would that be better to do that? If so, how would you do it?
var hasOwnProperty = Object.prototype.hasOwnProperty;
function isEmpty (obj)
{
// null and undefined are "empty"
if (obj == null) return true;
// Assume if it has a length property with a non-zero value
// that that property is correct.
if (obj.length > 0) return false;
if (obj.length === 0) return true;
// Otherwise, does it have any properties of its own?
// Note that this doesn't handle
// toString and valueOf enumeration bugs in IE < 9
for (var key in obj) {
if (hasOwnProperty.call(obj, key)) return false;
}
return true;
}
The whole thing seems rather pointless, you can just do this instead
$('#addContactForm').on('keyup', function() {
var userSearchData = {}, self = this;
$.each(['email', 'username', 'fullName'], function(_, el) {
var val = $(self).find('input[name="'+el+'"]').val();
if ( val.length > 3 ) userSearchData[el] = val;
});
$.post( '/post/addContact', { userSearchData: userSearchData }, function( data ) {
console.log( data );
});
});
Only add the properties to the object if the condition is met.
if ( username.length >=3 ) {
userSearchData.username = username;
}
if ( username in userSearchData ) {
// do stuff
}
you can delete properties in JS, but the better fix is to just make sure your code posts when it should.
if (obj === null || obj === undefined) return;
or something might help you here.
Also, for(key in obj) is old-style "iterate over prototype as well", and highly discouraged, so you probably want this instead:
var keys = Object.keys(obj);
if(keys.length === 0) ...
keys.forEach(function(key) { ... });
Do you mean you want do this?
if(!isEmpty(userSearchData)){
$.post( '/post/addContact', { userSearchData: userSearchData }, function( data )
{
console.log( data );
});
}

Jquery loop form to check for all empty fields then execute a function

I'm trying to loop form to check for empty field and then execute and function. I'm currently using something like this below that I found on this website but what is happening that the each loop check 1 field and see 1 that not empty and still execute else function. I think I need to check all at once then execute next function. How could I achieve this?
if($('.enter-info--ownerInfo .req').val() != "") {
alert("Empty Fields!!")
} else {
run this function
}
Thanks...
Use filtering, it is easy:
var anyFieldIsEmpty = $("form :input").filter(function() {
return $.trim(this.value).length === 0;
}).length > 0;
if (anyFieldIsEmpty) {
// empty fields
}
DEMO: http://jsfiddle.net/Lz9nY/
$('.enter-info--ownerInfo .req').each(function() {
if ($(this).val() == "")
{
alert("empty field : " + $(this).attr('id'));
}
});
Start by selecting all your fields:
var fields = $('.enter-info--ownerInfo .req')
Then filter them down to the ones with an empty value:
fields.filter(function() {
return this.value === '';
});
Then check the length property of the resulting object. If it's equal to 0 then all fields have a value, otherwise you execute your function.
if(fields.length === 0) {
// no empty fields
}
else {
// empty fields
}
You can use a loop and flag:
var valid = true;
$('.req').each(function () {
if ($(this).val() == '') {
valid = false;
return false;
}
});
if (valid) {
// all fields are valid
}
You can use .filter method to reduce the elements to those matching your criteria:
if $('.enter-info--ownerInfo .req').filter(function () {
return $.trim($(this).val()) == ""
}).length > 0) {
alert("One or more fields are empty")
} else {
// run this function
}

If/else condition inside an Object

function Validator(formIsValid) {
if(this.formIsValid) {
alert('Form is valid!');
}
else {
alert('Form is invalid...');
}
}
Validator.prototype = { // Notice the .prototype here, it's important!
formIsValid: true,
enforceTextFieldMinLength: function(field, minLength) {
if (!field.value || field.value.length < minLength) {
this.formIsValid = false;
}
},
enforceLabelHasText: function(label) {
if (!label.text) {
this.formIsValid = false;
}
}
}
//var val = new Validator();
The above is my Val.js. This is how i am using in my otherFile.js
AddPatient.Firstname = FirstNameValue || Validator.enforceLabelHasText(FirstName);
I get an error saying cannot find function enforceLabelHasText in Object function Validator(formIsValid)
You can't put expressions in an object definition. If you want code to be executed after an object instance is created, you should use:
function Validator() {
if(this.formIsValid) {
alert('Form is valid!');
}
else {
alert('Form is invalid...');
}
}
Validator.prototype = { // Notice the .prototype here, it's important!
formIsValid: true,
enforceTextFieldMinLength: function(field, minLength) {
if (!field.value || field.value.length < minLength) {
this.formIsValid = false;
}
},
enforceLabelHasText: function(label) {
if (!label.text) {
this.formIsValid = false;
}
}
}
var a = new Validator();
This is a dummy solution; you will want to add arguments to the Validator() function, to initialize formIsValid and the other values. I suggest you should read the MDC's description on prototypes.
EDIT: If you went with the prototype solution, you need to call val.enforceLabelHasText(FirstName), after making val a global variable (either by omitting the var or by using var window.val = new Validator()).
This is not valid syntax.
You've dumped an if/else condition inside an object definition, like this:
var myObj = { a, b, c, d,
if (true) {
alert('WTF!');
}
};
Procedural code like this must be inside a function.
You can insert logic into an object literal, using an iife. Like this;
const testable = 1
const obj = {
a: 'value1',
b: (() => {
if (testable === 1) {
return 'testable was 1'
} else {
return 'testable was not 1'
}
})()
}
console.log(obj)
Validator is an object literal and you can only assign properties there, not arbitrary code.
You could assign a function which includes your code to a property.
Bind this to a variable in the beginning.
var that = this;
This keeps this changing and point to something else.
And use firebug!

Categories