开发者

jquery validation problems

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: "*",
                card开发者_运维百科Validate: "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?


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