Introduction


This namespace contains validation functions.
Spacer uses drivers to show error messages. Every driver has its own implementation to show error messages. Let's take this example:

Hint: For bootstrap3 and listOfErrors drivers, click validate button and try to enter some values.



Validation Patterns


Spacer has several patterns to validate input fields. Think of pattern as a type validator such as integer and email. Each pattern has several rules to force additional validation such as min and max. Rules may require parameters such as max:255. When using validation consider the following syntax rules:

  • Each input may have one pattern or none. Combining patterns results in syntax error.
  • Pattern's rules must be enclosed with square brackets []. If no rules used, then the brackets [] are optional.
  • Pattern may have one or more rules separated with pipe symbol |.
  • Rule may have one or more parameters. Separate rule name from the parameters with colon :.
  • Rule parameters are separated with comma ,.

When your pattern conflict with the previous syntax rules, the Lexical Unit will throw a Syntax Error.


Available Patterns With Rules


Here is a list of all validation patterns with their possible rules:

Integer

integer[required|positive|negative|min:a|max:b|range:a,b|not:n1,n2,n3|confirmed:inputName]

Integer pattern passes validation if the input value is a valid integer number.

Rule Pass condition
required Value is present
positive Value is positive
negative Value is negative
min:a Value is larger than or equal to a
Note: min rule accepts 2nd parameter (i or o) that indicates whether the 1st parameter is valid or not.
i (of in which the default) indicates the the 1st parameter is valid.
o (of out) indicates the the 1st parameter is not valid.
max:b Value is less than or equal to b
Note: max rule accepts 2nd parameter (i or o) that indicates whether the 1st parameter is valid or not.
i (of in which the default) indicates the the 1st parameter is valid.
o (of out) indicates the the 1st parameter is not valid.
range:a,b Value is in the range [a, b]. Note that a and b are inside the range by default
Note: range rule accepts 3rd parameter (combination of i and o) that indicates whether the 1st and the 2nd parameters are valid or not.
ii (default) indicates the the 1st and the 2nd parameters are valid.
io indicates the the 1st parameter is valid and the 2nd parameter is not valid.
oi indicates the the 1st parameter is not valid and the 2nd parameter is valid.
oo indicates the the 1st and the 2nd parameters are not valid.
not:n1,n2,n3 Value is not n1 nor n2 nor n3. Note that you can add more parameters as much as you need
confirmed:inputName The validated input and the input whose name is inputName have the same value. Note: if this rule used without parameter i.e. confirmed, then Spacer assume the confirmation input name to be the same as validated input name suffixed with _confirmation
Example: Integer pattern validation with bootstrap3 driver

integer[required|range:18,60,io]


Float

float[required|positive|negative|min:a|max:b|range:a,b|not:n1,n2,n3|confirmed:inputName]

Float pattern passes validation if the input value is a valid float number.

Rule Pass condition
required Value is present
positive Value is positive
negative Value is negative
min:a Value is larger than or equal to a
Note: min rule accepts 2nd parameter (i or o) that indicates whether the 1st parameter is valid or not.
i (of in which the default) indicates the the 1st parameter is valid.
o (of out) indicates the the 1st parameter is not valid.
max:b Value is less than or equal to b
Note: max rule accepts 2nd parameter (i or o) that indicates whether the 1st parameter is valid or not.
i (of in which the default) indicates the the 1st parameter is valid.
o (of out) indicates the the 1st parameter is not valid.
range:a,b Value is in the range [a, b]. Note that a and b are inside the range by default
Note: range rule accepts 3rd parameter (combination of i and o) that indicates whether the 1st and the 2nd parameters are valid or not.
ii (default) indicates the the 1st and the 2nd parameters are valid.
io indicates the the 1st parameter is valid and the 2nd parameter is not valid.
oi indicates the the 1st parameter is not valid and the 2nd parameter is valid.
oo indicates the the 1st and the 2nd parameters are not valid.
not:n1,n2,n3 Value is not n1 nor n2 nor n3. Note that you can add more parameters as much as you need
confirmed:inputName The validated input and the input whose name is inputName have the same value. Note: if this rule used without parameter i.e. confirmed, then Spacer assume the confirmation input name to be the same as validated input name suffixed with _confirmation
Example: Float pattern validation with bootstrap3 driver

