如何在至少250个字词和最多1000个字数的文本区域中添加验证?

时间:2018-12-27 10:25:48

标签: javascript jquery html validation

我正在尝试在文本区域字段中添加至少250个单词和最多1000个单词的jquery验证。并在文本区域旁边的span标签中显示字数。另外,我还如何验证用户是否将复制粘贴到文本区域中,所以该验证也应该有效。任何帮助和建议都应该感谢。

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

2 个答案:

答案 0 :(得分:1)

下面的代码按要求工作,我在文本区域中添加了一些属性,以便您可以在单个页面上具有多个文本区域,所有区域都有不同的限制。

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

与您的示例相比,它涉及更多一点,但允许您做更多的事情(不确定您的总体项目是什么)。


字数

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

wordCount = $.trim( $("#writing").val() ).split(/\s+/).filter(Boolean).length;

代码说明:

  • $("#writing").val()-获取textarea的值(即字符串)
  • .trim()删除字符串开头或结尾的所有空格
  • .split(/\s+/)在每个空格周围分割字符串,并将它们放入数组中
  • .filter(Boolean)跳过数组中的所有空白值-即由双倍间距创建的空白值
  • .length获取数组的长度(即,有多少个单词)

演示

// 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("");

  }

});
.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;
}
<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 :(得分:0)

在您的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('');
    }
});

元素:

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