2

When validating prices with CI I use the following rule;

$this->form_validation->set_rules('price','lang:price','required|numeric|greater_than[0.99]');

Is there any way to allow commas in this rule line? Or do i have to create a callback?

3 Answers 3

4

Codeigniter 3 offers a regex validation. Form Validation

Using the regex given by Ben... No callback is required.

$this->form_validation->set_rules('price','lang:price','required|numeric|greater_than[0.99]|regex_match[/^[0-9,]+$/]');
Sign up to request clarification or add additional context in comments.

3 Comments

I believe this should be the correct answer as it's the single-liner the OP was trying to achieve.
doesnt work for me, when I type "7,5" message is saying "onlu numbers are allowed"
@Tikky my hunch is that the 7,5 is regional. I have not tested it using other regions.
2

From using the form validation library, I've never seen anything that would allow you to do that without a callback.

This would be the callback though:

function numeric_wcomma ($str)
{
    return preg_match('/^[0-9,]+$/', $str);
}

with a rule of

$this->form_validation->set_rules('input', 'Input', 'callback_numeric_wcomma');

1 Comment

Thanks, was hoping there was a way of doing it in the single line but will settle for a callback
0

My answer is:

$this->form_validation->set_rules('price','lang:price','regex_match[/^(?!0*[.,]?0+$)\d*[.,]?\d+$/m]');

or do it in your codeigniter view. Add script:

<script>
function replace(element) {
  // set temp value
  var tmp = element.value;
  // replace everything that's not a number or comma or decimal
  tmp = tmp.replace(/[^0-9,.,-]/g, "");
  // replace commas with decimal
  tmp = tmp.replace(/,/, ".");
  // set element value to new value
  element.value = tmp;
}
</script>

and then use input like this:

<input id="something" onkeyup="replace(this)" type="text">

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.