4

我已经为我的验证表单应用程序尝试了 client_side_validations gem,这真的很棒。我正在为我的用户模型使用设计,当我转到new_user_registration表单时,当我输入密码并将 [点击选项卡] 更改为字段密码确认时,在字段密码一侧显示验证“与确认不匹配”。

查找我的应用程序以进行注册:示例设计

在模型上

validates_confirmation_of :password, :only => :create
validates_presence_of :password

如何在字段密码确认中显示“与密码不匹配”的验证位置?

在此处输入图像描述

4

1 回答 1

0

我正在分享我的解决方案。

我破解了代码,以便正确显示 password_confirmation 错误,并且仅在输入错误确认密码后才显示。适用于 Zurb-Foundation 表单错误。

该文件位于 app/assets/rails.validators.js

//= require rails.validations


window.ClientSideValidations.formBuilders['ActionView::Helpers::FormBuilder'] = {
  add: function(element, settings, message) {
    var form = $(element[0].form);

    if (element.data('valid') !== false) {
      var for_id = element.attr('id');
      if (form.find("label.error[for='" + for_id + "']")[0] == null) {
        form.find("label[for='" +  for_id + "']").addClass('error');
        element.addClass('error');
        element.after('<small class="message error" for="' + for_id + '">' + message + '</small>');
      } 
    }

    return form.find("small.message[for='" + (element.attr('id')) + "']").text(message);
  },
  remove: function(element, settings) {
    var form = $(element[0].form);

    if (element.hasClass('error')) {
      var for_id = element.attr('id');
      form.find("label[for='" +  for_id + "']").removeClass('error');
      element.removeClass('error');
      form.find("small.error[for='" + for_id + "']").remove();
    }
    return element;
  }
}



window.ClientSideValidations.callbacks.element.fail = function(element, message, callback, event) {
  if (message.indexOf("doesn't match") != -1) {

    var eid = element.attr('id');
    var conf_el = $(element[0].form).find('#' + eid + '_confirmation');

    var form_id = $(element[0].form).attr('id');

    var settings = window.ClientSideValidations.forms[form_id];

    if (conf_el.data('interacted')) {
        ClientSideValidations.formBuilders[settings['type']].add(conf_el, settings, message);
    }
    ClientSideValidations.formBuilders[settings['type']].remove(element, settings);
    //callback();
  } else {
    callback();
  }
}


window.ClientSideValidations.callbacks.element.pass = function(element, callback, event) {
  var eid = element.attr('id');
  var conf_el = $(element[0].form).find('#' + eid + '_confirmation');

  if (conf_el.size() > 0) {
    var form_id = $(element[0].form).attr('id');
    var settings = window.ClientSideValidations.forms[form_id];
    //var settings = window.ClientSideValidations.forms['new_user'];
    ClientSideValidations.formBuilders[settings['type']].remove(conf_el, settings);
  } 

  callback();
}



$(function() {
  //bind change keyup keypress
  $("input[id$=_confirmation]").on('keyup keypress change', function(e) {
    $(this).data('interacted', true);
    $(this).off('keyup keypress change');
  });
});
于 2013-10-08T16:38:04.123 回答