Javascript:输入验证

Javascript: Input validation

本文关键字:验证 输入 Javascript      更新时间:2023-09-26

我需要创建一个JS函数,允许用户使用以下req:在输入字段中输入单词

  • 单词的最大长度为10个字符
  • 字符串的最大长度为30个字符

    onkeyup: return .split(' ').filter(
        function(what) {
            return /['w'd]/.exec(what) != null && what.length <= 10 ? what : ''
        }
    ).join('').length > 0
    

是否需要使用regex?

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 );
} );