首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在文本区域中添加最小250和最大1000字数的验证?

如何在文本区域中添加最小250和最大1000字数的验证?
EN

Stack Overflow用户
提问于 2018-12-27 18:25:48
回答 2查看 1.6K关注 0票数 0

我试图添加jquery验证在文本区的最低250字和最多1000字。并且还在文本区域旁边的span标签中显示字数。此外,我还可以如何验证,如果用户复制粘贴到文本区,那么这个验证也应该工作。任何帮助和建议都应该受到感谢。

代码语言:javascript
复制
var maxWords = 1000;
var minWords = 250;

$(document).on('keypress', 'textarea[name="writ"]', function(e) {
  var $this, wordcount;

  $this = $(this);
  wordcount = $this.val().split(/\b[\s,\.-:;]*/).length;
  if (wordcount > maxWords) {
    $('.writing_erorr').text("You've reached the maximum allowed words 1000.");
    return false;
  } else {
    return $('#writing span').text('Total words: ' + wordcount);
  }
});

$("textarea[name='writ']").bind('paste', function(e) {
  // access the clipboard using the api
  var pastedData = e.originalEvent.clipboardData.getData('text');
  alert(pastedData);
  var $this, wordcount;

  $this = $(this);
  wordcount = $this.val().split(/\b[\s,\.-:;]*/).length;
  if (wordcount > maxWords) {
    $('.writing_erorr').text("You've reached the maximum allowed words 1000.");
    return false;
  } else {
    return $('#writing span').text('Total words: ' + wordcount);
  }
});
代码语言:javascript
复制
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id=writing class=cond>
    <label class="required">Writing Entry</label>
    <textarea name=writ placeholder="Writing Entries: 100 words min, 600 words max"></textarea>
    <span></span>
    <div class="writing_erorr"></div>
</div>

EN

回答 2

Stack Overflow用户

发布于 2018-12-27 18:51:07

下面的代码按要求工作,我给文本区添加了一些属性,这样你就可以在一个页面上有多个文本区,每个文本区都有不同的限制。

您需要添加以下属性word-limit="true"max-words='n'min-words='n'。不再需要占位符,因为代码会在页面加载后自动生成一个占位符。

它比你的例子稍微复杂一些,但允许你做更多的事情(不确定你的整个项目是什么)。

字数统计

进行字数统计的基本代码如下:

代码语言:javascript
复制
wordCount = $.trim( $("#writing").val() ).split(/\s+/).filter(Boolean).length;

代码的解释:

  • $("#writing").val() -获取文本区域的值(例如,string)
  • .trim()删除string
  • .split(/\s+/)开头或末尾的所有空格,在每个空格周围分割字符串并将其放入array
  • .filter(Boolean)中)跳过数组中的任何空值-即,由double spacing
  • .length创建的值获取数组的长度(即,有多少个单词)

演示

代码语言:javascript
复制
// Cycle through each textarea and add placeholder with individual word limits
$("textarea[word-limit=true]").each(function() {
  $(this).attr("placeholder", "Writing entries: " + $(this).attr("min-words") + " words min, " + $(this).attr("max-words") + " words max");
});


// Add event trigger for change to textareas with limit
$(document).on("input", "textarea[word-limit=true]", function() {


  // Get individual limits
  thisMin = parseInt($(this).attr("min-words"));
  thisMax = parseInt($(this).attr("max-words"));

  // Create array of words, skipping the blanks
  var removedBlanks = [];
  removedBlanks = $(this).val().split(/\s+/).filter(Boolean);
  
  // Get word count
  var wordCount = removedBlanks.length;
 
  // Remove extra words from string if over word limit
  if (wordCount > thisMax) {
        
      // Trim string, use slice to get the first 'n' values
      var trimmed = removedBlanks.slice(0, thisMax ).join(" ");
      
      // Add space to ensure further typing attempts to add a new word (rather than adding to penultimate word)
      $(this).val(trimmed + " ");
      
    }
    
 
  // Compare word count to limits and print message as appropriate
  if ( wordCount < thisMin) {
  
    $(this).parent().children(".writing_error").text("Word count under " + thisMin + ".");
  
  } else if (wordCount > thisMax) {

    $(this).parent().children(".writing_error").text("Word count over " + thisMax + ".");
  
  } else {
    
    // No issues, remove warning message
    $(this).parent().children(".writing_error").text("");

  }

});
代码语言:javascript
复制
.writing_error {
  color: red;
}

[id^=writing] {
  border-bottom: 1px solid grey;
  margin-bottom: 20px;
  padding-bottom: 20px;
}

label {
  width: 100%;
}

textarea {
  width: 100%;
  margin-top: 4px;
}
代码语言:javascript
复制
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id=writing1 class=cond>
  <label class="required">Writing Entry 1</label>
  <textarea name=writ word-limit="true" max-words="600" min-words="100"></textarea>
  <span></span>
  <div class="writing_error"></div>
</div>


<div id=writing2 class=cond>
  <label class="required">Writing Entry 2</label>
  <textarea name=writ></textarea>
  <span></span>
  <div class="writing_error"></div>
</div>

<div id=writing3 class=cond>
  <label class="required">Writing Entry 3</label>
  <textarea name=writ word-limit="true" max-words="10" min-words="4"></textarea>
  <span></span>
  <div class="writing_error"></div>
</div>

票数 1
EN

Stack Overflow用户

发布于 2018-12-27 18:30:22

在你的javascript中:

代码语言:javascript
复制
$('textarea#message_area').on('keyup',function() 
{
  var maxlen = $(this).attr('maxlength');

  var length = $(this).val().length;
  if(length > (maxlen-10) ){
    $('#textarea_message').text('max length '+maxlen+' characters only!')
  }
  else
    {
      $('#textarea_message').text('');
    }
});

元素:

代码语言:javascript
复制
<form>
  <label for="message_area">No more than 100 characters</label>
  <p>
  <textarea id="message_area" maxlength="100" rows="6" cols="70"></textarea>
  </p>
  <span class="hint" id="textarea_message"></span>
</form>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53943446

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档