Krajee

Yii2 Validators

Thankful to Krajee! BUY A COFFEEor to get more out of us.

This extension adds new model validator components for Yii2 frameworkor and/or enhances existing Yii2 model validators. The following validators are supported

Tip

Not seeing the updated content on this page! Hard refresh your browser to clean cache for this page (e.g. SHIFT-F5 on Windows Chrome)

The yii2-validators extension can be installed automatically or manually using one of these options:

Composer Package Manager Recommended


Installation via Composer is the recommended and most easy option to install Krajee Yii2 extensions. You can install yii2-validators via composer package manager. Either run:

$ php composer.phar require kartik-v/yii2-validators "dev-master"

or add:

"kartik-v/yii2-validators": "dev-master"

to your application's composer.json file.

Manual Install


You may also manually install the extension to your project (in case your composer install does not work). Just download the source ZIP or TAR ball and extract the extension asset files and folders into your project. You may need to install dependencies manually and also set the namespaces to the extensions in your Yii2 extensions configurations manually.

The EmailValidator extends the yii\validators\EmailValidator component to support multiple email inputs for Yii2 framework. In addition this validator allows setting the multiple property and setting the min and max number of email addresses allowed. This is useful for adding validation rules to your attributes in the model and also adds enhanced client validation support for ActiveForm inputs at runtime via Javascript.

The EmailValidator supports all the options and settings included with the yii\validators\EmailValidator. In addition, the following options are supported.

multiple

boolean, whether multiple email addresses are supported. Defaults to to true, whereby multiple emails can be entered in the input separated by the delimiter property.

delimiter

string, the delimiter to separate multiple emails. Defaults to , (COMMA character). This property is valid only when the multiple property is set to true).

min

integer, minimum number of emails required (applicable only when the multiple property is true). Setting this to 0 or NULL will mean no minimum limit.

max

integer, maximum number of emails required (applicable only when the multiple property is true). Setting this to 0 or NULL will mean no maximum limit.

minThresholdMessage

string,the message when the number of emails are below the min property threshold. If not set, this property will default to the following:

Yii::t('kvvalidator', 'At least {value, number} {value, plural, one{email is} other{emails are}} required.');

maxThresholdMessage

string,the message when the number of emails are above the max property threshold. If not set, this property will default to the following:

Yii::t('kvvalidator', 'A maximum of {value, number} {value, plural, one{email is} other{emails are}} allowed.');

message

string,the user-defined error message if the entered email is invalid. It may contain the following placeholders which will be replaced accordingly by the validator:

  • {attribute}: the label of the attribute being validated

  • {value}: the value of the attribute being validated

If not set, this property will default to the following:

Yii::t('kvvalidator', '"{value}" is not a valid email address.');

The EmailValidator class can be easily used via the alias k-email in your model validation rules as seen in the example(s) below.

// Your model
// app/models/EmailModel.php
use yii\db\ActiveRecord;
use kartik\validators\EmailValidator;

class EmailModel extends ActiveRecord {
    
    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            [['to', 'cc', 'bcc'], 'k-email', 'allowName' => true, 'enableIDN' => true, 'max' => 5],
            // or you can alternatively use the class name
            // [['to', 'cc', 'bcc'], EmailValidator::class, 'allowName' => true, 'enableIDN' => true, 'max' => 5],
        ];
    }
}

// Your View 
// app/views/email/send.php

<?php 
use kartik\form\ActiveForm;
use yii\helpers\Html;
$form = ActiveForm::begin(['enableClientValidation' => true]);
$emailOpts = ['placeholder' => 'Enter email addresses separated by comma'];
?>
<?= $form->field($model, 'to')->textInput($emailOpts) ?>
<div class="row">
    <div class="col-md-6">
        <?= $form->field($model, 'cc')->textInput($emailOpts) ?> 
    </div>
    <div class="col-md-6">
        <?= $form->field($model, 'bcc')->textInput($emailOpts) ?>
    </div>
