我有一个带有文本框的页面,用户应该在其中输入一个24个字符(字母和数字,不区分大小写)的注册代码。我使用maxlength来限制用户输入24个字符。
注册代码通常是用破折号分隔的一组字符,但我希望用户输入的代码不带破折号。
我怎么能写我的JavaScript代码没有jQuery检查用户输入的给定字符串不包含破折号,或者更好的是,只包含字母数字字符?
我有一个带有文本框的页面,用户应该在其中输入一个24个字符(字母和数字,不区分大小写)的注册代码。我使用maxlength来限制用户输入24个字符。
注册代码通常是用破折号分隔的一组字符,但我希望用户输入的代码不带破折号。
我怎么能写我的JavaScript代码没有jQuery检查用户输入的给定字符串不包含破折号,或者更好的是,只包含字母数字字符?
当前回答
如果你在变量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/
你可以使用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 >
ES6在String的原型中包含了内置的方法(includes),可以用来检查String是否包含另一个字符串。
var str =“生存,还是毁灭,这是一个问题。”; console.log (str。包括(','));
下面的polyfill可用于在不受支持的浏览器中添加此方法。(源)
if (!String.prototype.includes) { String.prototype.includes =函数(搜索,启动){ 使用严格的; If (typeof start !== 'number') { Start = 0; } 如果(开始+搜索。长度> this.length) { 返回错误; }其他{ 返回。indexOf(search, start) ! } }; }
var inputString = "this is home"; Var findme = "home"; if (inputString.indexOf(findme) > -1) { Alert(“找到了”); }其他{ Alert(“未找到”); }
String的搜索函数也很有用。它搜索给定字符串中的字符和sub_string。
'apple'.search('pl')返回2
'apple'.search('x')返回-1