Advanced Validanguage Features

  1. Validating a form with validateForm()
  2. Adding and Disabling Validations
  3. Manually Failing a Form Field
  4. The showSubmitMessage and showFailedFields Options
  5. validanguage.settings.onload
  6. Transformation: validanguage.toggle()
  7. Setting up Ajax Validations with isAjax

Validating a form with validateForm()

The validateForm() method can be used to manually trigger validation on a form (without actually submitting it) and get access to the validation results and a list of any fields which failed and their error messages. This function is useful when you wish to submit a form via Ajax and want to validate the form fields first.

validateForm takes a single argument (the ID of the form to be validated) and returns an object containing the validation results and details on any fields which failed validation.

Example: var formValidation = validanguage.validateForm('form1');

In the above example, formValidation.result will be set to either true or false, depending on whether or not the form validated. If formValidation.result is false, then formValidation.failedValidations will contain details on the failed fields.

Adding and Disabling Validations

Validanguage provides several methods of enabling and disabling validations.

Adding Validations

As described in the Validanguage Overview, the main method for adding new validations is to define them via the Comment API or Object API and have the validations be automatically created when the validanguage javascript is loaded. Additionally, the addValidation() function is available to either load a new validation for a form field, or to reactivate a validation previously removed with the removeValidation() method. When adding a new validation with AddValidation(), you will first need to have inserted all the relevant details about the validation in the validanguage.el.formField object. Thus, if you have dynamically created a form field after the page has already loaded and wish to add validation to it, you cannot use the Comment API and must use the Object API to add the validation details directly into validanguage.el.formField before calling addValidation().

addValidation() takes the following arguments:

{String} elemId -- The ID of the field to receive the validation.
{String/Array} eventTypes -- A list of event types which should receive the indicated validations.
{String/Array/Function} validationNames --A list of the validation functions to be added. These must match exactly a validation which is listed in the validanguage.el.formField object, including variable type. Thus, when adding a validation which has a supported shortcut in validanguage.el.formField (such as "required" which is a shortcut for "validateRequired") the full function name must be present in validanguage.el.formField. If youwish to load all the validations which are listed in the validanguage.el.formField.validations array, you can use "*" as a shortcut to listing all the validations individually.
addValidation() example :
<script type="text/javascript">
   //first we add the new field to validanguage.el
   validanguage.el.newDateField = {
      errorMsg: 'You must enter a valid date',
      validations: [
         {
            name: 'validateRequired'
         },
         {
            name: 'validateDate'
         }
      ]
   }
   //Next we load the new validations with validanguage.addValidation()
   //Note that the new validations must be loaded with the array syntax below,
   //using "validateRequired, validateDate" will not work
   validanguage.addValidation( 'newDateField', ['onsubmit', 'onblur'], ['validateRequired', 'validateDate'] );

   //Instead of listing both validations individually, you could also use the following:
   validanguage.addValidation( 'newDateField', ['onsubmit', 'onblur'], '*' );
</script>

Disabling or Removing Validations

There are a number of different methods for disabling validations once they have been defined for a given form field:
  1. Disable the form field. You can use javascript to disable the actual form field, which will also disable all validations for this form field. Example: document.getElementById('formField').disabled = true; //Re-enable validations by setting this to false
  2. Mark the element as disabled in validanguage.el.formField. You can also easily disable all validations for a form fields by marking it as disabled in the validanguage.el object corresponding to the form field.
    Example: validanguage.el.formField.disabled = true; //Re-enable validations by setting this to false
  3. Disable all validations for the parent form. You can disable all validations for every field in a given form by marking the form as disabled in the validanguage.el object.
    Example: validanguage.el.form1.disabled = true; //re-enable validations by setting this to false
    Or if the form1 object does not yet exist: validanguage.el.form1 = { disabled: true }
  4. Use the removeValidation() method to remove some validations while leaving other validations in place. The removeValidation() function can be called to deactivate one or more previously defined validations.
removeValidation() takes the following arguments:
{String} elemId -- The ID of the field for which you wish to remove validations.
{String/Array} eventTypes -- A list of event types for which you wish to remove validations.This enables you to remove a given validation for, say, "onblur", while leaving the validation in place for "onsubmit". If you wish to remove all eventTypes for a given validation(s), you can use "*" as a shortcut to listing all the eventTypes individually.
{String/Array/Function} validationNames --A list of the validation functions to be removed. These must match exactly a validation which is listed in the validanguage.el.formField object, including variable type. Thus, when removing a validation which has a supported shortcut in validanguage.el.formField (such as "required" which is a shortcut for "validateRequired"), you must specify the full function name. If you wish to remove all the validations which are listed in the validanguage.el.formField.validations array, you can use "*" as a shortcut to listing all the validations individually.
removeValidation() example :
<script type="text/javascript">
   validanguage.removeValidation( 'newDateField', ['onsubmit', 'onblur'], ['validateRequired', 'validateDate'] );

   //Or, instead of listing the eventTypes and validations indivudally,
   //you can deactivate them all with the following:
   validanguage.removeValidation( 'newDateField', '*', '*' );
</script>

Manually Failing a Form Field

Form fields can be manully marked as failed, which enables you to trigger an ajax lookup against a database and, depending on the results, mark a field as "failed" so the form won't be allowed to submit until you manually mark it as "okay" again. You can mark a field as failed by noting it as such inside the corresponding validanguage.el.formFieldId object. For example:

validanguage.el.username.failed = true; //mark as failed validanguage.el.username.failed = false; //return to normal

An example of this appears on the validanguage demo.

