L
L
Lesha Fedoseev2014-02-17 16:02:27
JavaScript
Lesha Fedoseev, 2014-02-17 16:02:27

How to return value from asynchronous ajax request for jQuery Validation plugin required method?

I'm using the jQuery Validation plugin (JVP) to validate forms through ajax requests to the server. Everything works fine except for one thing: JVP does not remotely validate empty fields.

I don't mind using the plugin's default rule requiredwithout requests to the server, but I would like to implement such a validation. Yes, and I want to solve the problem)

So, the problem is: JVP does not validate empty fields through its built-in remote. But I can use functions in its requiredmethod:

required: function(element) {
  return true_or_false;
}

I decided to pull an asynchronous ajax request inside this function, but I can't give it the value received from the server. Here is the code (CoffeeScript):
validate_url = '/emails/validate'

required_validate = (e, callback) ->
  data = {}
  data[e.name] = $(e).val()
  $.ajax(
    url: validate_url
    type: 'post'
    dataType: 'json'
    data: data
    success: (response) ->
      callback(response)
  )

$('#my_form').validate(
  rules:
    'email[email]':
      required: (element) ->
        required_validate(element, (response) ->
          if response == true || response == "true"
            false
          else
            true
        )
)

I checked the data that goes to the server, and his answer is that everything is ok with them. The problem is that the requiredJVP method does not wait for a response from the server and receives it trueearlier.

How can I return this answer to him?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
H
himik, 2014-02-17
@himik

try
to make a request

M
mayorovp, 2014-02-19
@mayorovp

Answer: no way. By the time the request ends, the required function has already completed its execution a long time ago.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question