How to resolve space, comma, period and alphabets in code validation

On my browsing page. I have a text box for entering comments. In my code review that only allow alpha.

I need to allow space, comma, period, hyphen in the Comment field. How does this place in my validation rules

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

      

+3


source to share


3 answers


To perform a spot check, you need to use the 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');

      

+4


source


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

      

In rules, you can call it like this:

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

      



EDIT 01

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

      

Change this

0


source


The easiest and best way to do it,

Go to system/library/form_validation.


and execute functions or extend library:

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

      

now use it usually where you want it.

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

      

0


source







All Articles