3


I'm using a Yii2 MaskedInput plugin with a model for an integer field.

<?= $form->field($model, 'phone')->widget(MaskedInput::classname()([
    'mask' => '(999) 999-9999'
]); ?>

When I type text to this field, I'm getting an error (Phone must be an integer.)

Is there any way to validate this on the client and server without custom validation masks?

Bob Gilmore
  • 12,608
  • 13
  • 46
  • 53
Alexey Berezuev
  • 785
  • 9
  • 27

3 Answers3

5

MaskedInput will only generate a text field. I presume that your phone field is being stored as an integer. You'll have to change your validation of the phone field to be text, rather than integer. You may need to change the field type in your database to be varchar(14)

Joe Miller
  • 3,843
  • 1
  • 23
  • 38
2

You could put on the MaskedInput removeMaskOnSubmit to true, like this

<?= $form->field($model, 'phone')->widget(MaskedInput::classname()([
'mask' => '(999) 999-9999',
'clientOptions' => [
    'removeMaskOnSubmit' => true,
]); ?>

So you have to disable the client validation on the form

$form = ActiveForm::begin([
    'enableClientValidation'=>false,
]); ?>
JPSerra
  • 51
  • 4
0

I had similar problem and solved it easily with beforeValidateAttribute event and this code:

$('#w0').on('beforeValidateAttribute', function (e) {
    var paymentAmountElement = $('#w0').yiiActiveForm('find', 'payment-amount');
    var oldValidate = paymentAmountElement.validate;

    paymentAmountElement.validate = function (attribute, value, messages, deferred, form) {
        value = !value.length ? value : value.match(/\d+/g).join('');
        oldValidate(attribute, value, messages, deferred, form);
    }
});

I had an amount input in payment model, so its id is payment-amount. I saved the original validate function (because I had some others rules like required and number and I'm really lazy to writing them again) and remove mask with regular expression, then run original validate function with new value. You just need to make a regular expression for your case and use this approach for solving problem.

meysam
  • 1,754
  • 2
  • 20
  • 30