Skip to content

Instantly share code, notes, and snippets.

@ballerina-github-bot
Created September 25, 2023 06:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ballerina-github-bot/03b42e463700fc3e1a0d0ff0c32aa964 to your computer and use it in GitHub Desktop.
Save ballerina-github-bot/03b42e463700fc3e1a0d0ff0c32aa964 to your computer and use it in GitHub Desktop.
examples/constraint-validations
import ballerina/constraint;
// Constraint on the `int` type.
@constraint:Int {
minValue: 18
}
type Age int;
type Student record {|
// Constraint on the `string`-typed record field.
@constraint:String {
pattern: re`[0-9]{6}[A-Z|a-z]`
}
string id;
string name;
// Constrained type used as a record field.
Age age;
// Constraint on the `string[]`-typed record field.
@constraint:Array {
minLength: 1,
maxLength: 10
}
string[] subjects;
|};
public function main() returns error? {
Student student = {
id: "200146B",
name: "David John",
age: 25,
subjects: ["Maths", "Science", "English"]
};
// To validate the constraints on the `Student` record, the `validate` function should be
// called explicitly. If the validation is successful, then, this function returns the type
// descriptor of the value that is validated.
student = check constraint:validate(student);
// Set the student's age to 17, which will violate the `minValue` constraint on `Age`.
student.age = 17;
// When the validation fails, the `validate` function returns a `constraint:Error`.
student = check constraint:validate(student);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment