我需要创建一个JS函数,允许用户使用这些req:
在输入字段中输入单词字符串最大长度为30个字符
onkeyup: return .split(' ').filter(
function(what) {
return /[\w\d]/.exec(what) != null && what.length <= 10 ? what : ''
}
).join('').length > 0
答案 0 :(得分:0)
是否有必要使用正则表达式?
function isValid(str, maxlength, maxWordLength)
{
if ( !str || str.length > maxlength ) //if the string is not null and length greater than max length
{
return false;
}
var strArr = str.split(/(\s+)/); //okay a bit of regex here :) to split by white space
return strArr.some( function(value){ return value.length > maxWordLength } ); //if any value inside this array has value greater than maxWordLength
}
console.log( isValid( "asdas as", 30, 10 ) );
您可以通过
在文本框的keyup事件上执行此操作$( "#elementId" ).bind( "keyup", function(){
isValid( $( this ).val(), 30, 10 );
} );
纯js
document.getElementById( "elementId" ).addEventListener ("keyup", function(){
isValid( this.value, 30, 10 );
} );