My (Simple) Validator

Coding Critique is the place to post source code for peer review by other members of DevNetwork. Any kind of code can be posted. Code posted does not have to be limited to PHP. All members are invited to contribute constructive criticism with the goal of improving the code. Posted code should include some background information about it and what areas you specifically would like help with.

Popular code excerpts may be moved to "Code Snippets" by the moderators.

Moderator: General Moderators

Post Reply
User avatar
Chalks
Forum Contributor
Posts: 447
Joined: Thu Jul 12, 2007 7:55 am
Location: Indiana

My (Simple) Validator

Post by Chalks »

I'm really sick of building things from the ground up over and over again. So, I've decided to collect some of my most commonly used functions into one place that I can just stick into my projects whenever I need them. The first thing I decided to collect was a few of the validation things I use for simple login pages. Here's my validator class. I'm looking for suggestions on how to improve the existing code, and suggestions on what other common login/register type validation should be added to the class. Posted here is the version with (a ton of) comments. If you'd rather look at the code with fewer comments, just click here.

Code: Select all

<?php
/*
*This class was created by Jonathan Walters.
*Check out Jon's stuff at http://www.chalksdesign.com
*
*  You are free to modify and use this class in any way you
*  desire as long as my name and my website is credited in
*  your comments. ------ Last updated:  7/21/2008
*
*
*class validator (currently) performs four tasks:
*      validates user names to varying degrees of strictness
*              $this->user(name, [mode, custom regex, min length, max length])
*      validates passwords (just checks length)
*              $this->pass(password, [min length])
*      validates emails with a fairly lenient regex
*              $this->email(address, [custom regex])
*      validates urls with a large degree of leniency
*              $this->link(address, [allowed URL schemes])
*
*list of functions used:
*  trim()
*  strlen()
*  preg_match_all()
*  array()
*  func_num_args()
*  func_get_arg()
*  parse_url()
*  empty()
*/
 
class validator {
/***********
*user(name, [mode, custom regex, minimum length, maximum length])
*user(string, [int, string, int, int, int])
*  This function will validate a string against a variety of regexes.  If
*  $mode is not specified by the user, will default to allowing letters,
*  spaces, underscores and numbers.  If mode is set to 1, will allow just
*  letters and spaces, if 2 will use custom regex.  minl and maxl are for
*  determining minimum and maximum length of the string allowed.  Default
*  is 1 and 30 respectively (and inclusively).  Incidentally, any custom
*  regex should include all characters you do NOT want to match, like so:
*  /[^a-z]/i, which matches anything that is NOT a-z or A-Z.  The custom
*  regex is ONLY used if mode == 2.
*
*  WARNING, this function trim()s whitespace, so "  name" is the same as
*  "name".  If you don't like this, simply remove the first line in the function.
*
*  Example calls:
*  $this->user("billy b_o_b 123");  //default mode is 0
*   returns true
*  $this->user("billy bob", 1);
*   returns true
*  $this->user("bi]]y bob", 2, "/[a-z \]]/i");
*   returns true
*  $this->user("billy bob", 3);  //any modes other than 0, 1 or 2 will only allow letters
*   returns false
*  $this->user("billy bob", 0, "", 1, 5)
*   returns false
***********/
function user($name, $mode=0, $creg="/[^a-z]/i", $minl=1, $maxl=30)
{
  $name = trim($name);
  $l = strlen($name);
  $matches = 0;
  $reg = "/[^a-z]/i";   // if $mode != 0 || 1 || 2, letters only allowed
  if($mode==0)      // letters, spaces, underscores and numbers allowed
    $reg = "/[^a-z _1-9]/i";
  if($mode==1)      // letters and spaces allowed
    $reg = "/[^a-z ]/i";
  if($mode==2)      // use custom regex
    $reg = $creg;
  $matches = preg_match_all($reg, $name, $temp);
  if($l<$minl || $l>$maxl || $l <1)
    return false;
  if($matches!=0)
    return false;
  return true;
}
 
 
/***********
*pass(password, [minimum length])
*pass(string, [int])
*  This function will take a password and make sure it is a
*  minimum length.  If you want, you can specify a different
*  minimum with the second argument.
***********/
function pass($pass, $minl=6)
{
  $l = strlen($pass);
  if($l<$minl)
    return false;
  return true;
}
 
 
/***********
*email(address, [custom regex])
*email(string, [string])
*  This validates email based on the regex at 
*   http://www.regular-expressions.info/email.html
*  Please support them!  If you would like to validate the email
*  based on your own address, you can send it like so:
*  $this->email("email@email.com", "your regex here");
*  otherwise, just use:
*  $this->email("email@email.com");
***********/
function email($email)
{
  $matches = array();
  $args = func_num_args();
  if($args==2)
    $reg = func_get_arg(1);
  else
    $reg = "/^[a-z0-9._%+-]+@[A-Z0-9.-]+\.[a-z]{2,4}$/i";
  $num = preg_match_all($reg, $email, $matches);  // will this match "][';d(  a@bcd.com"?
  if($num!=1)
    return false;
  return true;
}
 
/*
*link(address, [allowed URL schemes])
*link(string, arrray)
*  This function merely checks to see if the url contains a scheme
*  (i.e. http) and a host (i.e. example.com).  By default the scheme
*  must either be "http" or "ftp".  If you send an empty array, it will
*  allow _any_ scheme.  If you send a array of strings, it will test
*  the scheme against each string in the array.  If the user inputs
*  something that is not a url and can not be parsed, it will simply
*  return false.
*  $this->link("http://example.com");
*  $this->link("ftp://example.com");
*  $this->link("gibberish://example.com", array("gibberish", "ftp", "http");
*/
function link($link)
{
  $test = false;
  $args = func_num_args();
  if($args==2)
    $allowedSchemes = func_get_arg(1);
  else
    $allowedSchemes = array("http", "ftp");
  $data = @parse_url($link);  //suppressed errors because user input can screw it
  if(empty($allowedSchemes))
    $test = true;
  else
    foreach($allowedSchemes AS $a)
      if($data['scheme'] == $a)
        $test = true;
  if(empty($data['scheme']) || empty($data['host']))
    $test = false;
  return $test;
}
}
?>
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: My (Simple) Validator

Post by Christopher »

I really looks like three helper functions and not a class at all. I think a library of functions would be handier and more straightforward.
(#10850)
User avatar
Chalks
Forum Contributor
Posts: 447
Joined: Thu Jul 12, 2007 7:55 am
Location: Indiana

Re: My (Simple) Validator

Post by Chalks »

arborint wrote:I really looks like three helper functions and not a class at all. I think a library of functions would be handier and more straightforward.
Yes, that's exactly what it is. The reason I stuck it in a class was because I knew I could easily put that into any script I wanted to. How do I make it a library instead?


edit: Also, I used "parse_url()" to validate urls. This is obviously not going to catch every false url (especially the way I implemented it), but I really didn't want to be too strict when validating a url. Is there any reason to get more strict than what I have there already?
User avatar
Zoxive
Forum Regular
Posts: 974
Joined: Fri Apr 01, 2005 4:37 pm
Location: Bay City, Michigan

Re: My (Simple) Validator

Post by Zoxive »

If i were you, i would leave it as a "Helper" class, and make all the functions static.

So then you can do..

Code: Select all

if(validator::pass($Pass)){
  // True
}else{
  // False
}
Then you never have to initialize the class to use the functions.
Post Reply