float[required|range:0.01,100|not:100]

KG


String

string[required|of:alpha,num,underscore,dash,spaces,comma,dot |not_of:alpha,num,underscore,dash,spaces,comma,dot|min:a|max:b|range:a,b|len:x |not:n1,n2,n3|confirmed:inputName]

String pattern always passes the validation unless one of the provided rules is not passed. This makes String pattern suitable for custom validation rules since it has no initial pass conditions.

Rule Pass condition
required Value is present
of:alpha,num,underscore,dash,spaces,comma,dot Value is composed only of characters specified in parameters where:
alpha represents alphabetical letters from a to z and from A to Z,
num represents digits from 0 to 9,
underscore represents underscore symbol _,
dash represents dash symbol -
spaces represents all types of spaces
comma represents comma symbol ,
dot represents dot symbol .
not_of:alpha,num,underscore,dash,spaces,comma,dot Value does not contain any of characters specified in parameters where:
alpha represents alphabetical letters from a to z and from A to Z,
num represents digits from 0 to 9,
underscore represents underscore symbol _,
dash represents dash symbol -
spaces represents all types of spaces
comma represents comma symbol ,
dot represents dot symbol .
min:a Characters length is larger or equal to a
Note: min rule accepts 2nd parameter (i or o) that indicates whether the 1st parameter is valid or not.
i (of in which the default) indicates the the 1st parameter is valid.
o (of out) indicates the the 1st parameter is not valid.
max:b Characters length is less or equal to b
Note: max rule accepts 2nd parameter (i or o) that indicates whether the 1st parameter is valid or not.
i (of in which the default) indicates the the 1st parameter is valid.
o (of out) indicates the the 1st parameter is not valid.
range:a,b Characters length is in the range [a, b]. Note that a and b are inside the range
Note: range rule accepts 3rd parameter (combination of i and o) that indicates whether the 1st and the 2nd parameters are valid or not.
ii (default) indicates the the 1st and the 2nd parameters are valid.
io indicates the the 1st parameter is valid and the 2nd parameter is not valid.
oi indicates the the 1st parameter is not valid and the 2nd parameter is valid.
oo indicates the the 1st and the 2nd parameters are not valid.
len:x Characters length is exactly b character(s)
not:n1,n2,n3 Value is not n1 nor n2 nor n3. Note that you can add more parameters as much as you need
confirmed:inputName The validated input and the input whose name is inputName have the same value. Note: if this rule used without parameter i.e. confirmed, then Spacer assume the confirmation input name to be the same as validated input name suffixed with _confirmation
Example: String pattern validation with bootstrap3 driver

string[required|of:alpha,num,underscore,dot,comma|min:6|confirmed:password-confirmation]


Timeline

timeline[required|format:~x~|min:a|max:b|range:a,b|confirmed:inputName]

Timeline pattern passes validation if the input value is a valid date or a valid time or valid datetime according to specified format .

Rule Pass condition
required Timeline is present
format:~x~ Timeline matches the format x. If format:~x~ rule is not exist, Spacer uses default timeline format specified in timelineFormat configuration option. Note that Spacer uses MomentJs to validate dates. For format, please refer to MomentJs Formats
min:a Timeline is after or equal to a
Note: min rule accepts 2nd parameter (i or o) that indicates whether the 1st parameter is valid or not.
i (of in which the default) indicates the the 1st parameter is valid.
o (of out) indicates the the 1st parameter is not valid.
max:b Timeline is before or equal to b
Note: max rule accepts 2nd parameter (i or o) that indicates whether the 1st parameter is valid or not.
i (of in which the default) indicates the the 1st parameter is valid.
o (of out) indicates the the 1st parameter is not valid.
range:a,b Timeline is in the range [a, b]. Note that a and b are inside the range
Note: range rule accepts 3rd parameter (combination of i and o) that indicates whether the 1st and the 2nd parameters are valid or not.
ii (default) indicates the the 1st and the 2nd parameters are valid.
io indicates the the 1st parameter is valid and the 2nd parameter is not valid.
oi indicates the the 1st parameter is not valid and the 2nd parameter is valid.
oo indicates the the 1st and the 2nd parameters are not valid.
confirmed:inputName The validated input and the input whose name is inputName have the same value. Note: if this rule used without parameter i.e. confirmed, then Spacer assume the confirmation input name to be the same as validated input name suffixed with _confirmation
Example: Timeline pattern validation with bootstrap3 driver

