What is the proper way to do multi-parameter AJAX form validation with jQuery and ASP.NET MVC?

亡梦爱人 提交于 2019-12-25 03:13:13

问题


I have a registration form for a website that needs to check if an email address already exists for a given company id. When the user tabs or clicks out of the email field (blur event), I want jQuery to go off and do an AJAX request so I can then warn the user they need to pick another address.

In my controller, I have a method such as this:

public JsonResult IsEmailValid(int companyId, string customerNumber)
{            
  return Json(...);
}

To make this work, I will need to update my routes to point directly to /Home/IsEmailValid and the two parameters {companyId} and {customerNumber}. This seems like I'm "hacking" around in the routing system and I'm guessing perhaps there is a cleaner alternative.

Is there a "proper" or recommended way to accomplish this task?

EDIT: What I meant by the routes is that passing in extra parameter ({customerNumber}) in the URL (/Home/IsEmailValid/{companyId}/{customerNumber}) won't work with the default route mapping.


回答1:


You can use the jQuery Validation Plugin to do that.

You're gonna have to implement your own method though like this :

$.validator.addMethod("checkCompanyEmail", function(value, element) {
    var email = value;
    var companyID = //get the companyID
    var result;
    //post the data to server side and process the result and return it
    return result;
}, "That company email is already taken.");

Then register your validation method :

$("#the-form").validate({
   rules: { email: { required: true, "checkCompanyEmail" : true } } 
});

PS. I don't understand why you need to "hack around" with routing for that.




回答2:


from the validate documentation under remote method

    remote: {
      url: "check-email.php",
      type: "post",
      data: {
        username: function() {
         return $("#username").val();
        }
      }
    }


来源:https://stackoverflow.com/questions/1615144/what-is-the-proper-way-to-do-multi-parameter-ajax-form-validation-with-jquery-an

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