About Me

My photo
Kozyatağı, İstanbul, Türkiye

Sunday, September 22, 2013

Rule Expression User Input Validation

If you are developing a business rule engine; your application needs to have an admin page that rules are defined through.

For example, imagine we are creating campaign rules:
"If the sum of the amounts of customers transactions within last 24 hours exceeds 10.000 or count exceeds 10 then send him an SMS"

In the rule definition pane, admin user inputs an expression like: "(R1 || R2) && R3"
Rule expressions are generally written in a free text format by the user.  Because user may insert parentheses, group rules and combine them.

The input of user has to be validated before saving it. Because syntax of such an expression above may be incorrect, may have missing parentheses, etc.

The easiest and effortless way of performing this validation is, using JavaScript eval() function:

function IsValidRuleText() {
    var txt = $('#txtInput').val();
    if (txt.length == 0) {
        return false;
    }
    var replaced = txt.replace(/R\d+/gi, "true");
    try {
        if (eval(replaced) == true) {
            // Trivial Comparison. Just for test if throws error.
        }
    } catch (err) {
        return false;
    }
    return true;
}

All the numbered [R] expressions are determined with regex. Then regex matches are replaced with "true" string. Now, final string contains "true" words and punctuation characters ((, ), &&, || ). If the "eval()" function successfully evaluates the replaced expression, then the expression is valid. If it throws error, then the expression has syntax errors.

No comments:

Post a Comment