Validation on prefilled value at the time of submit

I have a field for a phone number in my form which is already pre-filled. For example, the field value is 0234711288, and I have added a validation on the same field mentioned below:

[[‘PhoneNumber’], ‘match’, ‘pattern’ => ‘/^+[1-9]\d{3,14}$/’, ‘message’ => Yii::t(‘app’, ‘mobile_validation’)],

According to validation, the field should accept a value like +32495123456.

Now when I submit the form, it should trigger validation and display the error, but my form gets submitted. Note: I have enabled the client-side validation.

problem in Your Regex

[['PhoneNumber'], 'match', 'pattern' => '/^+[1-9]\d{3,14}$/', 'message' => Yii::t('app', 'mobile_validation')],

problem is here: ^+

  • ^ means start of string
  • + is a quantifier (repeat previous character)

u need to escape the + sign properly

[['PhoneNumber'], 'match',
    'pattern' => '/^\+[1-9]\d{3,14}$/',
    'message' => Yii::t('app', 'mobile_validation')
],
1 Like

In our country it’s not common to require/include the country code in a phone number.
So I would recommend to explicitly state that.
Or make it optional to fill in a country code, add a question mark after the plus then: /^\+?[1-9]\d{3,14}$/

I would probably make a separate field for the country code (maybe a dropdown) or just conclude it from a form field ‘country’.