WordPress Plugin Security: Data Validation

Data validation in WordPress plugin concern with the pattern of data processed by the plugin. Data with certain context should match the pattern generally acceptable. For example:

  • Phone number only contain numerical content
  • Postal code data contain valid postal code for designated country
  • Required fields must be filled before processing

The process of validation should be done as early as possible to save resource and mitigate errors. This can be done throug JavaScript on the front end or PHP code in the plugin.

Lets try an example on Phone number

<?php

function is_phone_number($phone_number){
    
    if ( empty( $phone_number ) ){

        return false;

    }

    if ( strlen( trim($phone_number) ) > 17 ){

        return false;

    }

    if ( ! is_numeric( $phone_number ) ){

        return false;

    }

    return true;

}

The function above can be used to validate phone number. There are some optimization which can be added for example using regex instead of is_numeric to check exact numbers for countries. But for general phone numbers this function should do well to validate them

This function utilized as if condition can serve as a gatekeeper when we work with phone number to ensure befor we do any actions the number is valid one. An example for the function usage is if there is a field of phone_number which we try to process

if ( isset( $_POST['phone_number'] ) && is_phone_number($_POST['phone_number'] ){
  // do something
}

Various PHP functions and WordPress core functions can serve as validation tools. Some examples can be seen in the reference bellow.

References:

WordPress plugin handbook: Data ValidationĀ 

 

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.