๐Ÿ‘ฎCreating Your First Rule

In this section we will see how to create your first rule with Polyrule. You can choose one of supported data format for writing it, for our examples, we are going to use json.

Let's create a rule for manage user creation :

{
  "username": {
    "type": "string",
    "message": "this username is invalid",
    "rules": {
      "regex": "^[a-zA-Zร€-ร–ร˜-รถรธ-รฟ ']+$",
      "min": 4,
      "max": 50
    }
  },
  "password": {
    "type": "string",
    "message": {
      "number": "%s must include one or multiple numbers",
      "lower": "%s must include one or multiple lowercase characters",
      "upper": "%s must include one or multiple uppercase characters",
      "special": "%s must include one or multiple special characters"
    },
    "rules": {
      "regex": {
        "number": "\\d",
        "lower": "[a-z]",
        "upper": "[A-Z]",
        "special": "\\W"
      },
      "min": 8,
      "max": 130
    }
  }
}

In our example, we need to validate two fields : username and password. Like you can see, it's pretty easy read it. We have, for each object, three main part :

  • type, that allows you to define a strict type.

  • message, that allows you to define custom message for your rule, you can give it any type, like a string for username or an object for password.

  • rules, that allows you to declare your rules, in our example, we use regex, min and max.

Now, we want to translate it to javascript for example, let's see how to use Polyrule. Open a terminal then run the following command in it :

polyrule build --lang js -i user.json -o user.js

New file called user.js should be created in your current directory :

export const UserRules = {
 username: {
  message: 'this username is invalid',
  validate(input, withErrors = false) {
   const errors = [];

   if (input.length < 4) {
    errors.push('min');
   }

   if (input.length > 50) {
    errors.push('max');
   }

   if (!/^[a-zA-Zร€-ร–ร˜-รถรธ-รฟ ']+$/.test(input)) {
    errors.push('regex');
   }

   if (withErrors) {
    return {
     errors: errors,
     valid: errors.length === 0,
    }
   }

   return errors.length === 0
  },
 },
 ...
};

Data format can be a little different depending on the programming language, if you use go, you can't return mixed value, we need to create two methods instead of withErrors parameter.

If you want to use this example, you can import it in your wanted javascript file and use it like that :

import { UserRules } from "./user.js"

console.log(UserRules.password.validate("test1234", true));

Output should be :

{
  errors: [ 'regex.upper', 'regex.special' ],
  valid: false
}

Last updated