</div>
<?= $form->field($model, 'subject')->textInput(['placeholder' => 'Enter message subject']) ?>
<?= $form->field($model, 'body')->textarea(['rows' => 5, 'placeholder' => 'Enter message body']) ?>
<div class="form_group text-right text-end">
    <?= Html::resetButton('Reset', ['class' => 'btn btn-secondary btn-default']) ?>
    <?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>

The PhoneValidator extends the yii\validators\Validator component using libphonenumber-for-php based on Google's libphonenumber library. The PhoneValidator supports only server based validation and does not currently support client validation via javascript.

The PhoneValidator supports all the options and settings included with the yii\validators\Validator. In addition, the following options are supported.

countryAttribute

string, the model attribute name that stores the country code value.

countryValue

string, the value for country code. This will override any value set in countryAttribute. This is the ISO 3166-1 two letter country code. If the number is passed in an international format (e.g. +44 117 496 0123), then the region code is not needed, and can be null. Failing that, the library will use this value to work out the phone number based on rules loaded for that region.

countryRequired

boolean, whether country code is mandatory for parsing the phone number. Defaults to to true.

applyFormat

boolean, whether to apply the parsed phone format and update the attribute. Defaults to to true.

format

string, the format to use when applying the format. Defaults to to PhoneNumberFormat::INTERNATIONAL.

message

string, the message to show if an invalid phone number is parsed.

If not set, this property will default to the following:

Yii::t('kvvalidator', '"{value}" does not seem to be a valid phone number.');

countryRequiredMessage

string, the message to show if country value is empty and countryRequired is true.

If not set, this property will default to the following:

Yii::t('kvvalidator', 'Country is required for phone validation.');

parseExceptionMessage

string,he message to show when a NumberParseException is thrown during phone number parsing.

If not set, this property will default to the following:

Yii::t('kvvalidator', 'Unexpected or unrecognized phone number format.');

The PhoneValidator class can be easily used via the alias k-phone in your model validation rules as seen in the example(s) below.

Reset
// Your model
// app/models/ContactModel.php
use yii\db\ActiveRecord;

class ContactModel extends ActiveRecord {
    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            [['phone_1'], 'k-phone', 'countryValue' => 'US'],
            [['phone_2'], 'k-phone', 'countryAttribute' => 'country'],
            [['country'], 'default', 'value' => 'GB'], // a default value for the country attribute
        ];
    }
}

// Your View 
// app/views/contact.php

<?php 
use kartik\form\ActiveForm;
use yii\helpers\Html;

$form = ActiveForm::begin();
?>
<div class="row">
    <div class="col-md-6">
        <?= $form->field($model, 'phone_1')->textInput(['placeholder' => 'Enter phone in US format']) ?>
    </div>
    <div class="col-md-6">
        <?= $form->field($model, 'phone_2')->textInput(['placeholder' => 'Enter phone in GB format']) ?>
    </div>
</div>
<div class="form_group text-right text-end">
    <?= Html::resetButton('Reset', ['class' => 'btn btn-secondary btn-default']) ?>
    <?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>

The CardValidator extends the yii\validators\Validator component. It validates standard debit and credit card number inputs using Luhn's checksum validation. It also helps auto detect the card types and additionally validating the card holder name, expiry date and CVV entered. The CardValidator supports only server validation and does not currently support client validation via javascript.

The CardValidator supports all the options and settings included with the yii\validators\Validator. In addition, the following options are supported.

cards

array, holds the configurations for each of the credit / debit cards including the card lengths and regex patterns to check for valid card number prefixes. Defaults to the following configuration:

