开发者

Text::MicroTemplate and Server side validation [Perl]

开发者 https://www.devze.com 2023-04-07 02:52 出处:网络
I have a form, which I use Text::MicroTemplate to add some fields to it, 开发者_运维知识库such as:

I have a form, which I use Text::MicroTemplate to add some fields to it, 开发者_运维知识库such as: User Name Last Name Email

the fields are added using a loop inside a <form> tag, the data for these is validated using a regex (sent as a parameter to the template and "hidden" in the HTML in <span> tag with style display:none), so far, all is fine.

suddenly I have to add another field, for which the data has to be validated on the server side, what is the best approach for doing so? (I can of course, check the POST data, and if its incorrect, can send back the form with the relevant error message, but then, I will have to render the whole page again, which I dont do for the other fields...)

probably something with ajax?

thanks,


AJAX can avoid the whole page rendering which is a good thing™.

You know for sure that writing AJAX code working with different browser implementations, will lead to spaghetti-JavaScript-code, so my advice is to level differences with a good JavaScript library. I have chosen jQuery, because is easy to learn and fun to use if you alredy know CSS2 selectors. There there are other good libraries YUI, Prototype, MooTools, just choose one.

With jQuery, you can invoke an AJAX call in various ways including this simple version:

$.post( url, parameters, callback, returned_type );

where

  • url: URL of server side resource that validates input
  • parameters: an object whose properties are serialized into encoded parameters
  • callback: callback invoked when request completes ( response body and status are passed to the callback as first and second parameter ).
  • type: a string like 'html', 'text', 'xml', 'json', that tells what kind of response to expect from server.

Usually, to send a form, you have to hook an event handler to the submit button: the event handler hijacks the submit event, giving the opportunity to validate values client-side and send them with an AJAX call.

$( '#my_form' ).submit( function( event ) {
    // Prevent classic submission that ends with whole page render
    event.preventDefault();
    // Here iterate through form elements and do a client-side check
    ... 
    $ajax.post( ... ); 
}

I can understand that my example is oversimplifed, but that pattern is rather common: hijack-submit-event-and-do-it-another-way. You'll find more examples ( including those with powerful jQuery plugins ) in chapter 11 of jQuery Cookbook, entitled Html form enhancements with plugins.

0

精彩评论

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

关注公众号