我有一个带有文本框的页面,用户应该在其中输入一个24个字符(字母和数字,不区分大小写)的注册代码。我使用maxlength来限制用户输入24个字符。
注册代码通常是用破折号分隔的一组字符,但我希望用户输入的代码不带破折号。
我怎么能写我的JavaScript代码没有jQuery检查用户输入的给定字符串不包含破折号,或者更好的是,只包含字母数字字符?
我有一个带有文本框的页面,用户应该在其中输入一个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/
其他回答
使用正则表达式来实现这一点。
function isAlphanumeric( str ) {
return /^[0-9a-zA-Z]+$/.test(str);
}
如果你在变量foo中有文本:
if (! /^[a-zA-Z0-9]+$/.test(foo)) {
// Validation failed
}
这将测试并确保用户至少输入了一个字符,并且只输入了字母数字字符。
试试这个:
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/
var inputString = "this is home"; Var findme = "home"; if (inputString.indexOf(findme) > -1) { Alert(“找到了”); }其他{ Alert(“未找到”); }
这对我很有效!
属性包含选择器[name*= " value "]
这是针对值匹配的最慷慨的jQuery属性选择器。如果选择器的字符串出现在元素的属性值内,它将选择一个元素。将此选择器与Attribute Contains Word选择器进行比较(例如[attr~=" Word "]),后者在许多情况下更合适。
来源:Attribute Contains Selector [name*= " value "] => https://api.jquery.com/attribute-contains-selector/
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>attributeContains demo</title>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
<input name="man-news">
<input name="milkman">
<input name="letterman2">
<input name="newmilk">
<script>
$( "input[name*='man']" ).val( "has man in it!" );
</script>
</body>
</html>