[
    // Debit cards must come first, since they have more specific patterns than their credit-card equivalents.
    CardValidator::ELECTRON => [
        'pattern' => '/^(?:417500|4026\\d{2}|4917\\d{2}|4913\\d{2}|4508\\d{2}|4844\\d{2})\\d{10}$/',
        'cvvLength' => [3],
        'luhn' => true,
    ],
    CardValidator::MAESTRO => [
        'pattern' => '/^(5018|5020|5038|6304|6759|6761|6763)[0-9]{8,15}$/',
        'cvvLength' => [3],
        'luhn' => true,
    ],
    CardValidator::FBF => [
        'pattern' => '/^600[0-9]{13}$/',
        'cvvLength' => [3],
        'luhn' => true,
    ],
    CardValidator::DANKORT => [
        'pattern' => '/^5019[0-9]{12}$/',
        'cvvLength' => [3],
        'luhn' => true,
    ],
    // Credit cards
    CardValidator::VISA => [
        'pattern' => '/^4[0-9]{12}([0-9]{3})?$/',
        'cvvLength' => [3],
        'luhn' => true,
    ],
    CardValidator::MASTERCARD => [
        'pattern' => '/^(5[0-5]|2[2-7])[0-9]{14}$/',
        'cvvLength' => [3],
        'luhn' => true,
    ],
    CardValidator::AMEX => [
        'pattern' => '/^3[47][0-9]{13}$/',
        'cvvLength' => [3, 4],
        'luhn' => true,
    ],
    CardValidator::CARTE_BLANCHE => [
        'pattern' => '/^389[0-9]{11}$/',
        'cvvLength' => [3],
        'luhn' => true,
    ],
    CardValidator::DINERS => [
        'pattern' => '/^3(?:0[0-5]|[68][0-9])[0-9]{11}$/',
        'cvvLength' => [3],
        'luhn' => true,
    ],
    CardValidator::BC_GLOBAL => [
        'pattern' => '/^(6541|6556)[0-9]{12}$/',
        'cvvLength' => [3],
        'luhn' => true,
    ],
    CardValidator::DISCOVER => [
        'pattern' => '/^65[4-9][0-9]{13}|64[4-9][0-9]{13}|6011[0-9]{12}|(622(?:12[6-9]|1[3-9][0-9]|[2-8][0-9][0-9]|9[01][0-9]|92[0-5])[0-9]{10})$/',
        'cvvLength' => [3],
        'luhn' => true,
    ],
    CardValidator::INSTA_PAY => [
        'pattern' => '/^63[7-9][0-9]{13}$/',
        'cvvLength' => [3],
        'luhn' => true,
    ],
    CardValidator::JCB => [
        'pattern' => '/^(3[0-9]{4}|2131|1800)[0-9]{11}$/',
        'cvvLength' => [3],
        'luhn' => true,
    ],
    CardValidator::VOYAGER => [
        'pattern' => '/^8699[0-9]{11}$/',
        'cvvLength' => [3],
        'luhn' => true,
    ],
    CardValidator::KOREAN_LOCAL => [
        'pattern' => '/^9[0-9]{15}$/',
        'cvvLength' => [3],
        'luhn' => true,
    ],
    CardValidator::SOLO => [
        'pattern' => '/^(6334[5-9][0-9]|6767[0-9]{2})\\d{10}(\\d{2,3})?$/',
        'cvvLength' => [3],
        'luhn' => true,
    ],
    CardValidator::SWITCH_CARD => [
        'pattern' => '/^(4903|4905|4911|4936|6333|6759)[0-9]{12}|(4903|4905|4911|4936|6333|6759)[0-9]{14}|(4903|4905|4911|4936|6333|6759)[0-9]{15}|564182[0-9]{10}|564182[0-9]{12}|564182[0-9]{13}|633110[0-9]{10}|633110[0-9]{12}|633110[0-9]{13}$/',
        'cvvLength' => [3],
        'luhn' => true,
    ],
    CardValidator::LASER => [
        'pattern' => '/^(6304|6706|6709|6771)[0-9]{12,15}$/',
        'cvvLength' => [3],
        'luhn' => true,
    ],
    CardValidator::UNIONPAY => [
        'pattern' => '/^(62|88)[0-9]{14,17}$/',
        'cvvLength' => [3],
        'luhn' => false,
    ],
]

