2

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.

3 Answers 3

1

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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);

4 Comments

Probably not correct. e.code && e.amount means *both code and amount are required". Maybe !e.amount || e.code ?
@VasilyLiaskovsky I think OP meant both are required
!e.code || !e.amount is exact reverse to e.code && e.amount. Second maybe correct in some meaning, but definitely not the first. With some still is not correct
@VasilyLiaskovsky thanks for highlighting the validation misunderstanding, feel free to suggest edits to the proposed solution
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.