简体   繁体   中英

Check if input number is valid in Codeigniter Form Validation

Can you help me to validate if my input number is valid.

It can be a whole number It can also be a decimal number but interval is 0.5, So 0.5, 1.5 , 2.5 is ok but .2,1.3,2.6 is not valid.

if ((preg_match('/^\d+\.\d+$/',$bkpoints))  || (preg_match('/^\.\d+$/',$bkpoints)))
{       {
    if ($bkpoints % 0.5 !== 0)
    {
          $this->form_validation->set_message('is_bk_decimal','Bk points decimal value should be incremented by 0.5');
          return false;
    }

 }
 return true;

You can validate it with one single regex ^\\d+(?:\\.[05]0*)?$ :

if(preg_match('#^\d+(?:\.[05]0*)?$#', $bkpoints)){
    echo 'valid';
}

Explanation:

  • ^ : begin of line
  • \\d+ : match a digit one or more times
  • (?: : start of non-capturing group
    • \\. : match a dot
    • [05] : match 0 or 5
    • 0 : match 0 zero or more times
  • ) : End of non-capturing group
  • ? : make the group optional
  • $ : end of line

online regex demo

Try the is_numeric() function in PHP: http://php.net/manual/en/function.is-numeric.php

It'd return true if the number is an valid number, and return false if it isn't.

Or you could also use the ereg() function:

if(ereg("^([0-9]+|[0-9]{1,3}(,[0-9]{3})*)(.[0-9]{1,2})?$", "0.9")){
  echo "number";
}else{
  echo "not a number";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM