Home › Forums › Other › Can someone recommend a customizable contact form, please? › Reply To: Can someone recommend a customizable contact form, please?
Okay, let’s move on to validating the form submission.
(Remember our validate() method?)
If you recall, we have a property $_validation
that tells us how each form field needs to be validated. Right now, we have only two needs: some fields are required, and one field must also be an email address.
protected function _validateRequired( $value,&$m="" ){
if( ! $value ){
$m = "This field is required.";
return false;
}
return true;
}
Very straightforward. If the value is empty, it fails validation.
You may not have seen &$someVariable
before —the &
makes it a reference. Instead of getting a copy of whatever variable we pass to the method, we get the actual variable. So, when we assign an error message to $m
inside the method, that message exists in $m
outside the method. Don’t worry if you don’t quite “get” this, for now. It works.
Same thing for email addresses:
protected function _validateEmail( $value,&$m="" ){
// {@see http://php.net/filter_var}
if( ! filter_var( $value,FILTER_VALIDATE_EMAIL ) ){
$m = "Please provide a valid email address.";
return false;
}
return true;
}
Checking the anti-spam challenge is a little different. First, we have to get the proper question from the session, and then we can check if the answer is correct.
protected function _validateAntispam( $value ){
// get antispam key from session, make sure the value is the correct answer
$correct = (
isset( $_SESSION[__CLASS__]["antispam"] )
&& isset( $this->_antispam[$_SESSION[__CLASS__]["antispam"]] )
&& $this->_antispam[$_SESSION[__CLASS__]["antispam"]] === $value
);
// remove used questions from session to prevent re-use
unset( $_SESSION[__CLASS__]["antispam"] );
if( ! $correct ){
$this->_errors["antispam"] = "Please try the antispam challenge again.";
return false;
}
return true;
}
Checking the security token follows a similar process, but we also check that the token “age” is valid.
protected function _validateToken( $token ){
// aside from simply including an issued token,
// the submission should not be too fast nor too slow
$valid = (
isset( $_SESSION[__CLASS__][$token] )
&& $this->_time > ($_SESSION[__CLASS__][$token] + $this->_option["token.min"])
&& $this->_time < ($_SESSION[__CLASS__][$token] + $this->_option["token.max"])
);
// remove used tokens from session (prevents duplicate submissions)
unset( $_SESSION[__CLASS__][$token] );
return $valid;
}
Last thing is to make a method that actually runs all this validation when the form is submitted. A class’ __construct
method is run automatically when the class instance is created, so we’ll use that.
public function __construct( array $_post=null ){
// set the current time in microseconds
$this->_time = microtime( true );
// validate the form submission if present
if( $_post ){
if( $this->validate( $_post ) ){ $this->_sendEmail(); }
}
}