Tuesday, October 22, 2013

username, password and date validation with php

Simple PHP functions to validate username, password and date, functions check the input format and allowed characters and then return TRUE for valid data and FALSE for invalid data.

PHP username validation.

A simple php function to check if the given username is valid or not using preg_match..
1
2
3
4
5
6
7
8
9
10
<?php 
 
function is_valid_username($username){
// accepted username length between 5 and 20
    if (preg_match('/^\w{5,20}$/', $username))
        return true;
    else
        return false;
}
?>


PHP password validation.

A simple php function to check if the given password is valid or not using preg_match.
1
2
3
4
5
6
7
8
9
10
<?php 
 
function is_valid_password($pwd){
// accepted password length between 5 and 20, start with character.
    if (preg_match("/^[a-zA-Z][0-9a-zA-Z_!$@#^&]{5,20}$/", $pwd))
        return true;
    else
        return false;
}
?>



PHP date validation.

Date validation is more complex than the previous validations because date can be entered in several formats
ex:
dd-mm-yyyy => 22-10-2013
mm-dd-yyyy => 10-22-2013
dd/mm/yyyy => 22/10/2013
mm/dd/yyyy => 10/22/2013
yyyy/mm/dd => 2013/10/22
dd-mmm-yyyy => 22-OCT-2013

so we should first determine the format of the date we use and then we can validate it
here is a simple php function to check if the given date is valid or not using preg_match function.
1
2
3
4
5
6
7
8
9
<?php 
 
function is_valid_date($date){
//============ date format dd-mm-yyyy
if(preg_match("/^(\d{2})-(\d{2})-(\d{4})$/", $date, $sdate))
    if(checkdate($sdate[2], $sdate[1], $sdate[3]))
        return true;
}
?>

Another php function to check if the given Date is valid or not using.
1
2
3
4
5
6
7
8
9
<?
 
function is_valid_date($date){
//============ date format dd-mm-yyyy
    $sdate  = explode('-', $date);
    if (checkdate($sdate[1], $sdate[0], $sdate[2]))
        return true;
}
?>


Share it

Online Marketing