DEV Community

Afroze Kabeer Khan. M
Afroze Kabeer Khan. M

Posted on

A Dead simple object validator

As i said it's simple to the core

Compares the validation object with model and returns its invalid / does not exist.

async function validator(requestObject, validatingObj){

  let paramsError = {
    missingParams: [],
    invalidParams: [],
    message: ''
  }

  function constructMessage(_paramsError){
    let missingParamsMsg = `Missing the following parameters ${_paramsError.missingParams.join()}`;

    let invalidParamsMsg = `The Following parameters are invalid ${_paramsError.invalidParams.join()}`;

    return missingParamsMsg + '. ' + invalidParamsMsg;
  }


  await Object.keys(validatingObj).map(validParam => {
  Object.keys(requestObject).includes(validParam) 
    ? typeof validatingObj[validParam] === typeof requestObject[validParam] ?
       '' : paramsError.invalidParams.push(validParam) : paramsError.missingParams.push(validParam);
  })

  paramsError.message = constructMessage(paramsError);

  return paramsError;
}
Enter fullscreen mode Exit fullscreen mode

Now let's see an example on how to use it.

let requestObject = { username: 'one', mailid: 123123, rides: [] };
let validatingObj = {
  username: "",
  mobile: 0,
  mailid: "",
  age: 0,
  rides: { driverid: 0, carModel: '' }
}

//validating object with the request object
validator(requestObject, validatingObj).then(paramsError => {
  console.info('paramsError',paramsError);
}).catch(err => {
  console.error("\nError",err)
})
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
anduser96 profile image
Andrei Gatej

I like the idea! But what’s the use case for async/await?

And because I’m quite opinionated, I’d get the array of keys requestObject before iterating over validatingObj, instead of recomputing it in every iteration.

Nonetheless, thank you for sharing!

Collapse
 
droidmakk profile image
Afroze Kabeer Khan. M

It's the opinions that enhances an idea.
As I was doing a map the output was undefined. Later I tried async way got the expected value.

Collapse
 
droidmakk profile image
Afroze Kabeer Khan. M

PS It needs a little improvisation in terms of validating objects! 😜