AS2: ContactForm

View Example
View Documentation
Download Class & Example Files

Creates a communication gateway between a contact form and a PHP script that checks for validity and sends the email. The e-mail checking is rudimentary at best, but it gets the job done. If someone will go through the trouble to try and break this e-mail checker, then by all means spam away (at least that's the way I see it).

Actionscript:
  1. import mx.events.EventDispatcher;
  2.  
  3. /**
  4. * Creates a communication gateway between a contact form and a PHP script that checks for validity and sends the email.  The
  5. * e-mail checking is rudimentary at best, but it gets the job done.  If someone will go through the trouble to try and break this
  6. * e-mail checker, then by all means spam away (at least that's the way I see it).
  7. *
  8. * <p>The fields array should contain an object for each field.  The object will have a "field" string value, which is the
  9. * instance name (minus the "_txt" suffix) of the text field to check, an "error" string value which is the error text
  10. * that is displayed when the error events are dispatched, and a "required" boolean that checks if the field is a
  11. * required field.</p>
  12. *
  13. * <p>As of right now, the fields that are passed into the fields array should be written as the instance name of the field minus the _txt extension.
  14. * For example, if the instance name is name_txt, you pass "name" as the field string value in the fields array.</p>
  15. *
  16. * <p>The class dispatches events depending on what happens.  The events are as follows:</p>
  17. *
  18. * <ul>
  19. * <li>onEmailError: Dispatched if the e-mail check returns an incorrect e-mail address</li>
  20. * <li>onInvalidError: Dispatched when a required field fails the check (displays error from fields array object)</li>
  21. * <li>onMessageSent: Dispatched when the message has been successfully sent</li>
  22. * <li>onServerError: Dispatched if the server is unable to deliver the message</li>
  23. * </ul>
  24. *
  25. * @usage
  26. * <code>
  27. * <pre>
  28. import com.reintroducing.forms.ContactForm;
  29. var listener:Object = new Object();
  30. var scriptURL:String = "scripts/contactSubmit.php";
  31. var toEmail:String = "matt@reintroducing.com";
  32. var subject:String = "Testing the ContactForm Class";
  33. var fields:Array = new Array(   {field: "name", error: "Please enter your name.", required: true},
  34.                                 {field: "email", error: "Please enter a valid e-mail address.", required: true},
  35.                                 {field: "phone", error: "", required: false},
  36.                                 {field: "comments", error: "Please enter your comments.", required: true});
  37. var cf:ContactForm = new ContactForm(fields, scriptURL, toEmail, subject);
  38. cf.addEventListener("onEmailError", listener);
  39. cf.addEventListener("onInvalidError", listener);
  40. cf.addEventListener("onMessageSent", listener);
  41. cf.addEventListener("onServerError", listener);
  42. listener.onEmailError = function($eo:Object):Void
  43. {
  44.     _root.error_txt.text = $eo.error;
  45. };
  46. listener.onInvalidError = function($eo:Object):Void
  47. {
  48.     _root.error_txt.text = $eo.error;
  49. };
  50. listener.onMessageSent = function($eo:Object):Void
  51. {
  52.     _root.error_txt.text = "Your message has been sent. Thanks!";
  53. };
  54. listener.onServerError = function($eo:Object):Void
  55. {
  56.     _root.error_txt.text = "Server failed. Please try again later.";
  57. };
  58. submit_btn.onRelease = function():Void
  59. {
  60.     _root.cf.sendMessage(_root);
  61. };
  62. * </pre>
  63. * </code>
  64. *
  65. * @author Matt Przybylski [http://www.reintroducing.com]
  66. * @version 1.1
  67. */
  68.  
  69. class com.reintroducing.forms.ContactForm
  70. {
  71.     /*
  72.      * ====================================================================================================
  73.      * PRIVATE VARIABLES
  74.      * ====================================================================================================
  75.      */
  76.     
  77.     // constants
  78.     private var _CLASS_NAME:String = "ContactForm";
  79.    
  80.     private var _fields:Array;
  81.     private var _numFields:Number;
  82.     private var _scriptURL:String;
  83.     private var _email:String;
  84.     private var _subject:String;
  85.     
  86.     /*
  87.      * ====================================================================================================
  88.      * PUBLIC VARIABLES
  89.      * ====================================================================================================
  90.      */
  91.    
  92.     public var msg:LoadVars;
  93.     public var msgSent:LoadVars;
  94.    
  95.     // EventDispatcher mixins
  96.     public var addEventListener:Function;
  97.     public var removeEventListener:Function;
  98.     public var dispatchEvent:Function;
  99.    
  100.     /*
  101.      * ====================================================================================================
  102.      * CONSTRUCTOR
  103.      * ====================================================================================================
  104.      */
  105.    
  106.     /**
  107.      * Creates a new instance of the ContactForm class.  The events "onEmailError" and "onInvalidError" will be dispatched if
  108.      * there is an error with the e-mail field or any other required field.  The errors that will be shown are defined in the
  109.      * fields array.
  110.      *
  111.      * @usage <pre><code>var cf:ContactForm = new ContactForm($fields, $scriptURL, $email, $subject);</code></pre>
  112.      *
  113.      * @param $fields An array that tells the form what fields to check, what errors to display, and if the field is required or not
  114.      * @param $scriptURL A string that represents the path on the server to the PHP script
  115.      * @param $email A string representing an e-mail address that the script will send the information to
  116.      * @param $subject A string representing the subject of the e-mail being sent
  117.      */
  118.    
  119.     public function ContactForm($fields:Array, $scriptURL:String, $email:String, $subject:String)
  120.     {
  121.         EventDispatcher.initialize(this);
  122.        
  123.         _fields             = $fields;
  124.         _numFields      = _fields.length;
  125.         _scriptURL      = $scriptURL;
  126.         _email        = $email;
  127.         _subject            = $subject;
  128.     }
  129.    
  130.     /*
  131.      * ====================================================================================================
  132.      * PRIVATE METHODS
  133.      * ====================================================================================================
  134.      */
  135.    
  136.     private function validateEmail($str:String):Boolean
  137.     {
  138.         var after_at = $str.split("@");
  139.         var after_periods = after_at[1].split(".");
  140.       
  141.         if (after_at.length != 2) return false;
  142.         if (after_periods.length <2 || after_periods.length> 3) return false;
  143.       
  144.         return true;
  145.     }
  146.    
  147.     // check the fields in the form and validate them
  148.     private function checkForm($r:MovieClip):Boolean
  149.     {
  150.         var missing:Boolean;
  151.        
  152.         for (var i:Number = 0; i <_numFields; i++)
  153.         {
  154.             if (_fields[i].field == "email" && _fields[i].required)
  155.             {
  156.                 // check the email field for validation
  157.                 if (!validateEmail($r[_fields[i].field + "_txt"].text))
  158.                 {
  159.                     missing = true;
  160.                     dispatchEvent({type: "onEmailError", target: this, field: _fields[i].field, error: _fields[i].error});
  161.                 }
  162.             }
  163.            
  164.             // check all other fields to see if they have something in them
  165.             if ($r[_fields[i].field + "_txt"].text == "" && _fields[i].field != "email" && _fields[i].required)
  166.             {
  167.                 missing = true;
  168.                 dispatchEvent({type: "onInvalidError", target: this, field: _fields[i].field, error: _fields[i].error});
  169.             }
  170.         }
  171.        
  172.         // if missing is true, return false; otherwise return true
  173.         return missing ? false : true;
  174.     }
  175.    
  176.     /*
  177.      * ====================================================================================================
  178.      * PUBLIC METHODS
  179.      * ====================================================================================================
  180.      */
  181.    
  182.     /**
  183.      * Checks the form and dispatches the appropriate event according to what is happening.
  184.      *
  185.      * @usage <pre><code>cf.sendMessage(_root);</code></pre>
  186.      *
  187.      * @param $root The timeline where the fields/clips for the form are located on
  188.      * @return Nothing
  189.      */
  190.    
  191.     public function sendMessage($root:MovieClip):Void
  192.     {
  193.         var tRef:Object     = this;
  194.         var formValid:Boolean = checkForm($root);
  195.        
  196.         msg     = new LoadVars();
  197.         msgSent    = new LoadVars();
  198.        
  199.         msgSent.onLoad = function():Void
  200.         {
  201.             if (this.sent == "OK")
  202.             {
  203.                 tRef.dispatchEvent({type: "onMessageSent", target: this});
  204.             }
  205.             else
  206.             {
  207.                 tRef.dispatchEvent({type: "onServerError", target: this});
  208.             }
  209.         };
  210.        
  211.         if (formValid)
  212.         {
  213.             // pass the email and subject that you are sending
  214.             msg.to = _email;
  215.             msg.subject = _subject;
  216.            
  217.             // pass the appropriate values to the php form for submission
  218.             for (var i:Number = 0; i <_numFields; i++)
  219.             {
  220.                 msg[_fields[i].field] = $root[_fields[i].field + "_txt"].text;
  221.             }
  222.            
  223.             msg.sendAndLoad(_scriptURL + "?ck=" + new Date().getTime(), msgSent);
  224.         }
  225.     }
  226.    
  227.     /*
  228.      * ====================================================================================================
  229.      * EVENT HANDLERS
  230.      * ====================================================================================================
  231.      */
  232.    
  233.    
  234.    
  235.     /*
  236.      * ====================================================================================================
  237.      * GETTERS & SETTERS
  238.      * ====================================================================================================
  239.      */
  240.    
  241.    
  242.    
  243.     /*
  244.      * ====================================================================================================
  245.      * HELPERS
  246.      * ====================================================================================================
  247.      */
  248.    
  249.     public function toString():String
  250.     {
  251.         return "[" + _CLASS_NAME + "]";
  252.     }
  253.    
  254.     /*
  255.      * ====================================================================================================
  256.      * END CLASS
  257.      * ====================================================================================================
  258.      */
  259. }

If you found this post useful, please consider leaving a comment, subscribing to the feed, or making a small donation.

1 Comment

[...] is a direct port of my AS2 ContactForm with updates to work with AS3. The files come with a ContactFormEvent class which allows me to [...]

Leave a comment

(required)

(required)