timeline[required|format:~D/M/YYYY~|min:26/3/2018]


Email

email[required|min:a|max:b|range:a,b|in_domain:x,y,z|not_in_domain:m,n,o|confirmed:inputName]

Email pattern passes validation if the input value is a valid email.

Rule Pass condition
required Value is present
min:a Characters length is larger or equal to a
Note: min rule accepts 2nd parameter (i or o) that indicates whether the 1st parameter is valid or not.
i (of in which the default) indicates the the 1st parameter is valid.
o (of out) indicates the the 1st parameter is not valid.
max:b Characters length is less or equal to b
Note: max rule accepts 2nd parameter (i or o) that indicates whether the 1st parameter is valid or not.
i (of in which the default) indicates the the 1st parameter is valid.
o (of out) indicates the the 1st parameter is not valid.
range:a,b Characters length is in the range [a, b]. Note that a and b are inside the range
Note: range rule accepts 3rd parameter (combination of i and o) that indicates whether the 1st and the 2nd parameters are valid or not.
ii (default) indicates the the 1st and the 2nd parameters are valid.
io indicates the the 1st parameter is valid and the 2nd parameter is not valid.
oi indicates the the 1st parameter is not valid and the 2nd parameter is valid.
oo indicates the the 1st and the 2nd parameters are not valid.
in_domain:x,y,z Value belongs to x domain or y or z. Note that you can add more parameters as much as you need
not_in_domain:m,n,o Value does not belongs to m domain nor n nor o. Note that you can add more parameters as much as you need
confirmed:inputName The validated input and the input whose name is inputName have the same value. Note: if this rule used without parameter i.e. confirmed, then Spacer assume the confirmation input name to be the same as validated input name suffixed with _confirmation
Example: Email pattern validation with bootstrap3 driver

email[required|max:50|not_in_domain:gmail.com,hotmail.com|confirmed]


Url

url[required|min:a|max:b|range:a,b|in_domain:x,y,z|not_in_domain:m,n,o|confirmed:inputName]

Url pattern passes validation if the input value is a valid url.

Rule Pass condition
required Value is present
min:a Characters length is larger or equal to a
Note: min rule accepts 2nd parameter (i or o) that indicates whether the 1st parameter is valid or not.
i (of in which the default) indicates the the 1st parameter is valid.
o (of out) indicates the the 1st parameter is not valid.
max:b Characters length is less or equal to b
Note: max rule accepts 2nd parameter (i or o) that indicates whether the 1st parameter is valid or not.
i (of in which the default) indicates the the 1st parameter is valid.
o (of out) indicates the the 1st parameter is not valid.
range:a,b Characters length is in the range [a, b]. Note that a and b are inside the range
Note: range rule accepts 3rd parameter (combination of i and o) that indicates whether the 1st and the 2nd parameters are valid or not.
ii (default) indicates the the 1st and the 2nd parameters are valid.
io indicates the the 1st parameter is valid and the 2nd parameter is not valid.
oi indicates the the 1st parameter is not valid and the 2nd parameter is valid.
oo indicates the the 1st and the 2nd parameters are not valid.
in_domain:x,y,z Value belongs to x domain or y or z. Note that you can add more parameters as much as you need
not_in_domain:m,n,o Value does not belongs to m domain or n or o. Note that you can add more parameters as much as you need
confirmed:inputName The validated input and the input whose name is inputName have the same value. Note: if this rule used without parameter i.e. confirmed, then Spacer assume the confirmation input name to be the same as validated input name suffixed with _confirmation
Example: Url pattern validation with bootstrap3 driver

