日期:2014-05-16  浏览次数:20342 次

JS正则验证字符串的语法问题
HTML code

<html>
    <head>
        <title>字符串格式检验</title>
        <script>
            function checkStrFormat(str)
            {
                if(/^([a-zA-Z_]{1})([\w]*)$/g.test(this.value))
                {
                    alert("just letter is permitted"); // 报警提示语句。
                }
            }
        </script>
    </head>
    <body>
        <form name="timeForm" action="resultOK.html">
                <input type="text" onblur="checkStrFormat(this.value)">
      </form>
    </body>
</html>



代码如上图所示。
代码需要限制字符串只能以字母开头,内容可以包含数字,字母,下划线。
结果现在是输入什么内容都会执行alert语句。
不知道问题出在哪里。请指教。

------解决方案--------------------
探讨

if(/^([a-zA-Z_]{1})([\w]*)$/g.test(this.value))应该是if(/^([a-zA-Z_]{1})([\w]*)$/g.test(str))

------解决方案--------------------
探讨
HTML code

<html>
<head>
<title>字符串格式检验</title>
<script>
function checkStrFormat(str)
{
if(/^([a-zA-Z_]{1})([\w]*)$/g.test(this.value))
……