Mark Mintoff My superpower is common sense

18Dec/102

Ajax Server Side Validation

There are times you would want to do some sort of server-side validation on a form. As an example, you might want to validate a user's login credentials. In my case, the reasons for developing this validation wrapper, were to ensure that an ID was populated on the server, before allowing my Wizard to proceed to the next step. My opinion of ASP.Net's CustomValidator is that it is, quite frankly; horse shit. So, as per usual, I set about making my own way. My requirements were as follows:
  • User clicks "Next" (or Submit) button
  • Server checks if ID is populated
  • Server returns this information
  • If ID is not populated, prevent moving to the next step
  • If ID is populated, allow moving to the next step
Clearly Ajax had to be used here, and I opted to use JQuery's $.ajax as I find it to be absolutely splendid. The secret to achieving the functionality we want, is to set the async property to false. The reason being that with the async property set to true, Ajax will behave as Ajax is supposed to behave. In our case we do not want Ajax to behave normally, as the form would submit while the Ajax call was being made. As is my style, I decided to create a wrapper functionality, making the whole thing rather generic and fun to use: The way this works is that it makes a call to the path which you give it, passes the data which you give it and depending on the server's response, will execute one of the functions (successEvent / failEvent) you passed to it. Meanwhile on C#'s back-end: This is pretty self explanatory, I won't insult your intelligence and explain what it does :) And to use this method on your page? Simple: If you're curious about the String.Format, please refer to here. And that's all there is to it! The process goes like this:
  • User clicks button
  • The click function we binded is fired
  • The ValidationEvent function is fired
  • Ajax call is made to server using our details
  • Depending on the response from the server, the success or fail events are executed
  • In my case, I only passed a failure function; TemplateValidationFailure
And that's all there is to it!
VN:F [1.9.22_1171]
Rating: 0.0/5 (0 votes cast)
Comments (2) Trackbacks (0)
  1. Can I ask why you use the .bind() function rather than the .click(function(){/*my code*/}); ? Is there an advantage using it?

    • I prefer using bind, because you might want to do it on a different kind of event, such as “mouseover”, and as far as I know there aren’t specific methods for those. I might be wrong. Also, I just like this way more hehe


Cancel reply

No trackbacks yet.