簡體   English   中英

添加驗證,不允許使用jQuery字數提交表單

[英]add validation and not allow form submit with jQuery word count

我有一個文本區域,其中不能超過100個字。 我找到了一個不錯的指示器腳本,該腳本可以倒計時頁面上的單詞,但是如果用戶鍵入的單詞超過100個,它仍然允許用戶提交。 我需要整合一個驗證。 注意:我在其他地方使用validate.js。

$(document).ready(function() {
    $("#word_count").on('keyup', function() {
        var words = this.value.match(/\S+/g).length;
        if (words > 100) {
            // Split the string on first 100 words and rejoin on spaces
            var trimmed = $(this).val().split(/\s+/, 100).join(" ");
            // Add a space at the end to keep new typing making new words
            $(this).val(trimmed + " ");
        }
        else {
            $('#display_count').text(words);
            $('#word_left').text(100-words);
        }
    });
 });  

您為什么不只將最大長度屬性添加到文本區域? 是否符合您的要求?

http://www.w3schools.com/tags/att_textarea_maxlength.asp

不,這不是因為計算字符而不是單詞。 但是,如果您應用該腳本,則會修剪文本並僅使用前100個單詞。 該行是

var trimmed = $(this).val().split(/\s+/, 100).join(" ");

極限是100

這是我的答案

 $.validator.addMethod("wordCount", function(value) {
            var words = value.match(/\S+/g).length;
            return words < 100;
        }, 'You can enter max 100 words');

        $("#form").validate({
            rules: {
                textarea : "wordCount"
            }
        });

而html是

 <form name="form" id="form" method="get" >
     <textarea name="textarea" ></textarea>
     <input type="submit" value="submit" onclick="return $('#form').valid()" />
 </form>

一種快速而骯臟的技巧是從$('#display_count')獲取文本,將其轉換為數字,然后查看其是否大於或等於100,然后停止提交表單。 由於您使用的是jQuery驗證插件 (假定),因此您可以執行以下操作:

$(".myForm").validate({
  submitHandler: function(form) {
      var total = parseInt($('#display_count').text(), 10);
      if ( total >= 100 ) {
          alert ("Max limit reached");
          return;
      }
      $(form).submit();
  }
});

有關此小提琴的更多信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM