1

I know this is very simple and repeated question, But i tried almost all but didnt get any solution. I want to validate a percentage of student like. Eg: 65.45.. The user has to enter value like this only otherwise it should show error. I have given below rules in the model. But its taking only integer values. Not validation for percentage.

[['c_percentage'], 'number', 'numberPattern' => '/^\s*[-+]?[0-9]*[.,]?[0-9]+([eE][-+]?[0-9]+)?\s*$/'],

Please help to solve this. Thanks in advance.

Salman Riyaz
  • 808
  • 2
  • 14
  • 37
  • Regarding *its taking only integer values*: the pattern is [correct](https://regex101.com/r/L6kPWD/1), it allows matching both integer and float values, are you sure you are checking/assigned the rule to/ the right element? Note that `[0-9]*` matches 0 or more digits, and `[.,]?` matches 1 or 0 commas/periods. – Wiktor Stribiżew Mar 17 '17 at 07:30
  • Regarding to your requirement *The user has to enter value like this **only*** modify it to be like this: `/^\s*[-+]?[0-9]+[.,][0-9]+([eE][-+]?[0-9]+)?\s*$/` – revo Mar 17 '17 at 07:31
  • Or if the scientific notation should not be allowed, use a much simpler `/^\s*\d+[.,]\d+\s*$/` – Wiktor Stribiżew Mar 17 '17 at 07:40
  • Thank you for replies.. Its still dos'nt work. its accepting values like 55.6666. i want to take value like 55.66 – Salman Riyaz Mar 17 '17 at 09:35
  • What if you also replace `'numberPattern'` with `'pattern'`? – Wiktor Stribiżew Mar 17 '17 at 09:43
  • yeah did tat and i have to change `number` to `match`. Even now its same as previous. Taking values if i enter 55.66666 – Salman Riyaz Mar 17 '17 at 09:47
  • isn't it is possible to restrict only two digit after `.` Dot symbol?? – Salman Riyaz Mar 17 '17 at 09:48

2 Answers2

3

This will do the job:

/^\s*[+-]?\d+(?:[.,]\d{1,2})?\s*$/

Explanation:

/               : regex delimiter
  ^             : begining of string
    \s*         : 0 or more spaces
    [+-]?       : optional plus or minus
    \d+         : 1 or more digits
    (?:         : start non capture group
      [.,]      : dot or comma
      \d{1,2}   : 1 or 2 digits (decimal part)
    )?          : the group is optional to allow whole integer
    \s*         : 0 or more spaces
  $             : end of string
/               : regex delimiter

If you want to match only float values, remove the optional part:

/^\s*[+-]?\d+[.,]\d{1,2}\s*$/

or, if you want exactly 2 decimals:

/^\s*[+-]?\d+[.,]\d{2}\s*$/
Toto
  • 89,455
  • 62
  • 89
  • 125
0

Try this it will validate

[['c_percentage'], 'number', 'numberPattern' => '/^[0-9]{1,2}(\.([0-9]{0,2})){0,1}$/'],
dev.meghraj
  • 8,542
  • 5
  • 38
  • 76