Reputation: 37
I've programmed validation test but the if
condition is satisfied
even though it is not supposed to.
Here is my code:
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>
I wrote my name
(wonki
), birth
(19890222
) and phone
(01012341234
), then clicked the button(onclick="chk_val()")
. It could pass all of the if
statements, but it got caught in alert('3')
or alert('5')
.
I used console.log
to check the value of num.test(birth)
and num.test(phone)
, and it comes out TRUE.
I don't know why I cannot pass if(!num.test(birth))
and if(!num.test(phone))
.
Upvotes: 0
Views: 106
Reputation: 317
you need to change just RegExp for number
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 = new RegExp('^\\d+$');
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>
Upvotes: 1
Reputation: 2202
As mentioned in one of the comments, you need to remove the global flag(/g) from the regex.
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.
Upvotes: 1