开发者

Scan string for special characters and alphabets

I have a text开发者_运维问答box which accepts time (max of 5 chars) in the format hh:mm or hhmm. 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.

<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()? 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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