[英]Scan string for special characters and alphabets
I have a textbox which accepts time (max of 5 chars) in the format hh:mm or hhmm. 我有一个文本框,可以接受hh:mm或hhmm格式的时间(最多5个字符)。 Pls tell me a way I can just scan the string entered in the textbox, for special characters and alphabets? 请告诉我一种方法,我可以只扫描文本框中输入的字符串以查找特殊字符和字母吗? [If the string entered has these chars or alphabets, then an alert is displayed('Pls enter a valid time')] I tried the str.match and str.indexOf methods but it doesn't seem to help. [如果输入的字符串包含这些字符或字母,则显示警报(“请输入有效时间”)]我尝试了str.match和str.indexOf方法,但似乎无济于事。
<script type='text/javascript'>
function clocks(){
var clk = document.getElementById('TIME').value;
var ampm = document.getElementById('AMPM').value;
var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";
for (var i = 0; i < 5; i++) {
if (iChars.indexOf(clks.charAt(i)) != -1) {
alert ("Pls enter a valid time");
return false;
}
}
.....}
</script>
How are you using string.match()? 您如何使用string.match()? This should work: 这应该工作:
<script type='text/javascript'>
function clocks(){
var clk = document.getElementById('TIME').value;
var ampm = document.getElementById('AMPM').value;
if (clk.match(/[^0-9:]/)) {
alert("Please enter a valid time");
}
// or, an even more precise regex
if (!clk.match(/^\d+:\d+$/)) {
alert("Please enter a valid time");
}
.....}
</script>
The first regex match should check for anything that is NOT a digit or the ':' character, and raise an alert if it finds anything. 第一个正则表达式匹配项应检查非数字或':'字符的内容,如果发现任何内容,则发出警报。 The second one will match any string that starts with one or more digits, then a ':' character, then one or more digits, then the end of the string (which is the format you're trying to match). 第二个将匹配以一个或多个数字开头,然后是“:”字符,然后是一个或多个数字,然后是字符串末尾(这是您要匹配的格式)的任何字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.