我已经编写了验证测试,但满足 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.
关于javascript - 如果验证测试中条件无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55700492/