3

I want to display custom validation messages for max length and min length of phone number. I have written this code to display custom validation message for max length and min length of phone number field.

['phone', 'string', 'max' => 12, 'min' => 8, 'message' => 'Please enter a valid Phone number.']

The validation is working well however custom message is not being displayed. everytime is shows this default yii2 message "Phone should contain at most 12 characters."

Thanks in advance for help.

topher
  • 13,854
  • 5
  • 51
  • 67
Vinit Singh
  • 1,113
  • 2
  • 21
  • 45

2 Answers2

6

Try:

Update: If you want to use number validator you can use the following:

['phone', 'number', 'max' => 12, 'min' => 8, 'tooBig' => 'Please enter a valid Phone number.', 'tooSmall' => 'Please enter a valid Phone number.']

If you want to use string validator you can use the following:

['phone', 'string', 'max' => 12, 'min' => 8, 'tooLong' => 'Please enter a valid Phone number.', 'tooShort' => 'Please enter a valid Phone number.']
Chinmay Waghmare
  • 5,128
  • 2
  • 42
  • 65
  • I am getting this Exception error if i use your code "Exception (Unknown Property) 'yii\base\UnknownPropertyException' with message 'Setting unknown property: yii\validators\StringValidator::tooBig' " Do i need to include any class for it – Vinit Singh Jul 18 '16 at 09:05
  • use number instead of string .. I updated the answer .. Please check and let me know whether it works for you. – Chinmay Waghmare Jul 18 '16 at 09:07
  • @Chinmay could you edit the answer to highlight the changes? Comments can be deleted. – topher Jul 18 '16 at 09:41
  • Just an observation, but using a number field to store telephone numbers may not be a good idea. You will lose a leading zero on saving, and it doesn't allow you to store word characters like + or () that may be in an international telephone number. I usually use a varchar field. – Joe Miller Jul 18 '16 at 09:59
  • @JoeMiller: I agree with you, since the OP used the min and max property that's why I suggested to use the number validator instead of string. – Chinmay Waghmare Jul 18 '16 at 10:34
  • sorry but that works for value of phone number but not for length. – Vinit Singh Jul 18 '16 at 10:34
  • @VinitSingh: See the updated answer, if you want to use string validator. you can use tooshort and toolong for it. – Chinmay Waghmare Jul 18 '16 at 10:44
0

please change string to length

    ['phone', 'length', 'max' => 12, 'min' => 8, 'message' => 'Please enter a valid Phone number.']

for your reff.

http://www.yiiframework.com/doc/api/1.1/CStringValidator

Hope it will help