XRule

Add User Defined Rules

Make more complicated rule.

Following example shows how to define a rule. Look at the call-back function's first argument 'x'. It is an instance of XRow. It has 5 properties. Those are 'label', 'el', 'rule', 'value' and 'message'. 'el' is an INPUT HTML DOM element and 'label' is a LABEL HTML DOM element's text(string) which is bound to this 'el'. 'rule' is parsed data-xr attribute of 'el' by XRule. 'value' is a string value of 'el'. 'message' is a violation message text(string) of 'el'. Second argument p is an array which has rules's arguments specified in data-xr attribute. In this example p is exactly equal to ["NAME", "aaa", "bbb", "ccc"]. p[0] is "NAME", p[1] is "aaa", p[2] is "bbb" and p[3] is "ccc". XRule get label text automatically and put it into p[0]. If there is no label bound then p[0] will be empty string. Third argument m is message string which is not assembled with array p. In this example 'm' is "Input a value among '{1}', '{2}', '{3}' for {0}". Highlight is format function. Just write "m.format(p)" when you compose a call-back function. It will make a assembled string. {0}~{n} will match p[0]~p[n].

<script>
    xr.put("allow", "Input a value among '{1}', '{2}', '{3}' for {0}", function(x, p, m){
        if (p.indexOf(x.value) < 0) x.message = m.format(p);
    });
</script>
<form onsubmit="return xr(this)">
  <label>NAME
    <input data-xr="allow(aaa, bbb, ccc)">
  </label>
<input type="submit"> </form>

Let's test how it works. Click submit button below.

Demo