Search code examples
ballerinaballerina-swan-lake

How to add constraints on ballerina record fields?


I have requirement where I need to validate the record fields after receiving a value for the record type. How can I have put constraints and how can I validate those constraints?

type User record {|
    string username; // more than 6 chars
    string password; // some strong password
    string email;   // valid email
|};

Solution

  • You can use the ballerina constraint module to validate record fields. Using this module you can add constraints for arrays, strings, numbers and dates. You can find the relevant api docs using this link.

    In the below code example will help to understand how to validate a record.

    import ballerina/io;
    import ballerina/constraint;
    
    type User record {|
        @constraint:String {
            minLength: 6
        }
        string username; // more than 6 chars
    
        @constraint:String {
            pattern: re `([a-zA-Z0-9._%\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,6})*`
        }
        string email;   // valid email
    
        @constraint:Int {
            minValue: 18,
            maxValue: 24
        }
        int age;
    
        @constraint:Array {
            maxLength: 6
        }
        string[] qualifications;
    
        @constraint:Date {
            option: "PAST"
        }
        record {
            int year;
            int month;
            int day;
        } dob;
    |};
    
    public function main() returns error? {
        User user = {
            qualifications: [],
            dob: {year: 1999, month: 12, day: 1},
            email: "username@gmail.com",
            age: 19,
            username: "newusername"
        };
        User validatedUser = check constraint:validate(user);
        io:println(validatedUser);
    }