views:

45

answers:

1

to custom validate an input i wrote a script:

function cardNumberCheck(value, element) {
        var res = false;
        $.get("/CaseHistories/ValidateCardNumber",
  { caseHistoryId: $('#CaseHistory_Id').val(), cardNumber: $('#CaseHistory_CardNumber').val() },
   function(data) { res = data });
      //alert(res) => works fine return true/false
        return res;
    }

    $.validator.addMethod("cardValidate",
 cardNumberCheck, "invalid");


    if ($('#CaseHistory_CardNumber').is("form *")) { //<= check if elem is in a form
        $('#CaseHistory_CardNumber').rules("add", {
            required: true,
            cardValidate: true,
            messages: {
                required: "*",
                cardValidate: "invalid"
            }
        });
    }

EDIT: the required rule works fine, but my validation method doesn't dispalt the message.
and the submit works even if the elements data havent passed the cardNumberCheck validation

whats not right here?

+1  A: 

This portion:

$.get("/CaseHistories/ValidateCardNumber",
  { caseHistoryId: $('#CaseHistory_Id').val(), 
    cardNumber: $('#CaseHistory_CardNumber').val() },
  function(data) { res = data });
    //alert(res) => works fine return true/false
    return res;
}

is asynchronous, it is returning undefined because that success function doesn't run until later, when the server responds with data (no matter how fast, it's after your JavaScript moves on for sure). It alerts ok because the alert happens later actually, because it's triggered when the data comes back...after the validate code has run. To do a synchronous callback, you need to do this instead:

function cardNumberCheck(value, element) {
  var res;
  $.ajax({
    async: false,
    url: "/CaseHistories/ValidateCardNumber",
    data: { caseHistoryId: $('#CaseHistory_Id').val(), 
            cardNumber: $('#CaseHistory_CardNumber').val() },
    success: function(data) { res = data });
  }
  return res;
}
Nick Craver
I did it synchronous as you sad. but the validation message still doesnt display.whats wrong with it? have any clues?
CoffeeCode
and the it still submit data even if the cardNumberCheck return true or false
CoffeeCode
@CoffeeCode - If you do replace `return res;` with `alert(res); return res;` does it alert true, false, or undefined?
Nick Craver
it alert true/ false
CoffeeCode
dont mind the last comment i found the problem
CoffeeCode