AS3: 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).

This 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 dispatch events in AS3 with custom parameters based on my AS3 Custom Events model.

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

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

14 Comments

nice class bro, good idea to run common options with the fields array, well done!

I have found one problem, when you remove email from the fields array, it no longer seems to work... it sends back the successful sent message, but the email never arrives?

I found the problem to be with the "Reply-To:" within $additionalHeaders in "contactSubmit.php" ...a simple IF statement on $_POST['email'] fixed it.

I realise most people will want the email field. But i just needed a name, number and comment form. So hopefully this will help any one else with similar needs.

Great work, and thanks again.

Thanks Damien!

Hey Damien,
For some reason I've been getting legit comments filtered as spam lately so I have to keep checking my spam daily to see if anyone has commented legitly.

Anyway, I'm no PHP expert by any means and most of that PHP code to make this work wasn't written by me. Would you mind sending me the updated PHP code that you added to fix the issue so I can post it here for everyone in the download? Thanks!

Hi Matt,

No Problem, just replace line 25 with this:

if($_POST['email']){
$additionalHeaders .= 'Reply-To: '.$_POST['email'];
} else {
$additionalHeaders .= 'Reply-To: noreply@mydomain.com';
}

All the best,

Damien

Thanks Damien,
I went ahead and replaced the zip with the changes. It should be ok now.

[...] up all my time so I haven’t had a chance to do much around here. I did, however, update the AS3 ContactForm due to an issue that Damien Oliver outlined in the comments so if you’re using the class, [...]

hey matt...i looked over you post awhile back and just took a look now....very useful but it doesnt clear the form on submit....all the info just remains there after the confirmation message.... is this a flaw or is it not written in the code?

hey pete,
you can react to the ON_SUCCESS event and clear the form yourself. I didn't add it in there because that may not be the desired effect for everyone. It is a very simple thing to do though.

thx matt...gonna take a look at it today ...

love your tween examples too....i got used to tweener and haven't had the time even to look at the other engines but now i can!

hi.. great form... did you manage to clear the form??
that 25 line is on the fla? or php? it wont work for me.. keep getting spam...

the class doesn't take care of clearing your form for you. you can listen to the ON_SUCCESS or ON_ERROR events and in the handler write the function to clear your form.

Hello,
In the email that it's sent how can I choose the order I desire? For example:

Address: Rua camelia 4 andar
Postal: 1800-088
Descrition: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec rhoncus.
Month: 12
Name: Bruno Proença
Email: test@test.cin
Year: 2000
Mobile: 96000000
Day: 1

---

and I would like to see:

Name:
Email:
Address:
Postal:
Mobile:
Day:
Month:
Year:
Description:

Thanks and great work 🙂

hi , i can use of it .
but in sender in email write >>> (unknown sender)

Leave a comment

(required)

(required)