url[required|max:200|in_domain:facebook.com]


In

in[required|items:n1,n2,n3]

In pattern passes validation if the input value is one of the items specified in items rule.

Rule Pass condition
required Value is present
items:n1,n2,n3 Value is n1 or n2 or n3. Spacer throw Syntax Error if items rule is not found. Note that you can add more parameters as much as you need
Example: In pattern validation with bootstrap3 driver

in[required|items:a, b, c, d]


Check

check[required]

check pattern passes validation if the input is checked

Rule Pass condition
required Value is present
Example: In pattern validation with bootstrap3 driver

check[required]


File

file[required|ext:n1,n2,n3|min:a|max:b|range:a,b|s_min:a|s_max:b|s_range:a,b|len:n]

File pattern passes validation if the input of type file has is a valid file(s).

Rule Pass condition
required At least one file is present
ext:n1,n2,n3 The extension of each file is n1, n2 or n3. Note that you can add more parameters as much as you need
min:a The size of all files is larger or equal to a MB
max:b The size of all files is less or equal to b MB
range:a,b The size of all files is in the range [a, b] MB. Note that a and b are inside the range
s_min:a The size of each file is larger or equal to a MB
s_max:b The size of each file is less or equal to b MB
s_range:a,b The size of each file is in the range [a, b] MB. Note that a and b are inside the range
len:n The input has n file(s).
Example: File pattern validation with bootstrap3 driver

file[required|max:5|len:3|ext:png,jpg,jpeg,doc,docx,pdf]


Regex

regex[pattern:~exp~|min:a|max:b|range:a,b|len:x|confirmed:inputName]

Regex pattern passes validation if the input value matches the regular expression specified in pattern.

Rule Pass condition
pattern:~exp~ Value matches the regular expression. Spacer throw Syntax Error if pattern rule is not found. Keep in mind, that the normal string escape rules (preceding special characters with \ when included in a string) are necessary. For more details please refer to RegExp
min:a Characters length is larger or equal to a
Note: min rule accepts 2nd parameter (i or o) that indicates whether the 1st parameter is valid or not.
i (of in which the default) indicates the the 1st parameter is valid.
o (of out) indicates the the 1st parameter is not valid.
max:b Characters length is less or equal to b
Note: max rule accepts 2nd parameter (i or o) that indicates whether the 1st parameter is valid or not.
i (of in which the default) indicates the the 1st parameter is valid.
o (of out) indicates the the 1st parameter is not valid.
range:a,b Characters length is in the range [a, b]. Note that a and b are inside the range
Note: range rule accepts 3rd parameter (combination of i and o) that indicates whether the 1st and the 2nd parameters are valid or not.
ii (default) indicates the the 1st and the 2nd parameters are valid.
io indicates the the 1st parameter is valid and the 2nd parameter is not valid.
oi indicates the the 1st parameter is not valid and the 2nd parameter is valid.
oo indicates the the 1st and the 2nd parameters are not valid.
len:x Characters length is exactly b character(s)
confirmed:inputName The validated input and the input whose name is inputName have the same value. Note: if this rule used without parameter i.e. confirmed, then Spacer assume the confirmation input name to be the same as validated input name suffixed with _confirmation
Example: Regex pattern validation with bootstrap3 driver

regex[required|pattern:~^5[1-5][0-9]{14}$~|min:6]


Extra Rules


min_input:inputName,inOut,fn

  • Supported patterns: integer, float and timeline
  • Pass condition: The value must be less than another input value.

Parameters Description
inputName Related input to compare the value with.
inOut Use i (of in) to indicate the related input's value is valid or o (of out) to indicate the related input's value is not valid
fn Override related input's friendly name

