jquery validation word count integration

天大地大妈咪最大 提交于 2019-12-13 06:12:46

问题


How can I integrate word count into bassistance.de validation? For example, i dont want people to enter more than 50 words, and it should show an error to indicate it.

<form action="done.php" method="post" id="mainform"  class="validate">
<textarea name="message" rows="4" id="message"  class="required" ></textarea>   
</form>

Here is all I have, but i dont know where to go from here

$(document).ready( function() {
$("form.validate").validate({
    submitHandler: function(form) {
               form.submit();
    }
})

});

any assistance here would be appreciated, i'm not familiar with this plugin at all.


回答1:


I would go with a minimum charachter count, based on what you think is the average word length (I still stand behind 5). So that would be:

$("#mainform").validate({
  rules: {
    message: {
      required: true,
      minlength: 250
    }
  }
});

Update:

If ajax is an option, you could use the remote rule. I think it would along the lines of:

$("#test").validate({
    rules: {
        message: {
            remote: {
                url: "check_wordcount.php",
                type: "post",
                data: {
                    wordcount: 5
                }
            }
        }
    }
}

I'm having some issues with it, with the timing, but I think some of that is just me rushing things, but it does work. In this case, the remote script must return true for the element name, so my php script looks like:

$message = $_POST['message'];
$wordcount = (int) $_POST['wordcount'];
$valid = (str_word_count($message) >= $wordcount);

echo json_encode(array('message' => $valid));



回答2:


Here is another solution that adds a custom rule to the validator a simple, reusable, clean way to get the job done.

$.validator.addMethod("wordCount", function(value, element, wordCount) {

    return value.split(' ').length <= wordCount;

}, 'Exceeded word count');'Exceeded word count of ' + len + ' or less');

How to use it

rules: {
  fieldName: { 
    required: true,
    wordCount: 300
  }
},
messages: {
  fieldName: { 
    required: 'Statement of justification is required',
    wordCount:'Please shorten to 300 words or less.'
  }
}



回答3:


go through http://roshanbh.com.np/2008/10/jquery-plugin-word-counter-textarea.html

or if you jus want to count a word length use

   var myLength = $("#myTextbox").val().length;

$("#mytextbox") finds the textbox by its id.

.val() gets the value of the input element entered by the user, which is a string.

.length gets the number of characters in the string. and in any event you can check it and give alert msg.



来源:https://stackoverflow.com/questions/10084673/jquery-validation-word-count-integration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!