DEV Community

loading...

A Dead simple object validator

Afroze Kabeer Khan. M
Full stack Developer. Node Js, JavaScript & React
ใƒป1 min read

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

Discussion (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 Author

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 Author

PS It needs a little improvisation in terms of validating objects! ๐Ÿ˜œ