max_input:inputName,inOut,fn

  • Supported patterns: integer, float and timeline
  • Pass condition: The value must be less than another input value.

Parameters Description
inputName Related input to compare the value with.
inOut Use i (of in) to indicate the related input's value is valid or o (of out) to indicate the related input's value is not valid
fn Override related input's friendly name

Usage


Attach Pattern To Input Field

  • Use data-v-p tag to define validation pattern.
  • Optionally use data-v-fn tag to define input friendly name to be shown in the error messages. If data-v-fn tag is not found, Spacer uses resource string defaultFriendlyName as input friendly name. defaultFriendlyName is set to value by default.
example:
<input type="text" name="weight" data-v-p="float[required|min:10|max:250]" data-v-fn="shipment weight">

Validate

Once you added patterns to inputs, you're ready to use the validation functions:

  • Validate Form

    spa.validation.validate(form)

    Use validate to validate all form's inputs. This method accept one parameter form which is the form as JQuery object.
    Note: validate's parameter is not required to be a form element. You can use any wrapper to input fields.

    var myForm = $('#myForm');
    if(spa.validation.validate(myForm)) {
        //form is valid
    }
    else {
        //form is not valid and the errors are shown according to current validation driver
    }

    For simplicity, you can pass form's Jquery Selector as string. Spacer is smart enough to get the JQuery object if the parameter is passed as string. So you can write:

    if(spa.validation.validate('#myForm')) {
        //form is valid
    }
    else {
        //form is not valid and the errors are shown according to current validation driver
    }


  • Reset Validation

    spa.validation.resetValidation(form)

    When you validate an input, Spacer attach events to re-validate the input when its value is changed. Reset validation for certain form does the following:

    • De-attach re-validation events
    • Clear all validation errors

    This method accept one parameter form which is the form as JQuery object.
    Note: resetValidation's parameter is not required to be a form element. You can use any wrapper to input fields.

    var myForm = $('#myForm');
    spa.validation.resetValidation(myForm)

    For simplicity, you can pass form's Jquery Selector as string. Spacer is smart enough to get the JQuery object if the parameter is passed as string. So you can write:

    spa.validation.resetValidation('#myForm')

Lite Rule

Use lite rule with any pattern to show the first error message only.

example:
<input type="text" name="weight" data-v-p="float[required|min:10|max:250|lite]" data-v-fn="shipment weight">

Pre Rule


Sometime wee need to pass the input value to custom function before we apply the validation. For example: we need to pass the value 1,500 to custom function to remove the comma before the validation occurs. To do that, just define your custom function and associate it with the pattern using pre rule.

validationPre configuration option is an object that hold pre validation functions. So to define removeCommas function, we could do the following (Keep in mind that the return value should be string value):

spa.setOptions({
	validationPre: {
		removeCommas: function (value) {
			//remove comma and return string value
		}
	},
});

After that we could use it as follow:

<input type="text" name="annual_income" data-v-p="integer[required|pre:removeCommas]" data-v-fn="Annual Income">

Please note:

  • You can pass pre as many function as you want. eg. pre:removeCommas,getAbsoluteValue,getRoundValue. These functions are applied from left to right. i.e. removeCommas applied first, then getAbsoluteValue then getRoundValue.
  • When using pre and confirmed together, then pre's functions are applied to both input value and confirm input value.

Validation Object

Spacer generate validation object for each input before the validation begin. When extending Spacer (custom rules, custom validation driver...), most functions are passed a validation object. The validation object has the following initial structure:

{
    //info about input being validated
    input: {
        //jquery object
        jquery: undefined,
        //name
        name: undefined,
        //original value
        originalValue: undefined,
        //value after applying pre rule
        //this is the value that should be validated
        valueToValidate: undefined,
        //friendly name
        friendlyName: undefined,
    },
     //info about confirm input
    confirmInput: {
        jquery: undefined,
        name: undefined,
        originalValue: undefined,
        //value after applying pre rule
        valueToValidate: undefined,
    },
    //info validation pattern
    pattern: {
        //validation pattern as string
        string: undefined,
        //pattern name
        name: undefined,
        //array of validation rules
        rules: [],
        isLite: false,
        timelineFormat: undefined,
        required: undefined,
        //array of failed validation rules
        invalidRules: [],
    },
}


