How to validate form POST data with Liberator?

477 views Asked by At

Where in the Liberator decision tree should I validate form input?

:malformed? seems to aimed at detecting invalid JSON or invalid form bodies.

2

There are 2 answers

2
schaueho On

This depends a little at what kind of validation you have in mind, cf. this discussion here on SO on whether HTTP 400 (bad request) for logical error should be used to signal logical errors as well. liberator provides lots of decision points that are related to things ranging from request-entity-too-large to checks for the right media-type. I would suggest to look at the wikipedia page on HTTP status codes to get an idea which return code might be the most appropriate for your validation and then use this to drive your suggestion which liberator decision point is relevant.

EDIT: Let's assume you want to return 422. You could use processable? to run the check you need, whose handler unprocessable-entity returns 422 if the check fails. Or you could use liberator.representation/ring-response to create the entire response from your handler or action. See also the discussion in the liberator google group.

0
Tim X On

I think it is fine to use handle-malformed, but you could also use, say, handle-unprocessable-entity. What is probably more important is to be consistent. I would look at it from the client side and decide which will make more sense and which provides the correct level of granularity or feedback for the client. For example, if it is important that the client gets sufficient feedback to distinguish between missing parameters and parameters that are provided, but have unacceptable values, then you might want to use handle-malformed for the first and handle-unprocessable-entity for the second. If on the other hand, you just need to signal there was a problem with the provided (or not provided) parameters, then only using handle-malformed might be the right choice as it will reduce your code size and simplify the logic needed at the client side.

I would tend to start with just using handle-malformed and then break it up into handle-malformed and handle-unprocessable-entity when I find there is a need to distinguish between the two types of failures.