-1

I want to validate the object so that the object is not null and few of the fields in that object is not empty.

For example, consider the following object:

address ={
    block : '2134',
    street : 'berly street',
    county : 'someCountry'
    postal : '876546'
}

I am using es6. I found the solution to do this using lodash

I want to do this in plain JS. Please let me know if there is a better way to do this than below:

 const isValidAddress = (address) => {

      const addressFields = ['block', 'county', 'postal', 'street'];
      return addressFields.every((element) => address[element] && address[element].length > 0);
};
codeMan
  • 5,730
  • 3
  • 27
  • 51

1 Answers1

2

You can try checking every value with Array.prototype.every like this.

const invalidAdress ={
    block: '',
    street: 'berly street',
    county: 'someCountry',
    postal: '876546'
};

const validAdress ={
    block: '1234',
    street: 'berly street',
    county: 'someCountry',
    postal: '876546'
};

// .every will return true if and only if every property in the object is a truthy value
const isValidAddress = (address) => Object.keys(address).every(x => address[x]);

console.log(isValidAddress(invalidAdress));
console.log(isValidAddress(validAdress));
Kunal Mukherjee
  • 5,775
  • 3
  • 25
  • 53
  • Object.keys is a good option, at least that what it looks like in the beginning but it will not solve the purpose if some property is entirely missing, but that's a different problem altogether – codeMan May 07 '19 at 11:47
  • @codeMan that wont solve it, but checking for missing properties is another task by itself. – Kunal Mukherjee May 07 '19 at 11:50