php - yii2 only numbers and + for string

I want to be able to write only numbers and numbers with + at the end in the field, for example 10+

As far as I understand, it is impossible to do this for an integer

It turns out that I need to make the field a string and add validation where only numbers and + can be used, or what is better?

And how do I do it in rules(), I only know how to add a max value:

public function rules()
    {
        return [
            [['number'], 'string', 'max' => 11],
        ];
    }

Answer

Solution:

The appropriate type in the rule is a string.

The you have to add a custom validation rule (see https://stackoverflow.com/a/32840337/3286903 for an example).

In your validation function,

  • check for the pattern '/^[0-9]+\+?$/' with preg_match()
  • define an error message

and you're done.

Source