Validating Fields of Submitted Form

Validating a Set of Fields

Now we know a way of validating a single field with the pre-defined callback method. What if you want to validate multiple fields at once? There are other pre-defined validation callback methods.

Steps

  1. Include the library
  2. Extend the library class
  3. Define the setUp() method
  4. Define the form
  5. Define the validation method
  6. Instantiate the extended class

Screenshot

Validating Fields of Submitted Form

Include the library

The library file needs to be loaded.

Extend the library class

The class name needs to be unique.

Define the setUp() method

In the setUp() method, we define the admin pages that are going to be created. For that, we need to decide:

  1. the root page.
  2. the sub page title.
  3. the sub page slug.

This time, we are going to add a sub page to the root page created in the plugin introduced in the previous tutorial. To specify a root menu item created by the framework in a separate script, use the setRootMenuPageBySlug() method and pass the class name that defines the root menu item.

The code will look like the following.

Define the Form

We are going to create a section and two fields and one submit button.

Define the Validation Method

We make the first field only accept an alphanumeric value and the second field have no HTML tags. Notice the method name is validation_ + instantiated class name + _ + section ID.

The first parameter receives an array holding the submitted field values of the section.  The second parameter receives the stored field array of the section. Note that in the previous tutorial, the variable types were strings because only the specified individual field value was passed.

Also, to construct a field error array, this time, set the section ID in the first dimension and set the field ID in the second dimension.

Instantiate the extended class

Finally, we instantiate the class. Unless it is instantiated, it will do nothing.

Code

Try the code below and post comments if you get a problem.

Leave a Reply

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