【问题标题】:Parsley.js focus on validated div on errorParsley.js 专注于验证 div 错误
【发布时间】:2020-04-22 00:17:14
【问题描述】:

我需要填写表单中三个字段中的至少一个。因此,我对包含这三个字段的 div 元素使用了欧芹验证。效果很好,唯一的问题是出错时,它不会像正常输入那样获得焦点。

这里有一些更具体的细节(这是haml语法):

#phone-fields.parsley-group-validate{data:{'parsley-one-child-required' => "mobile_phone|home_phone|work_phone",parsley_validate_if_empty:'true'
  = f.input :mobile_phone, as: :phone
  = f.input :home_phone, as: :phone
  = f.input :work_phone, as: :phone

然后在我的 javascript 文件中添加自定义 oneChildRequired 验证

      Parsley.addValidator('oneChildRequired', {
        requirementType: 'string', //expect format of string t be input ids separated by '|' e.g. "mobile_phone|home_phone|work_phone" not sure how to allow varying number of requirements so this will suffice
        validateString: function(_value, requirement, instance) {
          var multiSelector = "#enrolment_form_"+requirement.replace(/\|/g, ', #enrolment_form_');// gives multi selector like '"#enrolment_form_mobile_phone, #enrolment_form_home_phone, #enrolment_form_work_phone"'
          var $inputs = instance.$element.find(multiSelector);
          var valid = false;
          $inputs.each(function(i){
            if($(this).val()){
              valid = true; // one input has a value
              return false; //break out of the loop
            }
          });
          // no input has the target value (requirement2)
          return valid;
        }
      });

【问题讨论】:

    标签: validation parsley.js


    【解决方案1】:

    我在源代码中找到 return this._focusedField.focus();

    .focus() 仅适用于我认为的输入元素。

    所以为了修复它,我将其替换为

          if(this._focusedField.is(':input')){
            return this._focusedField.focus();
          } else {
            return this._focusedField.attr("tabindex",-1).focus();
          }
    

    else 块将触发对 div 元素的关注

    我想知道是否有更好的方法来做到这一点。

    【讨论】:

    • 如果您找到一种通用的方法来找到一个很好的通用方法来处理这个问题,欢迎 PR。
    猜你喜欢
    • 2014-08-23
    • 1970-01-01
    • 1970-01-01
    • 2015-02-15
    • 2018-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多