Akash Sethi
Akash Sethi

Reputation: 2294

how to apply custom validation on json value

I have a json data coming via api. I have set of policies that I need to validate over coming json data.

For Example I have a json like

{
"users_id":"x",
"is_user_logged_in":"true",
"checkin_date":"2018-12-12",
"checkout_date":"2019-12-13"
}

Now I want to apply validation like checkin_date should be less than checkout_data or let say if is-user_logged_in is true then user_id should not be null.

I cant deserialize the json as i need to pass it to different application to consume

I am using Scala any idea how can i implement this. The catch is there can be multiple policies or rules i need to validate and i can only get the rules in runtime.

Thanks

Upvotes: 1

Views: 786

Answers (1)

Andriy Plokhotnyuk
Andriy Plokhotnyuk

Reputation: 7989

Most easier way is to add validation to the default constructor and just use the JSON parser as a validator (no need to use parsed data):

import java.time.LocalDate

case class UserData(
  user_id: Option[String],
  is_user_logged_in: Boolean,
  checkin_date: LocalDate,
  checkout_date: LocalDate
) {
  require(!is_user_logged_in || user_id.isDefined, "missing `user_id` for logged in user")
  require(checkout_date.isAfter(checkin_date), "`checkout_date` should be after `checkin_date`")
}

For more complicated cases please consider to use some handy validation library, like:

https://github.com/jto/validation

Upvotes: 2

Related Questions