Validation becomes very important part when we take inputs from user and we need valid and correct values to work on. Here are little piece of codes to validate domain and email which uses regular expression.
Function to validate Domain
function isValidDomain($domain){
if (preg_match ("/^[a-z0-9][a-z0-9\-]+[a-z0-9](\.[a-z]{2,4})+$/i",
$domain)) {
return true;
} else {
return false;
}
}
# Call function
if (isValidDomain('example.com')) {
echo 'Valid Domain';
}else{
echo 'Invalid Domain';
}
Domain validation including subdomain
function isValidSubDomain($domain){
if (preg_match ('/([a-zA-Z0-9\-_]+\.)?[a-zA-Z0-9\-_]+\.[a-zA-Z]{2,5}/',
$domain)) {
return true;
} else {
return false;
}
}
# Call function
if (isValidSubDomain('subdomain.example.com')) {
echo 'Valid Domain';
}else{
echo 'Invalid Domain';
}
Function to validate Email
function isValidEmail($email){
if (preg_match("/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i",
$email)) {
return true;
} else {
return false;
}
}
# Call Function
if (isValidEmail('email@example.com')) {
echo 'Valid Email';
}else {
echo 'Invalid Email';
}
Posting Komentar