Buy Now
Sign in

FAQ search

Examples of Custom Validation in CFv5

Published: Friday, 12 February 2016 15:24

The validation tab for Text Box and Textarea Box elements in CFv5 has a Custom function box where you can add the name of a JavaScript function that the validation code will use to check the entry. This FAQ includes some examples of functions that you can use or adapt.

For more general notes on customising the validation, including adding custom error messages, please see this FAQ; and for CFv4 see this FAQ.

To add a Custom function you need to do two things:

  • write a JavaScript function that returns true or false and put the script into a Load JavaScript action in the form On Load event.
  • add the function name to the Custom function box on the validation tab of the element. 

Here are some examples of custom  functions.

Checking a value falls inside a range

This function checks that a numeric value falls in a range - from 500 to 2000 here. 

function validateMinMax(el) {
  return ( el.val() >= 500 && el.val() <= 2000 ) ;

Change the minimum and maximum values to yours and add validateMinMax to the Custom function box. You may also want to add a Digits validation and/or a Mask. 

Checking for a minimum length 

This function was written to prevent spaces being used to complete required inputs. It checks the length of the entry ignoring any spaces at the start or end. 

function validateLength(el) {
  return ( el.val().trim().length > 2 );

Change the length value to yours and add validateLength to the Custom function box.

Checking that one of two inputs has an entry

This is useful when you want, for example, to check if there is either a contact phone, or a contact email entered.

function validateOneOf () {
  var input_a, input_b;
  input_a = jQuery('#phone').val().trim().length;
  input_b = jQuery('#email').val().trim().length;
  return ( input_a > 0 || input_b > 0 );

Change the ids to the ids of the elements you want to validate and add validateOneOf to the Custom function box. You will also want to add a custom validation message in the Title boxes of the elements.