日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

關于for循環遍歷不同表單校驗的bug(需要多次校驗)

作者:農夫三拳有點疼=-= 更新時間: 2023-10-17 編程語言

明明是符合條件的,第一次校驗是true,第二次就變成了false不符合,原因

例子

export const ngx = {
    // 郵箱
  email: () => /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/g,
  // 手機號
  mobile:() => /^[1]\d{10}$g/,
  number:() => /^[0-9]*/g,
}

for (let i = 0; i < baseForm.value.length; i++) {
        // 手機校驗
          if (!ngx.mobile().test(Number(inpValue1)) {
            return message.error(`請正確輸入手機號`)
          }
          if (!ngx.email().test(inpValue2)) {
            message.error(`請正確輸入郵箱`)
            return
          }
        }
第一次符合條件兩個都為true,第二次兩個都為false

原因是正則匹配/g的這個問題,

每個正則匹配都有一個lastIndex的屬性

這屬性在后面/g的時候會記錄最后一個符合條件的下標的位置,導致下次一遍歷是從這個下標開始,

比如ngx.test(13566664444) //這個時候第一次校驗結束lastIndex在第11個位置,再次校驗是從第11為開始i往后校驗,沒有數據就顯示false

所以,解決這個問題就是取消/g以及將這個屬性寫成閉包的形式

export const ngx = {
    // 郵箱
  email: () => /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
  // 手機號
  mobile:() => /^[1]\d{10}$/,
  number:() => /^[0-9]*/,
}
for (let i = 0; i < baseForm.value.length; i++) {
        // 手機校驗
          if (!ngx.mobile().test(Number(inpValue1)) {
            return message.error(`請正確輸入手機號`)
          }
          if (!ngx.email().test(inpValue2)) {
            message.error(`請正確輸入郵箱`)
            return
          }
        }

這樣一來不管怎么for循環lastIndex都是從下標0開始

原文鏈接:https://blog.csdn.net/m0_64207574/article/details/131113705

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新