[英]JS phone number validation - matching strings
All I need to do is checking if the input includes any value of the given array. 我需要做的就是检查输入是否包含给定数组的任何值。 For some reason it returns always true;
由于某种原因,它总是返回true。
document.querySelector('#phonenumber').addEventListener('change', function (e) {
let alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
let target = e.target.value;
let splittedTarget = target.split('');
console.log(splittedTarget, alphabet)
if (alphabet.indexOf(splittedTarget) > -1) {
alert('there is not');
} else {
alert('there is');
}
});
Fiddle link: https://jsfiddle.net/et5avosu/ 小提琴链接: https : //jsfiddle.net/et5avosu/
You can use .some()
on your input characters: 您可以在输入字符上使用
.some()
:
const alphaInInput = !splittedTarget.some(elem => alphabet.indexOf(elem) > -1);
alphaInInput
will be a boolean
. alphaInInput
将是一个boolean
。 If your input contains a character from the alphabet
string then it will be true
, if it doesn't then it will be false
. 如果输入包含
alphabet
字符串中的一个字符,则为true
,否则为false
。
See working example below: 请参见下面的工作示例:
document.querySelector('#phonenumber').addEventListener('change', function (e) { let alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; // Remove .split() (no need for array) let target = e.target.value; let splittedTarget = target.split(''); const alphaInInput = splittedTarget.some(elem => alphabet.indexOf(elem) > -1); // console.log(splittedTarget, alphabet) if (!alphaInInput) { alert('there is not'); } else { alert('there is'); } });
<input id="phonenumber" />
Or you can use regex
by using the following pattern /[A-Za-z]/g
, and then using .test()
to see whether your input matches the pattern. 或者,可以通过使用以下模式
/[A-Za-z]/g
来使用regex
,然后使用.test()
来查看您的输入是否与该模式匹配。
Note : The /[A-Za-z]/g
tests for characters from A to Z and a to z, ie, what your Alphabet string contains: 注意 :
/[A-Za-z]/g
测试从A到Z和从a到z的字符,即字母字符串包含的内容:
document.querySelector('#phonenumber').addEventListener('change', function (e) { let inputStr = e.target.value; let regex = /[A-Za-z]/g; let alphaInInput = regex.test(inputStr); if (!alphaInInput) { alert('there is not'); } else { alert('there is'); } });
<input id="phonenumber" />
Array<String>.indexOf(Array)
is always -1
, because the list of String
s does not contain an Array
. Array<String>.indexOf(Array)
始终为-1
,因为String
的列表不包含Array
。 You need to use some other method to validate the input. 您需要使用其他方法来验证输入。
Use this instead, I tested and it worked 改用它,我测试了一下
document.querySelector('#phonenumber').addEventListener('change', function (e) {
let alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
let target = e.target.value;
let splittedTarget = target.split('');
if(splittedTarget.every(r => alphabet.indexOf(r) < 0)){
alert('only numbers');
} else {
alert('there is letter');
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.