Search code examples
jqueryvalidationyii2unique

How to unique validation two value that one of them has punctuations in yii2?


In my form, I've a textfield that has been set with jquery-masked-input, this is the jquery script:

<script>
jQuery(function ($) {
    $("#reg-number").mask("99.999.999.9-999.999");
});
</script>

and then, the value will be saved into database without punctuation. So when I input value like this: enter image description here

will be save in mysSQL database like this:

enter image description here

But I need to set this field as unique. So I add this validation in my model.php:

public function rules()
{
    return [
        [['regNumber'], 'required'],
        [['regNumber'], 'string', 'max' => 32, 'min' => 15],
    ];
}

But it didn't work, I guess it because the value from textfield contain punctuation and in the database column doesn't contain punctuation.

How do I can make it work?

Thanks


Solution

  • Try using Filter validator.

    ['regNumber', 'filter', 'skipOnArray' => true, 'filter' => function ($value) {
       return preg_replace("/[^a-zA-Z 0-9]+/", "", $value);
    }],
    [['regNumber'], 'string', 'max' => 32, 'min' => 15],
    [['regNumber'], 'unique'],
    

    Not tested though :)