name 属性中带有方括号的输入

Pie*_*ser 5 html javascript validation attributes input

我在这个论坛上进行了很多搜索来解决这个问题,但到目前为止还没有成功。我有一个包含多个<input>部分的表格。在此表单中,我有一个密码字段和一个确认密码字段,需要使用第一个密码进行验证。下面是 HTML 代码示例:

<input 
  title="Password should contain at least 6 characters or numbers" type="password"
  pattern=".{6,}"
  name="RegisterForm[password]"
  onchange="this.setCustomValidity(this.validity.patternMismatch ? this.title : ''); if(this.checkValidity()) form.RegisterForm[password2].pattern = this.value;"
  placeholder="Password..."/>

<input
  title="Please enter the same Password as above"
  type="password"
  pattern=".{6,}"
  name="RegisterForm[password2]"
  onchange="this.setCustomValidity(this.validity.patternMismatch ? this.title : '');"
  placeholder="Confirm Password . . ."/>
Run Code Online (Sandbox Code Playgroud)

两个输入都有一个带方括号的名称,例如"RegisterForm[password]"。如果我使用不带括号的名称属性,则验证有效,如果我使用带括号的名称属性,则验证不起作用。有什么想法如何克服名称属性中的方括号问题而不丢失方括号?

如果我将名称属性替换为"password1"and "password2",那么一切都会按预期进行。

如果有人有解决方案,请帮助我!:-)。

Ger*_*_RU 5

首先,我认为将大量代码放入on-事件属性中并不是一个好的做法。对于我来说,我更喜欢在 javascript 源文件中定义一些函数并使用它们,而不是将复杂的表达式放入属性中。

无论如何,问题是form.RegisterForm[password2].pattern访问输入元素的方式是错误的。在这种情况下form,将查找第一个对象。然后解释器尝试查找RegisterForm属性。方括号是访问对象属性的另一种方法,但它需要一个字符串。在您的情况下,有password2 标识符而不是字符串文字,我相信它将尝试读取具有相同名称的变量的值并根据RegisterForm结果查找属性。因此整个表达式是无效的,并且可能会在RegisterForm步骤早期失败。

但您仍然可以通过包含方括号的名称访问您的输入,例如使用querySelector()函数:

var passwordInput = document.querySelector('input[name="RegisterForm[password]"');
var confirmInput = document.querySelector('input[name="RegisterForm[password2]"');
Run Code Online (Sandbox Code Playgroud)

以下代码片段按预期工作:如果输入的密码无效,则将自定义有效性消息设置为密码输入,否则设置空有效性消息并更新确认输入的模式属性。

function validatePassword() {
    var self = document.querySelector('input[name="RegisterForm[password]"]');
    var conf = document.querySelector('input[name="RegisterForm[password2]"]');
          
    self.setCustomValidity(self.validity.patternMismatch ? self.title : '');
          
    if (self.checkValidity()) {
        conf.setAttribute("pattern", self.value);
    }
}

function validateConfirm () {
    var self = document.querySelector('input[name="RegisterForm[password2]"]');
    self.setCustomValidity(self.validity.patternMismatch ? self.title : ''); 
}       
Run Code Online (Sandbox Code Playgroud)
<input
     title="Password should contain at least 6 characters or numbers"
     type="password"
     required
     pattern=".{6,}"
     class="input_bx"
     name="RegisterForm[password]"
     oninput="validatePassword();"
     placeholder="Password..."/>

<input
     title="Please enter the same Password as above"
     class="input_bx"
     type="password"
     required pattern=".{6,}"
     name="RegisterForm[password2]"
     oninput="validateConfirm();"
     placeholder="Confirm Password . . ."/>
Run Code Online (Sandbox Code Playgroud)

PS 构建您的代码,这将对您将来有所帮助。