簡體   English   中英

name屬性中帶方括號的輸入

[英]inputs with square brackets in the name attribute

我在這個論壇上搜索了很多來解決這個問題,但到目前為止還沒有成功。 我有一個包含多個<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 . . ."/>

兩個輸入都有一個帶方括號的名稱,例如"RegisterForm[password]" 如果我使用沒有括號的名稱屬性驗證工作,如果我使用括號,驗證不起作用。 任何想法如何克服名稱屬性中的方括號問題而不丟失方括號?

如果我用"password1""password2"替換name屬性,那么一切都按照預期的方式工作。

如果有人有解決方案,請幫幫我! :-)。

首先,我認為這是不把太多的代碼里面很好的做法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]"');

以下代碼片段按預期工作:如果輸入的密碼無效,則將自定義有效性消息設置為密碼輸入,否則設置空的有效性消息並更新確認輸入的模式屬性。

 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 : ''); } 
 <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 . . ."/> 

PS結構你的代碼,這將在未來幫助你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM