robins
robins

Reputation: 1668

How to allow space,comma,dot and alphabets in codeigniter validation

In my view page.I have a textbox for entering comments.In my codeigniter validation that allow only alpha.

I need to allow space,comma,dot,hyphen in Comment field.. How this place in my validation set rules

    $this->form_validation->set_rules('e_comment', 'Comments', 'required|alpha');

Upvotes: 3

Views: 10714

Answers (4)

Akhil chandran
Akhil chandran

Reputation: 11

As I don't have enough reputation to comment on another answer, I will add this improved answer of jeemusu so as to include the issue raised by jorz, which is to avoid raising the error message whenever the data entered is blank

// validation rule
$this->form_validation->set_rules('comment', 'Comments', 'required|callback_customAlpha');

// callback function
public function customAlpha($str) 
{
    if ( !preg_match('/^[a-z .,\-]+$/i',$str)&& $str!= "" )
    {
        return false;
    }
}

// custom error message
$this->form_validation->set_message('customAlpha', 'error message');

Upvotes: 0

Abdul Manan
Abdul Manan

Reputation: 2375

Easy and Best way to do this ,

Go to system/library/form_validation.
and make a functions or extend the library:

public function myAlpha($string) 
    {
        if ( !preg_match('/^[a-z .,\-]+$/i',$string) )
        {
            return false;
        }
    }

now use it normally where you want it .

$this->form_validation->set_rules('comment', 'Comments', 'required|myAlpha');

Upvotes: 0

Abdulla Nilam
Abdulla Nilam

Reputation: 38652

function alpha($str)
{
    return ( ! preg_match("/^([-a-z_ ])+$/i", $str)) ? FALSE : TRUE;
} 

In the rules, you can call it like follows:

$this->form_validation->set_rules('comment', 'Comments', required|callback_alpha');

EDIT 01

return ( ! preg_match("/^([-a-z_ .,\])+$/i", $str)) ? FALSE : TRUE;

Change this

Upvotes: 0

Jeemusu
Jeemusu

Reputation: 10533

To do custom validation you will need to use a callback function.

// validation rule
$this->form_validation->set_rules('comment', 'Comments', 'required|callback_customAlpha');

// callback function
public function customAlpha($str) 
{
    if ( !preg_match('/^[a-z .,\-]+$/i',$str) )
    {
        return false;
    }
}

// custom error message
$this->form_validation->set_message('customAlpha', 'error message');

Upvotes: 5

Related Questions