簡體   English   中英

jQuery Validator最小必需字

[英]jQuery Validator Minimum Required Words

我正在尋找一種方法來使用jQuery驗證一些輸入textareas - 不幸的是,因為jQuery驗證器插件很棒,它缺乏驗證(據我所知)“最低要求的單詞”。 我沒有代碼(我早上會編輯),但是我編寫了一個函數來計算輸入中的單詞,但這不是像插件提供的那樣干凈的驗證。

我也查看了word-and-character-count.js,但是為了提交表單,這也沒有提供最小字數。

編輯:我提供的答案是一個自定義驗證方法 - 如果有人知道任何更清潔的方法,甚至一個易於使用的插件,請告訴我。

獲取實時字數的功能,不包括末尾的空格(簡單地分割將計算word (注意末尾的空格)為2個單詞。

function getWordCount(wordString) {
  var words = wordString.split(" ");
  words = words.filter(function(words) { 
    return words.length > 0
  }).length;
  return words;
}

//add the custom validation method
jQuery.validator.addMethod("wordCount",
   function(value, element, params) {
      var count = getWordCount(value);
      if(count >= params[0]) {
         return true;
      }
   },
   jQuery.validator.format("A minimum of {0} words is required here.")
);

//call the validator
selector:
{
    required: true,
    wordCount: ['30']
}

暫無
暫無

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

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