【问题标题】:Javascript: Input validation [closed]Javascript:输入验证
【发布时间】:2015-12-30 12:50:34
【问题描述】:

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

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

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

【问题讨论】:

  • 你能告诉我们你到目前为止取得了什么成就吗?
  • 如果您能向我们展示您迄今为止所做的工作,我们应该能够为您提供帮助。

标签: javascript regex


【解决方案1】:

有必要使用正则表达式吗?

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

} );

【讨论】:

  • @Markoo08 所以在keyup处理程序中调用isValid
  • @Markoo08 如果还有问题,然后创建一个小提琴并分享网址
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-17
  • 2015-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-29
相关资源
最近更新 更多