onkeyup and onfocusout is not working in jQuery Va

2020-01-27 08:10发布

问题:

I am using jQuery Validate plugin for the validation purpose. I have to real time validation on the form. For example if a first name is required, then user should get the required message for first time and goes when he start to type in the text box.

To achieve this functionality I am using on onkeyup and onfocusout options of the plugin. For this I refer this link who has the same issue.

Here is my coffeescript code for form validation

defaultPageForm: (self)->
      form = $("#PageForm")
      if form.length > 0
        form.find('textarea').on 'click', -> $(@).valid()
        form.find('input').on    'click', -> $(@).valid()
        form.validate    

          ignore: ".ignore"                        
          rules:
            "view[name]":
              required: true
              NameWordCount: [3]


            "view[comment]":
              required: true
              CommentWordCount: [5]

            accept_terms: "required"

          messages:
            "view[comment]": "Please add comment"

          errorElement: "span"
          errorClass: "error_msg wide "
          errorPlacement: (error, element) ->
            element.siblings(".view_form_error_msg").remove()
            error.appendTo element.closest(".controls")              
            return

          ###### Real time validation code #############
          onkeyup: (element) -> 
            $(element).valid()  
            return        

          onfocusout: (element) -> 
            $(element).valid()  
            return 

          submitHandler: (form) ->
            self._setupData()
            self._submitForm(form)
            off

      return

But it not working fine. For example for testing purpose I added alert message under onkeyup but is nothing pop up also it not applying realtime validation.

Is there anything I am missing. Here is my html

<input type="text" value="as as" size="50" placeholder="Full Name" name="view[name]" id="customerName" class="string required wide" style="font-size: 20.4572px; line-height: 49px;">

So how can I resolve this issue.

回答1:

You would never use the .valid() method within the .validate() method. Refer to the source code of onkeyup and onfocusout to see how it's done.

Use this.element(element) instead of $(element).valid()

To over-ride the default functionality ("lazy validation") of onkeyup and onfocusout and use "eager" validation instead...

$('#myform').validate({
    onkeyup: function(element) {
        this.element(element);  // <- "eager validation"
    },
    onfocusout: function(element) {
        this.element(element);  // <- "eager validation"
    }
    ....

DEMO: http://jsfiddle.net/ajy5j8jq/