Reputation: 493
I'm working on a CodeIgniter project, and I'm making a custom validation, and I'm no regex expert. So far, I have made a simple test, but I cannot seem to get this right. This validation can only contain A-Z a-z 0-9 and special characters such as:
@ ! # / $ % & ' * + - = ? ^ _ ` { | } ~ .
I cannot have ( ) [ ] : ; " < > , \
in my controller:
public function test(){
$this->form_validation->set_rules('communication_number', 'Communication Number', 'required|trim|xss_clean|callback_validate_communication_number');
$this->form_validation->set_message("validate_communication_number", "The %s field must only contain blah blah");
if($this->form_validation->run() == false)
{
echo validation_errors();
}
else
{
echo "Passed";
}
}
public function validate_communication_number($communication_number)
{
if(preg_match("/^[a-z0-9@\!\#\/$\%\&\'\*\+\-\/\=\?/^/_/`/{/|/}/~/.]+$/i", $communication_number))
{
return true;
}
else
{
return false;
}
}
Upvotes: 1
Views: 139
Reputation: 30995
You have to escape backslashes using \\
if you use double quotes or just change to single quote like this:
if(preg_match('/^[a-z0-9@\!\#\/$\%\&\'\*\+\-\/\=\?/^/_/`/{/|/}/~/.]+$/i', $ff_communication_room))
^--- Here
However, you can write your regex as this (you don't need all those escaped backslashes:
^[a-z0-9@!#\/$%&'*+=?^_`{|}~.-]+$
As you can see, it's a valid regex:
Code
$re = '/^[a-z0-9@!#\/$%&'*+=?^_`{|}~.-]+$/i'; // Note hyphen at the end
$str = "your string";
if(preg_match($re, $str))
{
return true;
}
else
{
return false;
}
Upvotes: 3