Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

from the validate documentation under remote method

    remote: {
      url: "check-email.php",
      type: "post",
      data: {
        username: function() {
         return $("#username").val();
        }
      }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top