A blazing fast request validator for your phoenix and bared plug app, which validates a request body before hitting the request handler in the controller.
It's common for a web service to validate incoming data. The most common layer where this is done is at the controller level and this sometimes leads to having a bloated controller. But with RequestValidator, you move the validation logic to a layer just before the controller and your controller is now free from doing validation.
The package can be installed by adding request_validator to your list of dependencies in mix.exs:
defdepsdo[{:request_validator,"~> 1.0.2"}]endFirst of all, you need to define a validation schema to be used against the incoming data.
defmoduleApp.Requests.RegistrationdouseRequest.ValidatorimportRequest.Validator.Rules# Get the validation rules that apply to the incoming request.@implRequest.Validatordefrules(_)do%{"email"=>~V[required|email],"first_name"=>~V[required|string],"last_name"=>~V[required|string],"password"=>~V[required|string|min:8|confirmed]}end# Determine if the user is authorized to make this request.@implRequest.Validatordefauthorize?(_),do: trueendThe above validation schema can now be used;
defmoduleApp.UserControllerdouseAppWeb,:controlleruseRequest.Validator.Plug@validateApp.Requests.Registrationdefregister(conn,params)docaseApp.UserService.create(params)do:ok->conn|>put_status(201)|>json(%{message: "Account created successfully"}){:error,msg}->conn|>put_status(500)|>json(%{message: msg})endendendAs you can see in the controller, the register handler does not need to worry about validating the incoming request because RequestValidator will handle that automatically and send the right response if the request fails validation based on the given validation schema.
You can specify validation schema for each of the handlers in a controller:
defmoduleApp.UserControllerdouseAppWeb,:controlleruseRequest.Validator.Plug@validateApp.Requests.Logindeflogin(conn,params)do# ...end@validateApp.Requests.Registrationdefregister(conn,params)do# ...endendFull documentation can be found at https://hexdocs.pm/request_validator.
This library provides a variety of helpful rules, however, you might want to define some rules to house your validation logic. To achieve this, you need to create your own rules module;
defmoduleApp.Validation.RulesdoimportRequest.Validator.RulesaliasRequest.Validator.Rules@specuppercase()::Rules.validator()defuppercasedofnattr,value->message=gettext("The %{attribute} field must be uppercase.",attribute: attr)caseString.upcase(value)==valuedotrue->:okfalse->{:error,message}endendendendTo use, you simply import your custom rules and;
importRequest.Validator.RulesimportApp.Validation.Rules# ...defrules(_)do%{"name"=>~V[required|string|uppercase],"age"=>~V[required|integer],"parent"=>[required_if("age",18,&Kernel.<=/2),upppercase()]}end# ...Find rules here.
Validating nested map input shouldn't be a problem. For example the HTTP request contains address field which is a map with nested attributes (line1, line2...), you may validate it like so:
%{"address.line1"=>~V[required|string|max:100],"address.city"=>~V[required|string|max:50],"address.zip_code"=>~V[required|string|max:10],"address.country"=>~V[required|string|max:60],"address.line2"=>~V[string|max:100],"address.state"=>~V[string|max:50]}In the case where you want to validate elements nested in a list, you should use the * character;
# request%{"likes"=>["epl","laliga"],"documents"=>[%{"type"=>"selfie"},%{"type"=>"id","issuing_country"=>"US"}]}# rules%{"likes"=>~V[required|list|min:1],"likes.*"=>~V[required|allowed:epl,laliga],"document"=>~V[required|list|min:2],"documents.*.type"=>~V[required|allowed:selfie,id]}- Include more validation rules
- Norm validation support
RequestValidator is released under the MIT License - see the LICENSE file.