Validation Rule Object

We already saw the validation object's properties: pattern.rules and invalidRules are array of rules. Each role has the following initial structure:

{
    name: undefined
    //array of passed parameters
    params: [],
}

Please note that invalidRules items have extra property called message that hold the error message.



Custom Rules


Spacer makes defining your own validation rules so easy. validationCustomRules configuration option is an object that hold all validation custom rules. To define a custom rule, you must implement the two functions:

  • validate(vo, index)

    Where vo is the validation object and index is the index of rule being validated in vo.pattern.rules array. This function performs validation on pattern.input.valueToValidate and should return true if validation passed or false if validation failed.

  • getErrorMessage(vo, index)

    Where vo is the validation object and index is the index of invalid rule in vo.pattern.invalidRules array. This function is called to get error message if the rule validation fails.

spa.setOptions({
    validationCustomRules: {
        ruleName: {
            validate: function (vo, index) {
                var rule = vo.pattern.rules[index];
                //return true or false
            },
            getErrorMessage: function (vo, index) {
                var rule = vo.invalidRules[index];
                //return string
            },
        },
    },
});

Validation Drivers


Spacer uses drivers to show error message(s). Spacer provide some useful drivers:


Available Validation Drivers

  • bootstrap3

    bootstrap3 driver follow bootstrap 3 outline. So to work properly, bootstrap3 driver requires the following:

    • To wrap input in <div class="form-group"></div>
    • The <div class="form-group"></div> should have <span> or <p> with class help-block

    If validation error occurs, Spacer add has-error class to <div class="form-group"></div> and add the error message(s) to help-block.

  • listOfErrors

    listOfErrors driver expects to have an element with id #spacer-listOfErrors in your page. Once the validation fails, listOfErrors driver show list of the errors as <li> items wrapped in <ul>.

    If you don't have an element with id #spacer-listOfErrors in your page and you want to show error list in custom way, then you can use spa.validation.getErrorList() to get error list as array of:

    {
        //info about input that has errors
        input: {
            //jquery object
            jquery: undefined,
            //name
            name: undefined,
            //original value
            originalValue: undefined,
            //value after applying pre rule
            //this is the value that should be validated
            valueToValidate: undefined,
            //friendly name
            friendlyName: undefined,
        }
        //the error messages related to the above object
        errors: [],
    }

    If you want to use a different id instead #spacer-listOfErrors, you are free to choose any id and don't forget to set listOfErrorsSelector configuration options using setOptions() function.

  • silent

    As the name implies, this driver do nothing. This driver is useful to manually handle the error. You may need this driver in such rare situation that doesn't deserve to write custom driver for it.

  • dialog

    Shows the first error using the current dialog driver. Please refer to dialog drivers for more details.

  • dialog.alert

    Shows the first error using alert dialog driver.

  • dialog.sweetAlert

    Shows the first error using sweetAlert dialog driver.

  • dialog.bootstrap3Panel

    Shows the first error using bootstrap3Panel dialog driver.

  • dialog.bootstrap3Modal

    Shows the first error using bootstrap3Modal dialog driver.


Custom Validation Drivers

To define your own validation driver, provide implementation to the two functions:

  • onError (vo)

    This function is used to output the validation error messages for single input and get called on every input when validation ends with errors. The only parameter vo is the validation object.

  • clearError (input)

    This function is used to clear the validation error messages for single input and get called on every input before validation begins. The 1st parameter input is the input as JQuery object.

validationDrivers configuration option is designed to hold all validation drivers. To define a new dialog driver called myValidationDriver, we can do it like so:

spa.setOptions({
       validationDrivers: {
              myValidationDriver: {
                     onError: function (vo) {
                            //implementation
                     },
                     clearError: function (input) {
                            //implementation
                     },
              },
       },
});