Validation

Validation of data is of fundamental importance in CRUD applications. You need to be sure that the data that the client is sending you is what you expect! This is not just for security reasons, protecting your data from misuse and intentional corruption, but also simply from unintentional mistakes in submitting data. Strings limited to a certain length, dates in a particular format and required fields are all common uses of data validation.

The Editor Node.JS libraries provide two different validation methods:

  • Field based, where each individual value submitted is independently validated: Field.validator().
  • Global validation, where the data submitted by the client-side can be validated as a whole: Editor.validator().

Field validation is the one you will most commonly work with; for example checking that an e-mail address field actually contains an e-mail address. Editor provides a number of ready to use validators for the most common data types as well as the ability to specify your own. Global validation can be useful when checking dependencies between fields and conflicts in the existing data set.

Field validation

The Editor Node.JS libraries provide a validator() method for the Field class and a number of pre-built validation methods in the Validate class. Each of these validation methods returns a function which is executed when required to validate submitted data.

Consider the following example - the Validate.minNum() function is configured with a number and returns a function that can be used for the field validator.

new Field("age")
    .validator(Validate.minNum( 16 ));

Please see below for more detailed examples.

Validation options

Each validation method provided by the Validation class can optionally accept parameters to tell it how to validate data (for example the minLen method will accept an integer to indicate the minimum length of an acceptable string), but all optionally accept a ValidationOptions class instance. This class defines a number of options that are shared between all validation methods.

The ValidationOptions class can be accessed through Validate.Options - see below for an example. The constructor for the class takes a single object with three parameters that can be used to alter the validation behaviour:

  • empty: (boolean) How to handle empty data (i.e. a zero length string):
    • true (default) - Allow the input for the field to be zero length
    • false - Disallow zero length inputs
  • message: (string) the error message to show if the validation fails. This is simply "Input not valid" by default, so you will likely want to customise this to suit your needs.
  • optional: (boolean) Require the field to be submitted or not. This option can be particularly useful in Editor as Editor will not set a value for fields which have not been submitted - giving the ability to submit just a partial list of options.
    • true (default) - The field does not need to be be in the list of parameters sent by the client.
    • false - The field must be included in the data submitted by the client.

Example - setting a custom error message

new Field('stock_name')
    .validator(Validation.minLen(
        10,
        new Validate.Options({
            message: 'Stock name must be at least 10 characters long.'
        })
    ))

Multiple validators

It can often be useful to use multiple validators together, for example to confirm that an input string is less than a certain number of characters and also that it is unique in the database. Multiple validators can be added to a field simply by calling the Field.validator() method multiple times. Rather than overwriting the previous validator it will in fact add them together. They are run in the sequence they were added, and all validators must pass for the data to be accepted as valid.

As an example consider the following code which will check the min and max length of the data, and also that it is unique:

new Field( 'stock_name' )
    .validator( Validation.minLen( 10 ) )
    .validator( Validation.maxLen( 12 ) )
    .validator( Validation.unique() );

Ready to use field validators

The Validate class in the Editor Node.JS libraries has a number of methods which can be used to perform validation very quickly an easily. These are:

Basic

  • none( cfg=null: ValidationOptions ) - No validation is performed
  • basic(cfg=null: ValidationOptions) - Basic validation - only the validation provided by ValidationOptions is performed
  • required(cfg=null: ValidationOptions) - The field must be submitted and the data must not be zero length. Note that Editor has the option of not submitting all fields (for example when inline editing), so the notEmpty() validator is recommended over this one.
  • notEmpty(cfg=null: ValidationOptions) - The field need not be submitted, but if it is, it cannot contain zero length data
  • boolean(cfg=null: ValidationOptions) - Check that boolean data was submitted (including 1, true on, yes, 0, false, off and no)

Numbers

  • numeric(cfg=null: ValidationOptions) - Check that any input is numeric.
  • minNum(min, cfg=null: ValidationOptions) - Numeric input is greater than or equal to the given number
  • maxNum(max, cfg=null: ValidationOptions) - Numeric input is less than or equal to the given number
  • minMaxNum(min, max, cfg=null: ValidationOptions) - Numeric input is within the given range (inclusive)