The showSubmitMessage and showFailedFields Options

showSubmitMessage() function

The showSubmitMessage() function is intended to be used as an onsubmit transformation for a form. If the form passes validation, the new method will replace the submit button with a div containing the text "Loading" and can also be styled to include a spinner image. This is helpful for signup pages to prevent multiple submissions of the form.

An example of this appears on the validanguage demo.

The showFailedFields option in validanguage.showError()

This option modifes the default showError() function to not only include an inline error message next to any failed fields, but it also populates a DIV with a list of all the fields which failed. By default, this is turned off, but it can enabled by setting:

validanguage.settings.showFailedFields = true.

The names used for the form fields in showFailedFields is determined by the validanguage.el.field setting (described below).

An example of showFailedFields (using manual CSS to style the DIV) appears on the validanguage demo.

The field attribute in validanguage.el

This option allows you to specify a human-readable name for a field. Thus, you can tell validanguage to refer to the field that has an ID of "email1" as the more human-friendly "Email Address". If validanguage.el.field is not provided, it will be inherited from the field ID. The field attribute is included in the failedValidations argument which is passed to onsubmit transformations and to the results of a call to validateForm().

You can specify the new field attribute using either the comment-based API or the Object API.

validanguage.settings.onload

The method enables you to specify a function to run after the validanguage.populate() function has finished loading and all validations have been loaded and prepared for use. Example:

validanguage.settings.onload = 'customOnloadFunction';

Transformation: validanguage.toggle()

This function is intended for somewhat advanced users, as the object-based syntax for defining this is fairly complex. This transformation function is actually 3 functions in one:
  • Toggle Visibility: You can use validanguage.toggle() to hide and show other form fields or HTML elements based on the user changing a SELECT box or checking/unchecking a field.
  • Toggle Values: Allows you to set a value of form field B in response to changes in form field A. This allows you to set a hidden field to 0 or 1 based on whether or not a checkbox has been checked.
  • Dynamic Select Boxes: You can add/remove options to select box B in response to what a user chooses for Select Box A.

Using validanguage.toggle() to Toggle Visibility

You can use validanguage.toggle() to hide and show other form fields or HTML elements based on the user changing a SELECT box or checking/unchecking a field. As an added bonus, form fields contained inside a region being hidden/shown are automatically disabled/enabled to ensure that validation is correctly handled on fields which are only shown under certain conditions. Also, any toggle visibility statements are automatically called on document.onload to ensure that the state of the UI will always match your declared rules.

Example: See the validanguage.toggle() test case page

Using validanguage.toggle() to Toggle Values

You can use validanguage.toggle() to set a value of form field B in response to changes in form field A. This allows you to set a hidden field to 0 or 1 based on whether or not a checkbox has been checked.

Example: See the validanguage.toggle() test case page

Using validanguage.toggle() to Create Dynamic Select Boxes

You can add/remove options to select box B in response to what a user chooses for Select Box A. The validanguage.toggle() test case page shows an example of setting up 3 dynamic select boxes which work in conjunction with toggling the visibility of each and the easy enabling/disabling of any associated validations.

Example: See the validanguage.toggle() test case page

Setting up Ajax Validations with isAjax

Introduced in version 0.9.7, the isAjax attribute for validation functions allows you to seamlessly integrate ajax calls to server-side code into your client-side validation routines.

When the code hits a validation function with isAjax = true associated with it, the code will fire off the ajax request and wait on the response to come back from the server. Once the response has come back, it will pick up where it left off (this is accomplished through the use of setInterval to create a loop that continually checks to see if the results have been reported back). This allows you to include custom ajax functions within an onsubmit form validation loop, just like you would with any other function.

Additionally, the following features are supported for ajax validations:
  • Customizable timeouts for expired requests. By default, if a form submission is waiting on results for an ajax validation and 30 seconds have elapsed, the form will automatically submit. Thus, users will not be prevented from submitting the form due to network issues or other problems with the ajax call.
  • Result caching. Once an ajax request comes back and returns results for a given form field's value, any subsequent validation of the same value will check the cache, instead of triggering a new request.
  • Discarding of outdated requests. One of the challenges in dealing with ajax is that there is no guarantee that requests will come back in order. Thus, if you're checking for the availability of a username and the user initially submits "dan" and then submits "dan17" a few seconds later, it is not unheard of for the "dan17" results to come back first, followed later by the "dan" results. Validanguage supports disregarding any older results through the use of an ajaxCounter that is incremented with each request. This counter will be sent to your validation callbacks so they can determine whether or not they are still relevant.
Timeouts and result caching can be disabled, if desired, via validanguage.settings.submitFormOnExpiredAjax and validanguage.settings.cacheAjaxLookups.

You can refer to the Ajax validation Test Cases page for an example of how to set this up. The important parts are the following 2 functions:
  • validanguage.setValidationStatus(id, returnStatus, type, errorMsg) -- Call this function inside your ajax callback to tell Validanguage that the ajax check has returned.
  • validanguage.isExpiredAjax(formFieldId, ajaxCounter) -- This function examines the ajaxLookup array to determine whether or not the specified ajaxCounter pertains to the most recent ajax call for that form field.

The isAjax support is primarily for advanced users who have a knowledge of server-side programming. In order to utilize the caching and discarding of outdated requests you will need to integrate the ajaxCounter variable into your ajax calls so that it is sent to the server and then returned inside the response (most likely via JSON encoding). To enable this, any function labelled with isAjax will be called with the form field value as the first argument and an incremented ajaxCounter value as the second argument.