sunpietro
sunpietro

Reputation: 2099

How to allow empty or numeric values in codeigniter's form_validation class?

I'd like to have input validated with form_validation class, that'll allow me to put numeric or empty value in the field.
Something like this:

$this->form_validation->set_rules('field[]','The field','numeric or empty|xss_clean');

Is this possible to achieve?

Upvotes: 2

Views: 37280

Answers (5)

Harunur Rashid
Harunur Rashid

Reputation: 29

$this->form_validation->set_rules('field[]','The field','is_natural|trim|xss_clean');
if ($this->form_validation->run() == FALSE) {
        $errors = $this->form_validation->error_array();
        if (!empty($errors['field'])) {
            $errors_data = $errors['field'];
        }
        print_r($errors_data);exit;
    }

You can use is_natural that Returns FALSE if the form element contains anything other than a natural number: 0, 1, 2, 3, etc. For empty checking required rule is used that Returns FALSE if the form element is empty. So remove the required rule is if used. And use form_validation rules for showing your rules message

Upvotes: 0

Ashish Pathak
Ashish Pathak

Reputation: 824

For phone number with 10 digits:

 $this->form_validation->set_rules('mobile', 'Mobile Number ', 'required|regex_match[/^[0-9]{10}$/]'); //{10} for 10 digits number

Upvotes: 1

stealthyninja
stealthyninja

Reputation: 10371

But, it returns me the errors

Then perhaps an extra step:

if (!empty($this->input->post('field[]')))
{
    $this->form_validation->set_rules('field[]', 'The field', 'numeric|xss_clean');
}

Upvotes: 3

Ogulcan Orhan
Ogulcan Orhan

Reputation: 5317

I think you mean "Using Arrays as Field Names"

You can have a look at this page

Upvotes: 0

Sam Granger
Sam Granger

Reputation: 411

$this->form_validation->set_rules('field[]', 'The field', 'numeric|xss_clean');

This should be sufficient in theory, since the field hasn't been set to required.

Upvotes: 8

Related Questions