remote.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. (function ($) {
  2. $.fn.bootstrapValidator.validators.remote = {
  3. html5Attributes: {
  4. message: 'message',
  5. url: 'url',
  6. name: 'name'
  7. },
  8. /**
  9. * Request a remote server to check the input value
  10. *
  11. * @param {BootstrapValidator} validator Plugin instance
  12. * @param {jQuery} $field Field element
  13. * @param {Object} options Can consist of the following keys:
  14. * - url
  15. * - data [optional]: By default, it will take the value
  16. * {
  17. * <fieldName>: <fieldValue>
  18. * }
  19. * - name [optional]: Override the field name for the request.
  20. * - message: The invalid message
  21. * @returns {Boolean|Deferred}
  22. */
  23. validate: function(validator, $field, options) {
  24. var value = $field.val();
  25. if (value == '') {
  26. return true;
  27. }
  28. var name = $field.attr('data-bv-field'), data = options.data;
  29. if (data == null) {
  30. data = {};
  31. }
  32. // Support dynamic data
  33. if ('function' == typeof data) {
  34. data = data.call(this, validator);
  35. }
  36. data[options.name || name] = value;
  37. var dfd = new $.Deferred();
  38. var xhr = $.ajax({
  39. type: 'POST',
  40. url: options.url,
  41. dataType: 'json',
  42. data: data
  43. });
  44. xhr.then(function(response) {
  45. dfd.resolve($field, 'remote', response.valid === true || response.valid === 'true');
  46. });
  47. dfd.fail(function() {
  48. xhr.abort();
  49. });
  50. return dfd;
  51. }
  52. };
  53. }(window.jQuery));