Strings

  • email(cfg=null: ValidationOptions) - Validate an input as an e-mail address.
  • ip(cfg=null: ValidationOptions) - Validate as an IP address.
  • minLen(min, cfg=null: ValidationOptions) - Validate a string has a minimum length.
  • maxLen(max, cfg=null: ValidationOptions) - Validate a string does not exceed a maximum length.
  • minMaxLen(min, max, cfg=null: ValidationOptions) - Validate a string has a given length in a range
  • noTags(cfg=null: ValidationOptions) - Don't allow HTML tags
  • url(cfg=null: ValidationOptions) - Validate as an URL address.
  • values(values: array, cfg=null: ValidationOptions) - Allow only values which have been specified in an array of options (the first parameter). This could be useful if you wish to have free-form input or event a select list, and want to confirm that the value submitted is within a given data set (see also the dbValues() method if valid values are stored in a database). Note that the values given in the values array are checked against the submitted data as case-sensitive data (i.e. `"A" != "a").
  • xss(cfg=null: ValidationOptions) - Check to see if the input could contain an XSS attack. This used the Field's XSS formatting function to determine if the input string needs to be formatted or not.

Date / time

  • dateFormat(format, locale, cfg=null: ValidationOptions) - Check that a valid date input is given. The format is defined by Moment.JS which is used for the parsing of date and time string. The locale is also passed through to Moment.

Database

  • dbValues(cfg=null: ValidationOptions, column=null, table=null, db=null, valid=null) - Allow only a value that is present in a database column. This is specifically designed for use with joined tables (i.e. ensure that the reference row is present before using it), but it could potentially also be used in other situations where referential integrity is required.
  • unique(cfg=null: ValidationOptions, column=null, table=null, db=null) - Ensure that the data submitted is unique in the table's column.

Custom field validators

If the provided methods above don't suit the kind of validation you are looking for, it is absolutely possible to provide custom validation methods. The validator() Field method will accept a function that returns either true or a string and accepts the following input parameters:

  1. value - The value to be validated
  2. data - The collection of data for the row in question
  3. host - Information about the host Field and Editor instances

The return value should be true to indicate that the validate passed, or a string that contains an error message if the validation failed.

Anonymous functions and arrow functions are excellent for defining validation methods quickly and easily. A custom validation method that simply ensures a string is of a certain size (5 characters in this case) might look like the following with arrow expression:

new Field("staffId")
    .validator((val, data, host) => {
        return val.length < 5
            ? "Input must be 5 characters or more"
            : true;
    })

Examples

Use the Validation.minNum() method to validate an input as numeric and greater or equal to a given number (no validation options specified, so the defaults are used):

new Field("age")
    .validator(Validate.minNum( 16 ))

As above, but with ValidationOptions used to set the error message:

new Field("age")
    .validator(Validation.minNum(
        16,
        new Validate.Options({
            message: "Minimum age is 16"
        })
    ))

This time validating an e-mail address which cannot be empty, and an error message is provided:

new Field("email")
    .validator(Validate.email( new Validate.Options({
        empty: false,
        message:: "An e-mail address is required"
    }) ))

A join with dbValues which will accept an empty value, which is stored as null on the database:

new Field("users.site")
    .options("sites", "id", "name")
    .validator(Validate.dbValues())
    .setFormatter(Format.nullEmpty());

Allow only certain values to be submitted:

new Field( "group" )
    .validator(Validate.values(["CSM", "FTA", "KFVC"]))

Global validators

You may also find it useful to be able to define a global validator that will execute whenever a request is made to the server and the Editor.process() method is executed. This method can be used to provide security access restrictions, validate input data as a whole or even to check that a user is logged in before processing the request.

Function

The function that is given to the Editor.validator() method has the following signature:

  1. editor (Editor) - The Editor instance that the function is being executed for
  2. action (string) - The action being performed
  3. request (object) - The data submitted by the client (see the client/server documentation).

As with the field validators, the return value from the function true if the validation passed without issue, or a string that contains an error message if the validation fails.

Note that this function is executed only once when the Editor.process() method is called, rather than once per submitted row.

Examples

// Allow read only access based on a session variable
let editor = new Editor(db, 'table')
    .validator( (editor, action, data) => {
        if ( action !== 'read' && req.session.readOnly ) {
            return 'Cannot modify data';
        }
        return true;
    } )
    .fields( ... );
// Create and edit with dependent validation
let editor = new Editor(db, "table")
    .validator( (editor, action, data) => {
        if ( action == 'create' || action == 'edit' ) {
            Object.keys( data.data ).forEach( function ( key ) {
                var values = data.data[key];

                if ( values.country == 'US' && values.location == 'London UK' ) {
                    return 'London UK is not in the US';
                }
            } );
        }
        return true;
    } )
    .fields( ... );

Validation reference documentation

The Editor Node.JS reference documentation details the pre-built validation methods available and also the interfaces used by the libraries if you wish to develop your own.