h5的input的required使用中遇到的问题

form提交时隐藏input发生的错误

问题描述

  • 在form表单提交的时候,有些input标签被隐藏,表单验证过程中会出现An invalid form control with name='' is not focusable 的错误

  • 虽然我遇到的问题是我的input标签根本没有required属性,但是在该标签隐藏之前,(我的是使用tab栏切换)我输入了错误的格式,再隐藏,这时候他其实是错误的,会被form表单同样去验证,但是由于它被隐藏,浏览器获取不到焦点就会报错。

解决方法

  • 隐藏之前将该input的value值设置为空即可.我的input上面没有使用required属性。

如果input含有display:nonerequired属性,也会产生该错误

  • 产生原因

Chrome希望专注于需要但仍为空的控件,以便可以弹出消息“请填写此字段”。但是,如果控件在Chrome想要弹出消息的时候隐藏,即在提交表单时,Chrome无法关注该控件,因为它是隐藏的,因此表单不会提交。

  • 解决方法如下
  1. 隐藏时,将required属性删除
selector.removeAttribute("required")
  1. 没有使用required的话,或许是由于button按钮,类型未设置造成。设置<button type="button">

  2. form表单不验证,即添加novalidate属性。(不是最终解决办法)<form novalidate></form>

  3. 既然是由于使用了display:none造成,同样的visibility: hidden 也会造成问题,那就不使用。通过可以设置css样式opacity: 0;

  4. 禁用此表单控件。 disabled 这是因为通常如果你隐藏了表单控件,那是因为你不关心它的价值。所以这个表单控件名称值对在提交表单时不会被发送。

$("body").on("submit", ".myForm", function(evt) {

    // Disable things that we don't want to validate.
    $(["input:hidden, textarea:hidden, select:hidden"]).attr("disabled", true);

    // If HTML5 Validation is available let it run. Otherwise prevent default.
    if (this.el.checkValidity && !this.el.checkValidity()) {
        // Re-enable things that we previously disabled.
        $(["input:hidden, textarea:hidden, select:hidden"]).attr("disabled", false);
        return true;
    }
    evt.preventDefault();

    // Re-enable things that we previously disabled.
    $(["input:hidden, textarea:hidden, select:hidden"]).attr("disabled", false);

    // Whatever other form processing stuff goes here.
});

如有其他更好方法,欢迎留言!

参考

https://stackoverflow.com/questions/22148080/an-invalid-form-control-with-name-is-not-focusable

https://stackoverflow.com/questions/30644606/an-invalid-form-control-with-name-is-not-focusable-without-any-required-or-h

原文地址:https://www.cnblogs.com/feiyu6/p/8930148.html