Wednesday 7 November 2012

Valilang

I have started a new project. Its name is valilang.

Create validation rules in a single format, meant to be used in both client and server sides.

Although I have given up my first plan of making valilang a minimal imperative programming language, the name still has the suffix "lang". I have opted to base the language syntax upon JSON, so it will be easier to learn and use.

The format is very easy to write. There are :

  • fields, which correspond to form fields, and
  • rules, which are (mostly premade) short functions taking a value argument and doing an assertion upon that value.

A valilang file will have an object with these keys:

  • fields, a list of fields.
  • fieldValidation, an object mapping field names to a list of rules applied sequentially to these fields.

Here is an example valilang file, for a form with a single field:

    {
        "fields": ["name"],
        "fieldValidation": {
            "name": [
                "required",
                "min-10",
                "max-50"
            ]
        }
    }

In the above object, we can see we have a single field name which has the following rules:

  • It's a required field
  • It takes at least ten characters (min-10)
  • and at most 50 characters (max-50).

These rules (which are actually functions) are executed sequentially, until any function returns null, in which case the validation fails.

Notice how arguments are handled. They are extracted from after the dash in each of the rule strings, provided these strings have a dash.

On the client side, you just have to include a valilang file and valilang.js.

    <script type="text/x-valilang">
        {
            "fields": ["name"],
            "fieldValidation": {
                "name": [
                    "required",
                    "min-10",
                    "max-50"
                ]
            }
        }
    </script>
    <script type="text/javascript" src="valilang.js"></script>

On the server side, you will load the valilang library for your framework or language, and ask it to validate your fields.

Of course this is all when both the client side and the server side are implemented. Remote loading of scripts is not yet supported. The server side hasn't been prepared for any language except for javascript (by requireing valilang.js in node and using its API), and there are too few validators (validation functions). Also unit testing is not done for the client or the server.

However, valilang.js is definitely compact, under 5 kb minified, and it is in a nearly usable state. Care to try it out and maybe contribute to its development? Report bugs and fork the github repository.

No comments:

Post a Comment