Skip to content

Instantly share code, notes, and snippets.

@michaeluno
Last active December 25, 2015 01:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save michaeluno/feb6e785a45d66d2e826 to your computer and use it in GitHub Desktop.
Save michaeluno/feb6e785a45d66d2e826 to your computer and use it in GitHub Desktop.
Demonstrates validating a single field of the form created by the framework. This is a sample plugin introduced in the tutorial, Validate Submitted Form Data of a Single Field (http://en.michaeluno.jp/admin-page-framework/tutorials-v3/07-validate-submitted-form-data-of-a-single-field/).
<?php
/*
* Plugin Name: Admin Page Framework Tutorial 07 - Validate Single Field
* Plugin URI: http://en.michaeluno.jp/admin-page-framework
* Description: Validates a single field of the form created by the framework.
* Author: Michael Uno
* Author URI: http://michaeluno.jp
* Version: 1.0.0
* Requirements: PHP 5.2.4 or above, WordPress 3.4 or above. Admin Page Framework 3.0.6 or above
*/
// Set your own path here
include( dirname( __FILE__ ) . '/library/apf/admin-page-framework.php' );
class APF_ValidateSingleField extends AdminPageFramework {
public function setUp() {
$this->setRootMenuPage( __( 'Validate Form Data', 'admin-page-framework-tutorials' ) ); // where to belong
$this->addSubMenuItem(
array(
'title' => __( '7. Validate Single Field', 'admin-page-framework-tutorials' ), // page and menu title
'page_slug' => 'apf_tutorial_single_field_validation' // page slug
)
);
$this->addSettingFields(
array(
'field_id' => 'url',
'title' => __( 'URL', 'admin-page-framework-tutorials' ),
'type' => 'text',
'default' => 'http://wordpress.org',
),
array(
'field_id' => 'submit',
'type' => 'submit',
)
);
}
/**
* The pre-defined validation callback method.
*
* Notice that the method name is validation_{instantiated class name}_{field id}.
*
* @param string|array $sInput The submitted field value.
* @param string|array $sOldInput The old input value of the field.
*/
public function validation_APF_ValidateSingleField_url( $sInput, $sOldInput ) {
// Set a flag
$_bIsValid = true;
// Prepare an field error array.
$_aErrors = array();
// Use the debug method to see what are passed.
// $this->oDebug->log( $sInput );
// Check if a url is passed
if ( ! filter_var( $sInput, FILTER_VALIDATE_URL ) ) {
$_bIsValid = false;
// $variable[ 'field_id' ]
$_aErrors['url'] = __( 'The value must be a url:', 'admin-page-framework-tutorials' ) . ' ' . $sInput;
}
// An invalid value is found.
if ( ! $_bIsValid ) {
// Set the error array for the input fields.
$this->setFieldErrors( $_aErrors );
$this->setSettingNotice( __( 'There was something wrong with your input.', 'admin-page-framework-tutorials' ) );
return $sOldInput;
}
return $sInput;
}
}
new APF_ValidateSingleField;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment