PHPBuilder - An introduction to PEAR's Validate package Page 2



RSS Twitter
Articles Pear

An introduction to PEAR's Validate package - Page 2

by: PHP Builder Staff
|
April 9, 2012

An introduction to PEAR's Validate package
Many alternatives aren't quite as complete!
By default, the string is only checked for format, not whether the domain exists. Something like validate.php?email=blah@phpbuilder.co would pass the validation in the first script, even though phpbuilder.co (at present) is not a valid domain. However, the email method allows certain options to be specified to change this. Simply adding true as a second parameter forces a domain check.

<?php
require_once 'Validate.php';
$email = $_REQUEST['email'];
$validate = new Validate();
if ($validate->email("$email"<b>,true</b>)) {
  echo "Valid email";
}
else {
  echo "Invalid email";
}
?>

validate.php?email=blah@phpbuilder.co would now fail the validation. The second parameter though can also be an array instead of a boolean. Then, the two boolean elements are check_domain, which does the same as above, and use_rfc822, which will validate the email according to the full RFC822 standard. Here's an example:

$validate->email("$email",array("check_domain"=>true,"use_rfc822"=>true))

Here's the full email method description:
boolean email( string $email, [mixed $options = null])

    * Return: true if valid email, false if not
    * Access: public

Parameters:
string $email : email to validate
mixed $options : This can be boolean $check_domain, which checks whether or not the domain exists, or array $options, consisting of an associative array of options: boolean 'check_domain', which checks whether or not the domain exists, and boolean 'use_rfc822', which determines whether to apply the full RFC822 grammar
The same simple mechanism is used to validate the other types of data. All that's needed to master this package is getting to know the other available methods and parameters.
Validating numbers
The number method, in its simplest form, tests whether the parameter is numeric:

<?php
require_once 'Validate.php';
$number = $_REQUEST['number'];
$validate = new Validate();
if ($validate->number("$number")) {
  echo "Valid number";
}
else {
  echo "Invalid number";
}
?>

validate.php?number=12 would return true, and validate.php?number=twelve false. There are also numerous options, supplied in the options array. You can test for a maximum value, a minimum value, or both (a range),by using either of both of the min and max parameters. For example, to ensure your value is between 1 and 99 (inclusive), use the following call:

$validate->number("$number",array("min"=>1,"max"=>99))

The number method also caters for decimal numbers. By default, decimals are not permitted, but you can supply any character, or number of characters, to use as the decimal character. Usually this would be a '.' or a ','. For example, to validate a number between 0 and 99, allowing decimals with either a comma or a point, you'd use the following:

$validate->number("$number",array("min"=>1,"max"=>99,"decimal"=>".,"))

You can also limit the number of decimal characters, with the dec_prec option. The following validates as true any decimal number with up to 5 digits after the decimal character. In this case, to demonstrate the flexibility of the method, I'm using the character 'x' as the decimal character, so the number 1x12345 would be valid, but not 1x123456, nor for that matter 1.12345.

$validate->number("$number",array("min"=>1,"max"=>99, "decimal"=>"x","dec_prec"=>5))

Here's the full method description: boolean number( string $number, [array $options = array()])

    * Return: true if valid number, false if not
    * Access: public

Parameters:
string $number : Number to validate
array $options : An array where: 'decimal' is the decimal character, or false if decimal is not permitted. (for example, ',.' to allow both ',' and '.'), 'dec_prec' is the number of allowed decimals, 'min' the minimum value and 'max' the maximum value.
Validating Strings
Strings are equally easy to validate. As you should expect by now, the method to use is called string. The options array this time is compulsory. You can determine whether the tested string should consist of numeric characters only (format=VALIDATE_NUM), alpha characters only (format=VALIDATE_ALPHA), or any of the other valid constants (for example VALIDATE_ALPHA_LOWER). Also, you can require it to be at least (min_length=n) as well as at most (max_length=n) a certain number of characters. Here's an example that requires the string to be alpha characters only, and between 1 and 4 characters in length (inclusive).

<?php
require_once 'Validate.php';
$string = $_REQUEST['string'];
$validate = new Validate();
if ($validate->string("$string",array("format"=>VALIDATE_ALPHA,"min_length"=>1,"max_length"=>4))) {
  echo "Valid string";
}
else {
  echo "Invalid string";
}
?>

Here's the full string method definition:
boolean string( string $string, array $options)

    * Return: true if valid string, false if not
    * Access: public

Parameters:
string $string : String to validate
array $options : Array where 'format' is the format of the string, and which can be any valid constant, such as VALIDATE_NUM (numeric characters only) or VALIDATE_ALPHA (alpha characters only), 'min_length' the minimum length and 'max_length' the maximum length.
Date validation
No validation package would be complete without date validation. However, use of this method requires the Date package to be installed (I'll write more about that particularly useful package in a future article). It takes a date string, as well as options determining acceptable formats, and the range. Here's an example showing the full set of possibilities, requiring the date to be in DD-MM-YYYY format, and between 12-12-2000 and 13-12-2004, inclusive.

$validate->date("$date",array("format"=>"%d-%m-%Y","min"=>array('12','12','2000'),"max"=>array('13','12','2004')))

The full method definition is:
boolean date( string $date, array $options)

    * Return: true if valid date/time, false if not
    * Access: public

Parameters:
string $date : Date to validate
array $options : array of options where 'format' contains the format of the date (for example, %d-%m-%Y), 'min' contains the minimum valid date (passed either in an array of $day, $month, $year or PEAR::Date object), and max the maximum valid date, passed in one of the same formats.
Validating URLs
The wonders of the Validate package don't stop there. You can validate a URL, or more specifically a URI - Uniform Resource Identifier, of which a URL - Uniform Resource Locator, is a subset. This, as always, takes a string containing the URL, and an array of options. By default the 'http://' part is required, and the allowed schemes element contains an array of the acceptable protocols, such as 'ftp' or 'http'. As with the email check, you can decide whether to check the DNS entry or not with the boolean element domain_check. There's also a strict element, introduced mainly for tightening up RFC2396. Here's an example requiring the https protocol, and the domain to be valid.

$validate->uri("$url",array("allowed_schemes"=>array('https'),"domain_check"=>true))

The full method definition is:
boolean uri( string $url, [array $options = null])

    * Return: true if valid uri, false if not
    * Access: public

Parameters:
string $url : URI to validate
array $options : boolean 'domain_check' determines whether to check the DNS entry or not, array 'allowed_schemes' contains the list of protocols (for example 'http' or 'ssh+svn'), string 'strict', which contains the characters to be refused in the query and fragment parts, which defaults to ';/?:@$,' (i.e. by default it's stricter than RFC2396).
Conclusion and further resources
You can find the home of the PEAR Validate Package here. Hopefully you've found it easy to use. Once you're comfortable with Validate, you should also look at the related packages (listed in the introduction), as they allow you to validate other data, such as postcodes using the specific country protocol, in the same simple manner. Good luck!


« Previous Page
1
|
2

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:

Comment:



Comment:

(Maximum characters: 1200). You have characters left.