Reputation: 31
I am running this task to teach my brother, he is asked to create a Javascript simple program to validate this data
[
{code: ‘10001’, amount: ‘’},
{code: ‘10002’, amount: ’50.00’},
{code: ‘’, amount: ’60.00’},
]
I need to show the errors that if there is an amount, code shouldn't be empty.
Upvotes: 2
Views: 139
Reputation: 4272
I mean if you is always getting an array of objs why not use Joi You can define yow schemas and set the characteristics or needs of each prop on them objs https://joi.dev/api/?v=17.3.0
Upvotes: 0
Reputation: 28414
You can use .some
:
const data = [
{code: '1000', amount: ''},
{code: '10002', amount: '50.00'},
{code: '', amount: '60.00'},
];
const isInValid = data.some(e => e.amount && !e.code);
console.log("Data is not valid?", isInValid);
Or use .every
:
const data = [
{code: '1000', amount: ''},
{code: '10002', amount: '50.00'},
{code: '', amount: '60.00'},
];
const isValid = data.every(e => !e.amount || e.code);
console.log("Data is valid?", isValid);
Upvotes: 1
Reputation: 2528
Credit to @Majed Badawi, but with fixed validation expression.
const data = [
{code: '1000', amount: ''}, // is okay
{code: '10002', amount: '50.00'}, // absolutely valid
{code: '', amount: '60.00'}, // invalid
{code: '', amount: ''}, // empty but still valid
];
const validFlags = data.map(e => !e.amount || e.code);
const isValid = validFlags.every(f => f);
console.log("Validation per record", validFlags.map(Boolean));
console.log("Final result", isValid);
Upvotes: 1