javascript - 如果验证测试中条件无法正常工作

标签 javascript jquery

我已经编写了验证测试,但满足 if 条件 即使不应该这样做。

这是我的代码:

function chk_val() {

  var name = $('.info .name').val();
  var birth = $('.info .birth').val();
  var phone = $('.info .phone').val();
  var eng_kor = /^[가-힣a-z]+$/gi;
  var num = /^[0-9]+$/g;

  if (name == '' || birth == '' || phone == '') {
    alert('1');
  } else if (!eng_kor.test(name)) {
    alert('2');
  } else if (!num.test(birth)) {
    alert('3');
  } else if (birth.length != 8) {
    alert('4');
  } else if (!num.test(phone)) {
    alert('5');
  } else if (phone.length != 10 && phone.length != 11) {
    alert('6');
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="info">
  <input class="name" type="text" />
  <input class="birth" type="text" maxlength="8" />
  <input class="phone" type="text" maxlength="11" />
</div>
<button onclick="chk_val()">Check</button>

我写下了我的姓名 (wonki)、出生 (19890222) 和电话 code> (01012341234),然后单击 button(onclick="chk_val()")。它可以传递所有 if 语句,但它陷入了 alert('3')alert('5') 中。

我使用console.log检查num.test(birth)num.test(phone)的值,它结果为真。

我不知道为什么我无法通过 if(!num.test(birth))if(!num.test(phone))

最佳答案

正如其中一条评论中提到的,您需要从正则表达式中删除全局标志(/g)。

If the regex has the global flag set, test() will advance the lastIndex of the regex. A subsequent use of test() will start the search at the substring of str specified by lastIndex (exec() will also advance the lastIndex property). It is worth noting that the lastIndex will not reset when testing a different string.

Reference link

关于javascript - 如果验证测试中条件无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55700492/

相关文章:

javascript - 如果可观察结果等于某个值,如何退出函数

javascript - ES6 类 'this' 用于非类方法

javascript - Onclick 在 IE 中不起作用

php - Laravel Blade 中无法显示 Jquery 和 Ajax 错误消息

javascript - JS中如何在回调迭代时显示不同的内容

java - 将用户输入写入 XML 文件

jquery - 如果文档高于视口(viewport)则执行函数

javascript - 更新产品数量而不进行回发

javascript - HTML5 中的 DatePicker 设置当前日期

javascript - 如何正确使用 ES6 进行柯里化(Currying)?