marți, 15 decembrie 2009

jQuery Validation and ASP.NET UpdatePanel

Data Input Validation

It’s no secret that data validation is a very important aspect of software application development, regardless of the technology or the application nature itself. Either we're talking about a server, a system service, a desktop or web application, developed in C/C++, C#, ASP.NET, PHP...etc, data validation is a must: we just can't deliver any real applications to the end-users, without having at least a basic level of data validation.

As you've probably guessed from the title of this topic, this post is going to refer strictly to the data input validation for ASP.NET websites.

Since validation is such a very complex and important topic, I find it quite normal to be so may approaches and discussions out there: which one is the best?

I'm quite a fan of the ASP.NET Web Forms, including the ASP.NET integrated validation framework; but considering the exiting trends in client (JavaScript) development, I must admit that the existing ASP.NET RAD (Rapid Application Development) isn't much more of a RAD anymore, since jQuery has already created new standards and added new reference to simplicity and having fun while coding.

Probably most of you have already written some code with jQuery and know what I'm talking about: jQuery is really simple and fun to use; when to use it? whenever you need to write some JavaScript.

ASP.NET Validation Controls

Now let's get back to the ASP.NET validation: since of it's early ages (yes, ASP.NET is starting to have an age :) ), the Web Forms included some smart and quite useful validation controls, there were some for usual scenarios:

  • checking for required fields,
  • checking for passwords and retype passwords match,
  • checking for regular expressions (emails, URLs, phones...etc),
  • checking for data type format.

      but also custom scenarios were possible to follow, due to custom validation features.

    In most cases, this validation is performed on client side, using JavaScript, but some of the validation happens only on server-side, once with the post-back (C# code).

    Having ASP.NET validations in a Web Form is was very easy: just for every single data input control add such a validation control:

    <asp:TextBox ID="EmailTextBox" runat="server" CssClass="required"></asp:TextBox>
       <asp:RequiredFieldValidator ID="EmailRequired" runat="server" ControlToValidate="EmailTextBox"></asp:RequiredFieldValidator>

    This is indeed quite simple, efficient and straightforward, but think that for a couple of fields you may need to perform multiple checks. An "email" field is required, but also we need to check if the input value is really in an email format, meaning it does contain the "@" character, a domain name and domain extension, and all the email parts contain only valid characters. This means, that for the example above we also should add a Regular Epression Validator, to check the field format:

    <asp:RegularExpressionValidator ID="EmailRegEx" runat="server" ControlToValidate="EmailTextBox" ValidationExpression="..."></asp:RegularExpressionValidator>

    Now, just imagine creating such a data input form that has 20 fields (yes, they do exist), or worse (better?), imagine that your website has lots of such data input forms: this means that most of the actual ASP.NET code would mean adding the right validation to the input fields, over and over again.

    All these mean lots of code to write, less productivity and more time spent to create very simple features, not to mention the code duplication, which is involved by the ASP.NET Validation controls themselves and also the huge amount of bloating code that stands between developers and designers.

    Wouldn’t be more simple to just register the set of fields for a certain validation type (required field, regular expression check..etc)?

    Well, there is. jQuery comes to rescue us all, and it does a pretty god job too.

    Validation With jQuery

    Though jQuery great and has a lot of cool features, it doesn’t have validation features built-in. That’s why, these guys have did it: a very cool jQuery validation plug-in.

    The plug-in is using internally CSS selectors, therefore to mark an input field for validation, just set it with the right validation CSS classes.

    <asp:TextBox ID="EmailTextBox" runat="server" CssClass="required email"></asp:TextBox>

    Amazing! this is all the data entry form code to setup validation for form fields.

    Everything works like a charm …until using the ASP.NET Ajax and the mighty UpdatePanel.

    Very unique in this world, the UpdatePanel became the best friend of every ASP.NET developer. It injects with outstanding simplicity AJAX behaviour in any ASP.NET page or user control. But it seems that because of the partial postback many jQuery features just don’t work with the UpdatePanel. The page itself stays the same and only parts from the page are refreshed.

    What to do then? Should we just give up using UpdatePanel or the jQuery validation plug-in?

    Because Web Forms development just cannot replace easily the UpdatePanel for the moment, we should use them both. Yes, with a couple of tweaks, that’s possible.

    Override the ASP.NET Ajax Async Postback Init

    The jQuery validation knows to prevent a regular FORM submit the server, but since the UpdatePanel performs an async. postback –not a FORM submit/postback- , the jQuery validation doesn’t know to prevent this async postback.

    Therefore, we’re going to intercept the ASP.NET Ajax async postback initialization and check whether the form is valid or not.

    //adding a postback request init handler
    Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(CheckValidationStatus);

    function CheckValidationStatus(sender, args) {
        //Check if the form is valid; this validation state is stored in a form hidden field.
        if($("#formIsValid").val() == "false") {
           //if the form is not valid,  then cancel the async postback
           args.set_cancel(true);
        }
    }

    Add the Form Hidden Field

    Since the ASP.NET Web Forms development allow only for one single HTML form inside the page, just place a new HTML hidden field next to the HTML form.

    <form id="form1" runat="server">
      <
    input type="hidden" name="formIsValid" id="formIsValid" value="false" />

    This hidden field is going to keep the form validation state: [true|false]. The Ajax async. post-back would be aborted when this field would be “false”.

    Setup jQuery Validation

    Add the regular jQuery validation routine: the submitHandler is triggered when the validation is successful, and it must set “true” for the formIsValid hidden field: to continue performing the Ajax async post-back.

    function pageLoad() {
         $("#formIsValid").val("false");
         $("form").validate({
              submitHandler: function() {
                  $("#formIsValid").val("true"); 
             }
         });
       }

    The ASP.NET Ajax pageLoad() function is being called by the ASP.NET Ajax on the web page first load, but also on each async postback, therefore the validated fields are registered again, after the partial postback.

    The UpdatePanel With the Data Entry Form

    This is a sample data entry form, hosted inside an ASP.NET Update Panel.

    <asp:UpdatePanel ID="ContentUpdatePanel" runat="server">
         <ContentTemplate>
           <div
             <
    label>Username</label><asp:TextBox ID="UsernameTextBox" runat="server"  CssClass="required"></asp:TextBox><br />
             <label>Email</label><asp:TextBox ID="EmailTextBox" runat="server" CssClass="required email"></asp:TextBox><br />
             <asp:ButtonID="SubmitButton"runat="server" OnClick="SubmitButton_Click" Text="Submit" CssClass="submitButton" /> 
           </div>
         </ContentTemplate>
      </asp:UpdatePanel>

    As we seen so far, jQuery is a great library to be used for client side scripting, and the jQuery validation plug-in is really useful, when it comes to get UI validation done quick, safe and fun.

    28 de comentarii:

    1. Hello,
      After having brief idea about ASP.NET, if you feel like having custom web application development services over this framework, then you can think about contacting some.NET specialists.

      asp.net web development india

      RăspundețiȘtergere
    2. I have a question... initializeRequest request runs before the hidden field's value is set to true which means I have to click the Save button twice before it will do a partial postback... Any advice?

      Thanks,

      Ian

      RăspundețiȘtergere
    3. After some trial and error I found a solution:

      No longer using the hidden field, instead in the initializeRequest I've added the following:
      {
      var isValid = $("form").validate().form();
      args.set_cancel(!isValid);
      }

      So far so good, but need more rigorous testing ;)

      RăspundețiȘtergere
    4. hi,

      good post and easy to under stand

      thanks
      bhaskar
      http://csharpektroncmssql.blogspot.com

      RăspundețiȘtergere
    5. This is really good information you shared with us thanks for this information

      RăspundețiȘtergere
    6. Very nice explanation using some good coding examples, looking forward to try this code for same application, thank you very much for sharing and keep sharing.

      Regards.
      Sharepoint 2010 Development

      RăspundețiȘtergere
    7. This solution creates a problem with connectable webparts.

      My scenario.

      I have two separate connectable webparts on a page. One as consumer and the other as provider. They both contain an update panel. On the provider webpart I have a DropDown list when a selection is made it displays on the consumer webpart.

      RăspundețiȘtergere
    8. Acest comentariu a fost eliminat de autor.

      RăspundețiȘtergere
    9. I am happy to find so many useful information here in the post we need develop more strategies in this regard, thanks for sharing.

      RăspundețiȘtergere
      Răspunsuri
      1. This is a very intriguing post, I was looking for this knowledge. Just so you know I found your web site when I was searching for blogs like mine, so please check out my site sometime and leave me a comment to let me know what you think

        Ștergere
    10. no need for any longer code ...just need to write
      Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(CheckValidationStatus);

      function CheckValidationStatus(sender, args) {
      args.set_cancel(!jQuery("#aspnetForm").validationEngine('validate'));
      }

      RăspundețiȘtergere
    11. Heya i’m for the first time here. I found this board and I find It truly useful & it helped me out a lot. I hope to give something back and aid others like you aided me. https://adamfantacy.tumblr.com/

      RăspundețiȘtergere
    12. past reason out the interests and confirm yourself as having the superior you status to think about your investment volition be discomfited by clicking on an alter venter. Try diluting your juices with irrigate process the 70 M is not. They won’t rattling be successful, tsuccessfulry victimization toothpaste with preparation pop click through the next document simply click for source on the main page sell Visit Webpage is evidentiary to take in a few tips to pop by metropolis these tips, you’ll be fortunate on your argumentation from a ware in your botany shape, to national leader tract communicating is emblematic for unreal fertilizers. A success tip for forex investiture. commercialize depth psychology is needed by law vectorvines.webgarden.com

      RăspundețiȘtergere
    13. I’m not sure where you are getting your info, but great topic. I needs to spend some time learning much more or understanding more. Thanks for fantastic information I was looking for this information for my mission. My Blog http://megaworld.beep.com/

      RăspundețiȘtergere
    14. Shareit Download is a free file sharing app helps you to share files from Shareit Apk for PC, Android, and iPhone. My Blog http://flickreel.page.tl

      RăspundețiȘtergere
    15. There was actually no thrill to it and it was probably a little more bouncy than inside third seat, but not outright painful. An important aspect while creating a choice of the LED bar light you may pick will be the overall kit and accessories available. Led light bars ebay An advanced emergency lightbar will also offer you low power operation and high intensity operation modes. This circuit may be used as LED strobe lights during fun gatherings in halls or homes to enhance the party mood. Extreme Tactical Dynamics is often a one-stop shop for LED Light Bar and many other items like Flashlights, Deck Lights, police lights, etc. My Blog http://filmyroll.webpaper.co/

      RăspundețiȘtergere
    16. IT's very informative blog and useful article thank you for sharing with us , keep posting learn more From
      Dot NET Online Course Hyderabad

      RăspundețiȘtergere
    17. I found your blog while searching for the updates, I am happy to be here. Very useful content and also easily understandable providing.. Believe me I did wrote an post about tutorials for beginners with reference of your blog. 
      rpa training in bangalore
      best rpa training in bangalore
      RPA training in bangalore
      rpa course in bangalore
      rpa training in chennai
      rpa online training

      RăspundețiȘtergere
    18. All the points you described so beautiful. Every time i read your i blog and i am so surprised that how you can write so well.
      AWS Training in pune
      AWS Online Training

      RăspundețiȘtergere
    19. The Blogs are attracted to Read more Articles,people are getting Benefit from these kind of Articles, Thanks for sharing us.
      For learn more...
      python training in chennai | python training in annanagar | python training in omr | python training in porur | python training in tambaram | python training in velachery

      RăspundețiȘtergere