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

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

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


当前回答

试试这个:

if ('Hello, World!'.indexOf('orl') !== -1)
    alert("The string 'Hello World' contains the substring 'orl'!");
else
    alert("The string 'Hello World' does not contain the substring 'orl'!");

这里有一个例子:http://jsfiddle.net/oliverni/cb8xw/

其他回答

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

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

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

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

<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>

你可以使用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 >

在your_string中查找"hello"

if (your_string.indexOf('hello') > -1)
{
  alert("hello found inside your_string");
}

对于alpha数值,您可以使用正则表达式:

http://www.regular-expressions.info/javascript.html

数值正则表达式

includes()方法确定数组在其条目中是否包含某个值,根据需要返回true或false。

const array1 = [1, 2, 3];

console.log(array1.includes(2));
// expected output: true

const pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));
// expected output: true

console.log(pets.includes('at'));
// expected output: false

知道更多