I'm trying to use str_word_count to validate my subject title and message, it seems to be returning a false positive, is there a better way of doing this?
class
class Validation
{
private static
$contact,
$email,
$subject,
$message;
const MIN_NAME = 2,
MIN_SUBJECT = 2,
MIN_MESSAGE = 20;
public static function testName($contact){
//test contact me name
return(strlen($contact) >= self::MIN_NAME) && filter_var($contact, FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => "/^[a-zA-Z0-9]+$/"]]) !== false;
}
public static function testEmail($email){
//test email address
return (filter_var($email, FILTER_VALIDATE_EMAIL) != self::$email);
}
public static function testSubject($subject){
//test contact me subject
return(str_word_count($subject) >= self::MIN_SUBJECT) && filter_var($subject, FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => "/^[a-zA-Z0-9]+$/"]]) !== false;
}
public static function testMessage($message){
//test contact me message
return(str_word_count($message) >= self::MIN_SUBJECT);
}
}
useage
$fields = array(
'contact' => array(
'validator' => 'testName',
'message' => 'Your name should be a minimum of two characters and alphanumeric'
),
'email' => array(
'validator' => 'testEmail',
'message' => 'Please enter a valid email address'
),
'subject' => array(
'validator' => 'testSubject',
'message' => 'Please enter a minimum of two alphanumeric characters as your subject'
),
'message' => array(
'validator' => 'testMessage',
'message' => 'Please enter a minimum of twenty words'
)
);
foreach($post as $key => $value)
{
if(isset($fields[$key]))
{
if(!Validation::{$fields[$key]['validator']}($value))
{
$errors[] = ['name' => $key, 'error' => $fields[$key]['message']];
}
}
}