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