allowedCards

array, list of allowed cards. If not set or empty, all cards set in cards will be allowed. For example, to allow only VISA and MASTERCARD, set this to: [CardValidator::VISA, CardValidator::MASTERCARD].

autoUpdateNumber

boolean, whether to auto update the card number as pure numeric digits and overwrite the model attribute. Defaults to to true.

autoUpdateType

boolean, whether to auto update and store the auto detected type within the typeAttribute. Applicable only when autoDetectType is set to true. Defaults to to true.

validateHolder

boolean, whether to validate the card holder name. Defaults to to true.

validateExpiry

boolean, whether to validate the card expiry date (year / month). Defaults to to true.

validateCVV

boolean, whether to validate the card CVV (Card Verification Value). Defaults to to true.

format

string, the format to use when applying the format. Defaults to to CardNumberFormat::INTERNATIONAL.

typeAttribute

string, the card type attribute. Refer the cards property for valid card types.

holderAttribute

string, the card holder name attribute.

expiryYearAttribute

string, the card expiry year attribute.

expiryMonthAttribute

string, the card expiry month attribute.

cvvAttribute

string, the card CVV attribute.

typeValue

string, the card type value to check. Refer the cards property for valid card types.

holderValue

string, the card holder name value to check.

expiryYearValue

string, the card expiry year value to check.

expiryMonthValue

string, the card expiry month value to check.

cvvValue

string, the card CVV value to check.

holderPattern

string, the regular expression pattern to match for card holder name. Defaults to /^[a-z ,.\'-]+$/i.

message

string,the user-defined error message if an invalid credit card number is entered. It may contain the following placeholders which will be replaced accordingly by the validator:

  • {attribute}: the label of the attribute being validated

  • {value}: the value of the attribute being validated

  • {number}: the input credit card number

If not set, this property will default to the following:

Yii::t('kvvalidator', '"{number}" is not a valid card number.');

invalidTypeMessage

string, the message shown if the detected card type is invalid.

If not set, this property will default to the following (the token {number} will be replaced by the input card number):

Yii::t('kvvalidator', 'Unsupported card number "{number}"');

invalidHolderMessage

string, the message shown if the detected card holder is invalid.

If not set, this property will default to the following (the token {holder} will be replaced by the input card holder):

Yii::t('kvvalidator', 'Invalid holder name "{holder}"');

invalidExpiryMessage

string, the message shown if the detected card expiry year or month is invalid.

If not set, this property will default to the following (the token {expiry} will be replaced by the input card expiry year/month):

Yii::t('kvvalidator', 'Invalid expiry month/year "{expiry}"');

invalidCVVMessage

string, the message shown if the detected card CVV is invalid.

If not set, this property will default to the following (the token {cvv} will be replaced by the input card CVV):

Yii::t('kvvalidator', 'Invalid CVV "{cvv}"');

The CardValidator class can be easily used via the alias k-card in your model validation rules as seen in the example(s) below.

NOTE The example below does not store any of the input fields and only does a validation on the fly. You can use some of sample credit card numbers to test.

Reset
// Your model
// app/models/PaymentModel.php
use yii\db\ActiveRecord;

class PaymentModel extends ActiveRecord {
    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            [
                ['card_number'],
                'k-card',
                'typeAttribute' => 'card_type',
                'holderAttribute' => 'card_holder',
                'expiryYearAttribute' => 'card_expiry_year',
                'expiryMonthAttribute' => 'card_expiry_month',
                'cvvAttribute' => 'card_cvv'
            ],
            [['card_type'], 'safe'],
            [['card_number', 'card_holder', 'card_expiry_year', 'card_expiry_month', 'card_cvv'], 'required'],
        ];
    }
}

// Your View 
// app/views/payment.php

<?php 
use kartik\form\ActiveForm;
use yii\helpers\Html;
use yii\helpers\Url;

