0

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;

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks much, Actually We are almost there but when I input 0.5 it also gave invalid. 0.5 should also be accepted
@user2046410 impossibruuuu regex demo | php demo. Make sure you don't have spaces etc...
I edit it like this if((preg_match('#^\d+(?:\.[05]0*)?$#', $bkpoints)) || (preg_match('#^(?:\.[05]0*)?$#', $bkpoints))){ and it works fine for. Thank you very much for the idea HamZa
@user2046410 You could wrap everything in one single regex ^\d+(?:\.[05]0*)?$|^(?:\.[05]0*)$ demo. What you have will even match empty strings.
0

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.

2 Comments

ah yes but it will not check if its interval of 0.5
I'm sorry, check my other answer below ;)
-1

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";
}

1 Comment

Update your existing answer, don't post a second one... also: ereg is DEPRECATED, use preg_match instead. Lastly: regular expressions to check if a value is a float is just total overkill

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.