我有一个带有文本框的页面,用户应该在其中输入一个24个字符(字母和数字,不区分大小写)的注册代码。我使用maxlength来限制用户输入24个字符。

注册代码通常是用破折号分隔的一组字符,但我希望用户输入的代码不带破折号。

我怎么能写我的JavaScript代码没有jQuery检查用户输入的给定字符串不包含破折号,或者更好的是,只包含字母数字字符?


当前回答

String的搜索函数也很有用。它搜索给定字符串中的字符和sub_string。

'apple'.search('pl')返回2

'apple'.search('x')返回-1

其他回答

仅测试字母数字字符:

if (/^[0-9A-Za-z]+$/.test(yourString))
{
    //there are only alphanumeric characters
}
else
{
    //it contains other characters
}

正则表达式正在测试0-9、A-Z和A-Z字符集中的一个或多个(+),从输入的开始(^)开始,到输入的结束($)结束。

你可以使用string.includes()。例子:

Var string = "lorem ipsum hello world"; Var include = "world"; var a = document.getElementById("a"); If (string.includes(include)) { Alert ("found '" + include + "' in your string"); a.innerHTML = " find '" + include + "' in your string"; } < p id = " " > < / p >

完美的工作。这个例子会很有帮助。

<script>    
    function check()
    {
       var val = frm1.uname.value;
       //alert(val);
       if (val.indexOf("@") > 0)
       {
          alert ("email");
          document.getElementById('isEmail1').value = true;
          //alert( document.getElementById('isEmail1').value);
       }else {
          alert("usernam");
          document.getElementById('isEmail1').value = false;
          //alert( document.getElementById('isEmail1').value);
       }
    }
</script>

<body>
    <h1>My form </h1>
    <form action="v1.0/user/login" method="post" id = "frm1">
        <p>
            UserName : <input type="text" id = "uname" name="username" />
        </p>
        <p>
            Password : <input type="text" name="password" />
        </p>
        <p>
            <input type="hidden" class="email" id = "isEmail1" name = "isEmail"/>
        </p>
        <input type="submit" id = "submit" value="Add User" onclick="return check();"/>
    </form>
</body>

如果你在变量foo中有文本:

if (! /^[a-zA-Z0-9]+$/.test(foo)) {
    // Validation failed
}

这将测试并确保用户至少输入了一个字符,并且只输入了字母数字字符。

使用ES6 MDN docs .includes()

"FooBar".includes("oo"); // true

"FooBar".includes("foo"); // false

"FooBar".includes("oo", 2); // false

E: IE不支持-相反,你可以使用波浪号操作符~(按位Not)和.indexOf()

~"FooBar".indexOf("oo"); // -2 -> true

~"FooBar".indexOf("foo"); // 0 -> false

~"FooBar".indexOf("oo", 2); // 0 -> false

与数字一起使用,波浪符有效 ~ n => -(n +1)。用双重否定!!(逻辑不)转换bool中的数字:

!!~"FooBar".indexOf("oo"); // true

!!~"FooBar".indexOf("foo"); // false

!!~"FooBar".indexOf("oo", 2); // false