$session = Yii::$app->session;
$form = ActiveForm::begin(['options' => ['class' => 'krajee-example-form']]);
$this->registerCss('.krajee-example-form .help-block{display:none}'); // hide field level error blocks
?>
<div class="center-block card p-3" style="max-width:450px;background-color: #fff">
    <?= $form->errorSummary($model) ?>
    <?php if ($session->hasFlash('success')) :?>
    <div class="alert alert-success">
        <i class="fa fa-thumbs-up"></i> 
        <?= $session->getFlash('success') ?>
    </div>
    <?php endif;?>
    <div class="row">
        <div class="col-md-6">
            <?= $form->field($model, 'card_number')->textInput(['placeholder' => 'Card number'])->label(false) ?>
        </div>
        <div class="col-md-6">
            <?= $form->field($model, 'card_holder')->textInput(['placeholder' => 'Card holder name'])->label(false) ?>
        </div>
    </div>
    <?= $form->field($model, 'card_type')->textInput(['disabled' => true, 'placeholder' => 'Card Type (auto detected)'])->label(false) ?>
    <div class="row">
        <div class="col-md-4">
            <?= $form->field($model, 'card_expiry_month')->textInput(['placeholder' => 'MM'])->label(false) ?>
        </div>
        <div class="col-md-4">
            <?= $form->field($model, 'card_expiry_year')->textInput(['placeholder' => 'YYYY'])->label(false) ?>
        </div>
        <div class="col-md-4">
            <?= $form->field($model, 'card_cvv')->textInput(['placeholder' => 'CVV'])->label(false) ?>
        </div>
    </div>
    <div class="form_group text-right text-end">
        <?= Html::resetButton('Reset', ['class' => 'btn btn-secondary btn-default']) ?>
        <?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
    </div>
</div>
<?php ActiveForm::end(); ?>

The JsonValidator extends the yii\validators\Validator component. It validates JSON input in text area fields. The validator also helps to format and overwrite the JSON input as a pretty format via prettify property. It includes both server and client side validations.

The JsonValidator supports all the options and settings included with the yii\validators\Validator. In addition, the following options are supported.

prettify

boolean, whether to prettify the json output and overwrite the attribute with a prettified JSON. Defaults to to true. This property will only be applied on server side validation of the attribute.

The JsonValidator class can be easily used via the alias k-json in your model validation rules as seen in the example(s) below.

Reset
// Your model
// app/models/ConfigModel.php
use yii\db\ActiveRecord;

class ConfigModel extends ActiveRecord {
    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            [['config_json', 'validation_list'], 'required'],
            [['config_json'], 'k-json', 'prettify' => true],
            [['validation_list'], 'k-json', 'prettify' => false],
        ];
    }
}

// Your View 
// app/views/config.php

<?php 
use kartik\form\ActiveForm;
use yii\helpers\Html;
// a monospace CSS for JSON input
$this->registerCss('.json-text{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;');
$form = ActiveForm::begin();
?>
<?= $form->field($model, 'config_json')->textarea([
    'class' => 'form-control json-text',
    'placeholder' => 'Enter JSON configuration...'
]) ?>
<?= $form->field($model, 'validation_list')->textarea([
    'class' => 'form-control json-text',
    'placeholder' => 'Enter the validation list as JSON key value pairs...'
]) ?>
<div class="form_group text-right text-end">
    <?= Html::resetButton('Reset', ['class' => 'btn btn-secondary btn-default']) ?>
    <?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>

yii2-validators is released under the BSD-3-Clause License. See the bundled LICENSE.md for details.

Note

You can now visit the Krajee Webtips Q & A forum for searching OR asking questions OR helping programmers with answers on these extensions and plugins. For asking a question click here. Select the appropriate question category (i.e. Krajee Plugins) and choose this current page plugin in the question related to field.

The comments and discussion section below are intended for generic discussions or feedback for this plugin. Developers may not be able to search or lookup here specific questions or tips on usage for this plugin.

 
visitors to Krajee Yii2 Demos since 22-May-2017