简体   繁体   中英

Form validation server side in wordpress

I am new to wordpress. I have a custom contact form in frontend and i have to validate the data.

Will I have to make validation class or is there any hooks provided by wp.

if you try to use contact form 7 plugin, then you have validation plugin available for this,ie Jquery Validation For Contact Form 7

or try

http://code-tricks.com/contact-form-7-custom-validation-in-wordpress/

Regardless of what you use WordPress for, there's a range of common functions people need their site to perform that aren't bundled with WordPress. This leaves you with two choices, installing a plugin or creating it yourself.

I am validating form data with my own class wrapper. following are some of the methods you can use :

function handleContactForm() {

 if($this->isFormSubmitted() && $this->isNonceSet()) {
    if($this->isFormValid()) {
        $this->sendContactForm();
    } else {
        $this->displayContactForm();
    }
 } else {
    $this->displayContactForm();
 }

}

public function sendContactForm() {
}

function isNonceSet() {
  if( isset( $_POST['nonce_field_for_submit_contact_form'] )  &&
     wp_verify_nonce( $_POST['nonce_field_for_submit_contact_form'],  'submit_contact_form' ) ) return true;
  else 
     return false;
 }

function isFormValid() {
 //Check all mandatory fields are present.
 if ( trim( $_POST['contactname'] ) === '' ) {
    $error = 'Please enter your name.';
    $hasError = true;
 } else if (!filter_var($_POST['contactemail'], FILTER_VALIDATE_EMAIL) )    {
    $error = 'Please enter a valid email.';
    $hasError = true;
 } else if ( trim( $_POST['contactcontent'] ) === '' ) {
    $error = 'Please enter the content.';
    $hasError = true;
 } 

 //Check if any error was detected in validation.
 if($hasError == true) {
    echo $error;
    return false;
 } 
 return true;
 }

 function isFormSubmitted() {
    if( isset( $_POST['submitContactForm'] ) ) return true;
    else return false;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM