jqBootstrapValidation icon indicating copy to clipboard operation
jqBootstrapValidation copied to clipboard

programmatic API to set errors (eg, by server validation errors)

Open carchrae opened this issue 11 years ago • 3 comments

Perhaps I missed some piece of documentation that shows how to do this, but I'm struggling with the following use case:

I would like to show server validation errors on a per-form basis rather than per-field. My application submits the form values via an AJAX like request and this returns success or a hash like

{ "errors" : { "username" : "this username is taken" } }

Now, I know you have support for a per field server validation, but I would really like to avoid writing an additional validator end-point for each form field. Also, note that in some cases, such an error could be the result of a combination of fields.

carchrae avatar Jun 03 '13 18:06 carchrae

I think I can hack a somewhat ugly way to do this by adding a data-validation-regex validator to the form (and re-rendering it on the client) which then shows the error

  <input name="username" 
  data-validation-regex-regex="((?!(bob)).)*" data-validation-regex-message="this username is taken" />

(regex from http://stackoverflow.com/questions/6449131/javascript-regular-expression-to-not-match-a-word - i believe jqBootstrapValidation adds the outside (anchors) for the expression)

of course, care would need to be taken to ensure that the regex value was properly escaped: http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex

carchrae avatar Jun 03 '13 18:06 carchrae

+1

Yeah, I was looking for such a feature as well.

dsc8x avatar Jun 05 '13 19:06 dsc8x

For the moment, I just add extra error elements to my form - not ideal.

I tried the regex, but didn't get it working. I then started adding a "must not match" validator, but haven't finished it yet. It would look like this:

 <input name="username" 
  data-validation-servererror1-notmatch="bob" data-validation-servererror1-message="this username is taken" />

You could simply add new validators to each input on successive failures, eg,

 <input name="username" 
  data-validation-servererror1-notmatch="bob" data-validation-servererror1-message="this username is taken" 
  data-validation-servererror2-notmatch="charles" data-validation-servererror2-message="this username is also taken" />

Which could remind the user of previous subimt errors.

carchrae avatar Jun 05 '13 20:06 carchrae