Custom Validators
You can write custom validations that give users feedback about required syntax, types, and acceptable values in your provider. The Framework has a collection of predefined validators. Refer to Predefined Validators to learn how to use them.
This page explains how to migrate attribute validation functions from SDKv2 to attribute validators in the Framework.
SDKv2
In SDKv2, arbitrary validation logic can be applied to individual attributes by using ValidateFunc
and/or
ValidateDiagFunc
.
The following example shows the implementation of a validation that ensures that an integer attribute has a value greater than one.
Framework
In the Framework, you implement either type of validation by setting the Validators
field on the schema.Attribute
implementation.
The following example shows how to implement a validation that ensures that an integer attribute has a value greater than one.
Migration Notes
Remember the following details when migrating from SDKv2 to the Framework.
- In SDKv2,
ValidateDiagFunc
is a field onschema.Schema
that you can use to define custom validation functions. In the Framework,Validators
is a field on eachschema.Attribute
implementation that can be used for custom validations. - Use predefined validators when there is a validator that meets your requirements.
Example
SDKv2
The following example shows the implementation of the ValidateDiagFunc
field for
the exampleResource
's example_attribute
attribute to validate that it's value is at least 1 (greater than zero).
Framework
The following shows the same section of provider code after the migration.
This code validates that the exampleResource
's example_attribute
attribute is greater than zero by using a custom AtLeast
validator.
This example code illustrates how you can implement your own validators.