views:

29

answers:

2

Say I submit a form via Ajax and need a response from the server:

  • Pass/fail indicator
  • On fail, a list of validation errors with associated field ids/names, etc

Is there a standard or best practice for the JSON format for such a structure? If so, I'd like to try to stick to it instead of coming up with my own convention.

A: 
{
    "result": "false", 
    "fields":
        [
             {"id": "element1", "name": "element1"},
             {"id": "element2", "name": "element2"},
             {"id": "element3", "name": "element3"}
        ]
}
Marko
A: 

Hmm. I don't know about a standard, but you might want to just do something like

{
    "result": "false", 
    "hasErrors": true, // redundant, but saves you the checking of the errors array
    "errors":
        [
             {"errorCode": "1234", "errorText": "malformed address"},
             {"errorCode": "5678", "errorText": "no username"}
        ]
}
Gopherkhan
Why not just check errors array if result = false?
StackOverflowNewbie
it's something we do at work. I'm not sure of the reasoning myself :P I'm assuming it's for a general validation failure case, to which no specific errors map....but then again, that would seem to merit a catchall error code. I'm not sure why they do it :)
Gopherkhan