Range Attribute, Custom Attribute & Custom Validation – Session 39

Range Attribute - Custom Attribute & Custom Validation

In this session of ASP.NET 5.0 / Core Tutorial, we will talk about Range Attribute, Custom Attribute and Custom Validation in detail. In continuation of Session 38, we are going to introduce one more validation attribute which is Range attribute. Also, we will show you the way that you can customize the attributes and the way that you can create a custom validation attribute.

Range Attribute

This attribute can set a range of valid value for each property with different property type. Also, Range attribute is in System.ComponentModel.DataAnnotations namespace, thus, for using this attribute, we need to add this namespace to the Model or the ViewModel. Moreover, it has several version of overload that can be used based on our requirement.

As you can see in above code, we decorate Amount and Date properties with Range Attribute.

Custom Attribute in ASP.NET 5.0 / Core

For this purpose, we need to create a class which should be inherited form the attribute that we want to customize. We can create the class everywhere in our project, but to keep the project structure clear, we recommend creating a specific folder for this purpose. Also, for as we need to use Attribute classes, we should add their namespace (System.ComponentModel.DataAnnotations) to the class.

Then we can do the required customization with the Base method.

For example, we customized StringLengthAttribute and created AllowedCharcterLength attribute. AllowedCharcterLength attribute does not need any input parameter and we can decorate string properties with this attribute. the decorated property with this attribute, would have maximum length of 10 characters.

Create Custom Validation in ASP.NET 5.0 / Core

For creating custom validation, again we need to create a class and the class should be inherited form ValidationAttribute class. Also, again we need to add System.ComponentModel.DataAnnotations namespace to the created class.

Then, we should override IsValid method and set the required conditions. Later, based on the value and the condition, method return a Boolean result.

For example, AllowedCharacterRange attribute checks the string length and return true if the string is between 5 to 10 characters.

If you need more details, watch this session video. Also, for being updated about our coming sessions, follow us on Instagram, Facebook, Telegram or YouTube. Also you can have access to list of all sessions HERE.

You can download this Session Slides form HERE

0.00 avg. rating (0% score) - 0 votes


0 0 votes
Article Rating

Inline Feedbacks
View all comments