khejduk
khejduk

Reputation: 309

Codeigniter form validation. Alpha and spaces

When using Codeigniter form validation, does alpha allow spaces? Ex. "Bob Smith"

Upvotes: 10

Views: 40592

Answers (6)

stuck.overflow
stuck.overflow

Reputation: 11

Easiest solution is

by using alpha_numeric_spaces in your form validation This allow user to input alphabet, numeric, and whitespace

Example:

$this->form_validation->set_rules
        ('username', 
        'Username', 
        'required|alpha_numeric_spaces|trim|is_unique[user.username]',
        [
            
            'required' => 'Error msg',
            'alpha_numeric_spaces'=>'Error msg for alpha_numeric_spaces',
            'is_unique' => 'Error msg'
        ]  
        );

Upvotes: 1

Italo Hernández
Italo Hernández

Reputation: 1132

One line solution:

 $this->form_validation->set_rules('field', 'Field', 'regex_match[/^([a-z ])+$/i]');

Alpha characters and space.

Upvotes: 3

Jeeva
Jeeva

Reputation: 642

I know I'm late to answer this. But for those who are still looking for an answer on how to just allow letters and white spaces, you can follow this:

In form validation

$this->form_validation->set_rules('fullname', 'Fullname', 'min_length[7]|trim|required|xss_clean|callback_alpha_dash_space');

Then add a callback function for alpha_dash_space

function alpha_dash_space($fullname){
    if (! preg_match('/^[a-zA-Z\s]+$/', $fullname)) {
        $this->form_validation->set_message('alpha_dash_space', 'The %s field may only contain alpha characters & White spaces');
        return FALSE;
    } else {
        return TRUE;
    }
}
  • ^ and $ Tells that it is the beginning and the end of the string
  • a-z are lowercase letters, A-Z are uppercase letters
  • \s is whitespace and + means 1 or more times.

Hope it helped!

Upvotes: 8

Youssef
Youssef

Reputation: 3114

Here is a code that should solve your problem:

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

In the rules, you can call it like follows:

$this->form_validation->set_rules('name', 'Name', trim|xss_clean|callback_alpha_dash_space');

Edit

Removed one extra _ from callback_alpha_dash_space

Upvotes: 17

Visakh M Viswambaren
Visakh M Viswambaren

Reputation: 11

You can use

$field = trim($_POST['field']);
$_POST['field'] = str_replace(' ', '', $_POST['field']);

and check it as alpha in the rule, then you can use $field after successful validation.

$this->form_validation->set_rules('field', 'FIELD', 'alpha');

Upvotes: 1

Seabass
Seabass

Reputation: 1983

No, it does not allow spaces.

Someone wrote a library extension that allows that though: http://ellislab.com/forums/viewthread/158696/#794699

Upvotes: 6

Related Questions