How to use Yii2 Custom Validation?

how to use yii2 custom validation
Yii2 Custom Validation

Yii2

How to use Yii2 Custom Validation?

Learn how to use Custom Validation in Yii2 with examples.

Sometimes you have a situation where you need some kind of validation that is NOT covered in Yii2 core validators. This validation is often called custom validation, ad-hoc or call back.

So what is Custom Validation? Well the idea is we are coming up with our own sets of rules to achieve certain kind of validation.

Let’s create our own example to see how these call backs actually works.

Go to your model and under the rules section you will find all of your core validation rules. Here we will specify our custom validation rule.

See you have a new rule here  ['article_type','validateType']  validateType is the name of your custom validation you could make this anything at all. Now this name is going to be used in our own custom method.

In this above custom validateType()  function we are comparing field article_type  and return error if matched. As a matter of fact we could have used compare or match validators from core validators but the point is this could be any rule you want.

Here is another sophisticated example, let’s do some custom validation on more than one field.

Modify your rule to add another parameter called params ['article_type','validateType','params'=>['article_by'=>article_by]]  and add another condition in your custom validation function.

Here params array is used to pass other fields in your custom validation function.

Now if you select research as “Article Type” and type “Husnain” as Author, It will throw an error message saying “Author Husnain is not allowed to see research Articles”.

To validate attributes only when certain conditions met, for example the validation of one attribute depends on the value of another attribute you can use the when property to define such conditions.

If you also need to support client-side conditional validation, you should configure the whenClient property which takes a string representing a JavaScript function whose return value determines whether to apply the rule or not.

Like:

In this above validation rule article_type  will be REQUIRED if and only if article_by  is equal to “Husnain”. In simple words if author “Husnain” is selected you will have to add Article Type.

That’s it, If you find any thing confusing please let me know in the comment section below.

I am a Sr. Android App & Web Developer having 5 plus years of extensive hands-on experience in Object Oriented Programming, Database Design and Implementation using Agile & UML. Pro in Yii2 PHP Framework, Android App Development, MYSQL & a Blockchain enthusiast.

Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *

More in Yii2

Recent Posts

Categories

Tags

To Top