1

Is it possible to validate both numbers and decimal values using codeigniter validations class?

Coz i need to give the user to enter either a number or a decimal value. Eg: 10 or 1.5 or 30.45

In codeigniter validation class it allows to either validate a number or decimal separately.

Can someone tell me how can this validation be done in codeigniter?

2 Answers 2

2
<?php

class Form extends CI_Controller
{
    public function index()
    {
        $this->load->helper(array('form', 'url'));

        $this->load->library('form_validation');

        $this->form_validation->set_rules('weight', 'Weight', 'required|trim|callback_weight_check');

        if ($this->form_validation->run() == FALSE) {
            $this->load->view('myform');
        } else {
            $this->load->view('formsuccess');
        }
    }

    public function weight_check($val)
    {
        if (!is_int($val) && !is_float($val)) {
            $this->form_validation->set_message('weight_check', 'The {field} field must be number or decimal.');
            return FALSE;
        } else {
            return TRUE;
        }
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

Your condition is wrong. it should be !is_int($val) && !is_float($val). If you don't change it all floats will fail
@MdAshrafulIslam It is fixed now. Thank you.
@Tpjoka Your condition is still wrong. Because I have checked it again. Sorry my last condition was wrong too. Because both !is_int and !is_float fail when argument is "10.00". is_float works when argument is a number. But in this case, the argument is a string. It fails on most case. Use !filter_var($val, FILTER_VALIDATE_FLOAT) istead. No need to do that for integer too because it automatically validates integers.
No. Check with value "10.00" it fails.
Because it is string. Question required int or float condition. However, this is 3 years old answer and with your help it is fixed now. Thanks.
|
0

You can try building your own callback or use the regex_match rule to do it like this:

$this->form_validation->set_rules('cost', 'Cost', array('trim','required','min_length[1]','regex_match[/(^\d+|^\d+[.]\d+)+$/]'));

You have to use the array way to set the rules because the regex rule uses a pipe ( | ).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.