Form Validation

revIgniter provides a comprehensive form validation and data prepping library that helps minimize the amount of code you'll write.

 

Overview

Before explaining revIgniter's approach to data validation, let's describe the ideal scenario:

  1. A form is displayed.
  2. You fill it in and submit it.
  3. If you submitted something invalid, or perhaps missed a required item, the form is redisplayed containing your data along with an error message describing the problem.
  4. This process continues until you have submitted a valid form.

On the receiving end, the script must:

  1. Check for required data.
  2. Verify that the data is of the correct type, and meets the correct criteria. For example, if a username is submitted it must be validated to contain only permitted characters. It must be of a minimum length, and not exceed a maximum length. The username can't be someone else's existing username, or perhaps even a reserved word. Etc.
  3. Sanitize the data for security.
  4. Pre-format the data if needed (Does the data need to be trimmed? HTML encoded? Etc.)
  5. Prep the data for insertion in the database.

Although there is nothing terribly complex about the above process, it usually requires a significant amount of code, and to display error messages, various control structures are usually placed within the form HTML. Form validation, while simple to create, is generally very messy and tedious to implement.

 

Form Validation Tutorial

What follows is a "hands on" tutorial for implementing RevIgniters Form Validation.

In order to implement form validation you'll need three things:

  1. A View file containing a form.
  2. A View file containing a "success" message to be displayed upon successful submission.
  3. A controller to receive and process the submitted data.

Let's create those three things, using a member sign-up form as the example.

The Form

Create a form called myForm.lc. In it, place this code and save it to your application/views/ folder:

</html>
  <head>
    <title>My Form</title>
  </head>
  <body>

    <p>[[gData["formErrors"]]]</p>

    [[gData["formOpenTag"]]]

    <h5>Username</h5>
    <input type="text" name="username" value="" size="50" />

    <h5>Password</h5>
    <input type="text" name="password" value="" size="50" />

    <h5>Password Confirm</h5>
    <input type="text" name="passconf" value="" size="50" />

    <h5>Email Address</h5>
    <input type="text" name="email" value="" size="50" />

    <div><input type="submit" value="Submit" /></div>

    </form>

  </body>
</html>

The Success Page

Create a form called formSuccess.lc. In it, place this code and save it to your application/views/ folder:

<html>
  <head>
    <title>My Form</title>
  </head>
  <body>

    <h3>Your form was successfully submitted!</h3>

    <p>[[gData["againAnchor"]]]</p>

  </body>
</html>

The Controller

Create a controller called form.lc. In it, place this code and save it to your application/controllers/ folder:

<?lc

# PUT YOUR HANDLER NAMES  INTO THE GLOBAL gControllerHandlers AS A COMMA SEPARATED LIST
put "index" into gControllerHandlers

# PUT ALL THE VARIABLES TO BE MERGED WITH VIEWS INTO THE ARRAY VARIABLE gData


command index
  put "form,url" into tHelpers
  rigLoadHelper tHelpers

  rigLoaderLoadLibrary "Formvalidation"

  # BUILD THE FORM OPEN TAG
  put rigFormOpen("form") into gData["formOpenTag"]

  if rigFormValidRun() is FALSE then
    # GET VALIDATION ERRORS
    put rigValidationErrors() into gData["formErrors"]
    get rigLoadView("myForm")
  else
    # THIS LINK IS ON THE SUCCESS PAGE
    put rigAnchor("form", "Try it again!") into gData["againAnchor"]
    get rigLoadView("formSuccess")
  end if
end index

Note: If CSRF (gConfig["csrf_protection"]) is set to true in application/config/config.lc, please make sure that the value set for the cookie domain (gConfig["cookie_domain"]) is correct. For the purpose of this tutorial you can leave gConfig["cookie_domain"] empty.

Try it!

To try your form, visit your site using a URL similar to this one:

example.com/index.lc/form/

If you submit the form you should simply see the form reload. That's because you haven't set up any validation rules yet.

Since you haven't told the Form Validation library to validate anything yet, it returns FALSE (boolean false) by default. The rigFormValidRun() function only returns TRUE if it has successfully applied your rules without any of them failing.

Explanation

You'll notice several things about the above pages:

The form (myForm.lc) is a standard web form with a couple exceptions:

  1. It uses a form helper to create the form opening. Technically, this isn't necessary. You could create the form using standard HTML. However, the benefit of using the helper is that it generates the action URL for you, based on the URL in your config file. This makes your application more portable in the event your URLs change.
    [[gData["formOpenTag"]]]

    This expression will be merged with the result of the rigFormOpen() function in the controller.

  2. At the top of the form you'll notice the following expression:
    [[gData["formErrors"]]]

    This expression will be merged with any error messages sent back by the validator. If there are no messages it is merged to an empty string.

The controller (form.lc) has one handler: index. This handler initializes the validation library and loads the form helper and URL helper used by your view files. It also runs the validation routine. Based on whether the validation was successful it either presents the form or the success page.

Setting Validation Rules

revIgniter lets you set as many validation rules as you need for a given field, cascading them in order, and it even lets you prep and pre-process the field data at the same time. To set validation rules you will use the rigSetRules handler:

rigSetRules

The above function takes three parameters as input:

  1. The field name - the exact name you've given the form field.
  2. A "human" name for this field, which will be inserted into the error message. For example, if your field is named "user" you might give it a human name of "Username". Note: If you would like the field name to be stored in a language file, please see Translating Field Names.
  3. The validation rules for this form field.


Here is an example. In your controller (form.lc), add this code just below the validation initialization function:

rigSetRules "username", "Username", "requiredR"
rigSetRules "password", "Password", "requiredR"
rigSetRules "passconf", "Password Confirmation", "requiredR"
rigSetRules "email", "Email", "requiredR"

Your controller should now look like this:

<?lc

# PUT YOUR HANDLER NAMES  INTO THE GLOBAL gControllerHandlers AS A COMMA SEPARATED LIST
put "index" into gControllerHandlers

# PUT ALL THE VARIABLES TO BE MERGED WITH VIEWS INTO THE ARRAY VARIABLE gData


command index
  put "form,url" into tHelpers
  rigLoadHelper tHelpers

  rigLoaderLoadLibrary "Formvalidation"

  # BUILD THE FORM OPEN TAG
  put rigFormOpen("form") into gData["formOpenTag"]

  rigSetRules "username", "Username", "requiredR"
  rigSetRules "password", "Password", "requiredR"
  rigSetRules "passconf", "Password Confirmation", "requiredR"
  rigSetRules "email", "Email", "requiredR"

  if rigFormValidRun() is FALSE then
    # GET VALIDATION ERRORS
    put rigValidationErrors() into gData["formErrors"]
    get rigLoadView("myForm")
  else
    # THIS LINK IS ON THE SUCCESS PAGE
    put rigAnchor("form", "Try it again!") into gData["againAnchor"]
    get rigLoadView("formSuccess")
  end if
end index

Note: The last character ("R") in rules indicate, that it is a rule and helps to avoid name conflicts.

Now submit the form with the fields blank and you should see the error messages. If you submit the form with all the fields populated you'll see your success page.

Note: The form fields are not yet being re-populated with the data when there is an error. We'll get to that shortly.

Setting Rules Using an Array

Before moving on, it should be noted that the rule setting function can be passed an array if you prefer to set all your rules in one action. If you use this approach you must name your array keys as indicated:

put "username" into tConfig[1]["field"]
put "Username" into tConfig[1]["label"]
put "requiredR" into tConfig[1]["rules"]

put "password" into tConfig[2]["field"]
put "Password" into tConfig[2]["label"]
put "requiredR" into tConfig[2]["rules"]

put "passconf" into tConfig[3]["field"]
put "Password Confirmation" into tConfig[3]["label"]
put "requiredR" into tConfig[3]["rules"]

put "email" into tConfig[4]["field"]
put "Email" into tConfig[4]["label"]
put "requiredR" into tConfig[4]["rules"]

rigSetRules tConfig

Cascading Rules

revIgniter lets you pipe multiple rules together. Let's try it. Change your rules in the third parameter of rule setting function, like this:

rigSetRules "username", "Username", "requiredR|minLengthR[5]|maxLengthR[12]"
rigSetRules "password", "Password", "requiredR|matchesR[passconf]"
rigSetRules "passconf", "Password Confirmation", "requiredR"
rigSetRules "email", "Email", "requiredR|validEmailR"

The above code sets the following rules:

  1. The username field must be no shorter than 5 characters and no longer than 12.
  2. The password field must match the password confirmation field.
  3. The email field must contain a valid email address.

Give it a try! Submit your form without the proper data and you'll see new error messages that correspond to your new rules. There are numerous rules available which you can read about in the validation reference.

Prepping Data

In addition to the validation functions like the ones we used above, you can also prep your data in various ways. For example, you can set up rules like this:

rigSetRules "username", "Username", "trim|requiredR|minLengthR[5]|maxLengthR[12]|xssClean"
rigSetRules "password", "Password", "trim|requiredR|matchesR[passconf]|md5"
rigSetRules "passconf", "Password Confirmation", "trim|requiredR"
rigSetRules "email", "Email", "trim|requiredR|validEmailR"

In the above example, we are "trimming" the fields, converting the password to md5, and running the username through the "xssClean" handler, which removes malicious data. See Prepping Reference below.

Note: You will generally want to use the prepping functions after the validation rules so if there is an error, the original data will be shown in the form.

Re-populating the form

Thus far we have only been dealing with errors. It's time to repopulate the form field with the submitted data. revIgniter offers several helper functions that permit you to do this. The one you will use most commonly is:

rigSetValue("fieldname")

Complement your form.lc controller as shown:

<?lc

# PUT YOUR HANDLER NAMES  INTO THE GLOBAL gControllerHandlers AS A COMMA SEPARATED LIST
put "index" into gControllerHandlers

# PUT ALL THE VARIABLES TO BE MERGED WITH VIEWS INTO THE ARRAY VARIABLE gData


command index
  put "form,url" into tHelpers
  rigLoadHelper tHelpers

  rigLoaderLoadLibrary "Formvalidation"

  # BUILD THE FORM OPEN TAG
  put rigFormOpen("form") into gData["formOpenTag"]

  rigSetRules "username", "Username", "requiredR"
  rigSetRules "password", "Password", "requiredR"
  rigSetRules "passconf", "Password Confirmation", "requiredR"
  rigSetRules "email", "Email", "requiredR"

  if rigFormValidRun() is FALSE then
    # GET VALIDATION ERRORS
    put rigValidationErrors() into gData["formErrors"]

    # RE-POPULATE THE FORM
    put rigSetValue("username") into gData["name"]
    put rigSetValue("password") into gData["pw"]
    put rigSetValue("passconf") into gData["pwconf"]
    put rigSetValue("email") into gData["mail"]
    
    get rigLoadView("myForm")
  else
    # THIS LINK IS ON THE SUCCESS PAGE
    put rigAnchor("form", "Try it again!") into gData["againAnchor"]
    get rigLoadView("formSuccess")
  end if
end index

Open your myForm.lc view file and update the value in each field using the corresponding expression to be merged:

<head>
<title>My Form</title>
</head>
<body>

<p>[[gData["formErrors"]]]</p>

[[gData["formOpenTag"]]]

<h5>Username</h5>
<input type="text" name="username" value="[[gData["name"]]]" size="50" />

<h5>Password</h5>
<input type="text" name="password" value="[[gData["pw"]]]" size="50" />

<h5>Password Confirm</h5>
<input type="text" name="passconf" value="[[gData["pwconf"]]]" size="50" />

<h5>Email Address</h5>
<input type="text" name="email" value="[[gData["mail"]]]" size="50" />

<div><input type="submit" value="Submit" /></div>

</form>

</body>
</html>

Now reload your page and submit the form so that it triggers an error. Your form fields should now be re-populated

Note: The Handler Reference section below contains handlers that permit you to re-populate <select> menus, radio buttons, and checkboxes.

Important Note: If you use an array as the name of a form field, you must supply it as an array to the function. Example:

<input type="checkbox" name="myCheckbox[]" value="A" [[gData["myCheckA"]]] />

For more info please see the Using Arrays as Field Names section below.

Callbacks: Your own Validation Handlers

The validation system supports callbacks to your own validation handlers. This permits you to extend the validation library to meet your needs. For example, if you need to run a database query to see if the user is choosing a unique username, you can create a callback handler that does that. Let's create an example of this.

In your controller, change the "username" rule to this:

rigSetRules "username", "Username", "callback_userNameCheck"

Then add a new handler called userNameCheck to your controller. Here's how your controller should now look:

<?lc

# PUT YOUR HANDLER NAMES  INTO THE GLOBAL gControllerHandlers AS A COMMA SEPARATED LIST
put "index,userNameCheck" into gControllerHandlers

# PUT ALL THE VARIABLES TO BE MERGED WITH VIEWS INTO THE ARRAY VARIABLE gData


command index
  put "form,url" into tHelpers
  rigLoadHelper tHelpers

  rigLoaderLoadLibrary "Formvalidation"

  # BUILD THE FORM OPEN TAG
  put rigFormOpen("form") into gData["formOpenTag"]

  rigSetRules "username", "Username", "callback_userNameCheck"
  rigSetRules "password", "Password", "requiredR"
  rigSetRules "passconf", "Password Confirmation", "requiredR"
  rigSetRules "email", "Email", "requiredR"

  if rigFormValidRun() is FALSE then
    # GET VALIDATION ERRORS
    put rigValidationErrors() into gData["formErrors"]

    # RE-POPULATE THE FORM
    put rigSetValue("username") into gData["name"]
    put rigSetValue("password") into gData["pw"]
    put rigSetValue("passconf") into gData["pwconf"]
    put rigSetValue("email") into gData["mail"]
    
    get rigLoadView("myForm")
  else
    # THIS LINK IS ON THE SUCCESS PAGE
    put rigAnchor("form", "Try it again!") into gData["againAnchor"]
    get rigLoadView("formSuccess")
  end if
end index


command userNameCheck pStr
  if pStr = "test" then
    rigSetMessage "userNameCheck", "The %s field can not be the word" && quote & "test" & quote & "."
    return FALSE
  else
    return TRUE
  end if
end userNameCheck

Note: Don't forget to add the "userNameCheck" handler name to the list in the gControllerHandlers variable at the top of the controller file.

Reload your form and submit it with the word "test" as the username. You can see that the form field data was passed to your callback function for you to process.

To invoke a callback just put the handler name in a rule, with "callback_" as the rule prefix.

You can also process the form data that is passed to your callback and return it. If your callback returns anything other than a boolean TRUE/FALSE it is assumed that the data is your newly processed form data.

Setting Error Messages

All of the native error messages are located in the following language file: language/english/formvalidationLang.lc

To set your own custom message you can either edit that file, or use the following function:

rigSetMessage "rule", "Error Message"

Where rule corresponds to the name of a particular rule, and Error Message is the text you would like displayed.

If you include %s in your error string, it will be replaced with the "human" name you used for your field when you set your rules.

In the "callback" example above, the error message was set by passing the name of the handler:

rigSetMessage "userNameCheck"

You can also override any error message found in the language file. For example, to change the message for the "requiredR" rule you will do this:

rigSetMessage "requiredR", "Your custom message here"

Translating Field Names

If you would like to store the "human" name you passed to the rigSetRules handler in a language file, and therefore make the name able to be translated, here's how:

First, prefix your "human" name with lang:, as in this example:

rigSetRules "firstname", "lang:firstname", "requiredR"

Then, store the name in one of your language file arrays (without the prefix):

put "First Name" into gLang["firstname"]

Note: If you store your array item in a language file that is not loaded automatically by revIgniter, you'll need to remember to load it in your controller using:

rigLoadLanguage "filename"

See the Language Library page for more info regarding language files.

Changing the Error Delimiters

By default, the Form Validation library adds a paragraph tag (<p>) around each error message shown. You can either change these delimiters globally or individually.

  1. Changing delimiters Globally

    To globally change the error delimiters, in your controller handler, just after loading the Form Validation library, add this:

    rigSetErrorDelimiters "<div class=" & quote & "error" & quote & ">", "</div>"

    In this example, we've switched to using div tags.

  2. Changing delimiters Individually

    Each of the two error generating functions shown in this tutorial can be supplied their own delimiters as follows:

    put rigFormError("fieldname", "<div class=" & quote & "error" & quote & ">", "</div>") into gData["fieldNameError"]

    Or:

    put rigValidationErrors("<div class=" & quote & "error" & quote & ">", "</div>") into gData["formErrors"]

Showing Errors Individually

If you prefer to show an error message next to each form field, rather than as a list, you can use the rigFormError() function.

Try it! Change your controller so that it looks like this:

put rigFormError("username") into gData["nameError"]
put rigFormError("password") into gData["pwError"]
put rigFormError("passconf") into gData["pwConfError"]
put rigFormError("email") into gData["emailError"]

Change your form so that it looks like this:

<h5>Username</h5>
[[gData["nameError"]]]
<input type="text" name="username" value="[[gData["name"]]]" size="50" />

<h5>Password</h5>
[[gData["pwError"]]]
<input type="text" name="password" value="[[gData["pw"]]]" size="50" />

<h5>Password Confirm</h5>
[[gData["pwConfError"]]]
<input type="text" name="passconf" value="[[gData["pwconf"]]]" size="50" />

<h5>Email Address</h5>
[[gData["emailError"]]]
<input type="text" name="email" value="[[gData["mail"]]]" size="50" />

If there are no errors, nothing will be shown. If there is an error, the message will appear.

Important Note: If you use an array as the name of a form field, you must supply it as an array to the function. Example:

put rigFormError("myCheckbox[]") into gData["checkboxError"]

For more info please see the Using Arrays as Field Names section below.

 

Saving Sets of Validation Rules to a Config File

A nice feature of the Form Validation library is that it permits you to store all your validation rules for your entire application in a config file. You can organize these rules into "groups". These groups can either be loaded automatically when a matching controller/handler is called, or you can manually call each set as needed.

How to save your rules

To store your validation rules, simply create a file named validation.lc in your application/config/ folder. In that file you will place an array with your rules. As shown earlier, the validation array will have this prototype:

<?lc


local sConfig


put "username" into sConfig[1]["field"]
put "Username" into sConfig[1]["label"]
put "requiredR" into sConfig[1]["rules"]

put "password" into sConfig[2]["field"]
put "Password" into sConfig[2]["label"]
put "requiredR" into sConfig[2]["rules"]

put "passconf" into sConfig[3]["field"]
put "Password Confirmation" into sConfig[3]["label"]
put "requiredR" into sConfig[3]["rules"]

put "email" into sConfig[4]["field"]
put "Email" into sConfig[4]["label"]
put "requiredR" into sConfig[4]["rules"]


# THIS FUNCTION IS MANDATORY
function rigFetchValidationConf
  return sConfig
end rigFetchValidationConf

Your validation rule file will be loaded automatically and used when you call the rigFormValidRun() function.

Please note that you MUST add the rigFetchValidationConf() function to your configuration file as shown above.


There is an alternative to generate the rules array in a config file. It significantly reduces the required amount of code. Using this approach the example above would read like:

<?lc


local sConfig


rigAddValidationGrp
rigAddValidationRules "username", "Username", "requiredR", sConfig
rigAddValidationRules "password", "Password", "requiredR", sConfig
rigAddValidationRules "passconf", "Password", "requiredR", sConfig
rigAddValidationRules "email", "Email", "requiredR", sConfig


# THIS FUNCTION IS MANDATORY
function rigFetchValidationConf
  return sConfig
end rigFetchValidationConf

Creating Sets of Rules

In order to organize your rules into "sets" requires that you place them into "sub arrays". Consider the following example, showing two sets of rules. We've arbitrarily called these two rules "signup" and "email". You can name your rules anything you want:

<?lc


local sConfig


put "username" into sConfig["signup"][1]["field"]
put "Username" into sConfig["signup"][1]["label"]
put "requiredR" into sConfig["signup"][1]["rules"]

put "password" into sConfig["signup"][2]["field"]
put "Password" into sConfig["signup"][2]["label"]
put "requiredR" into sConfig["signup"][2]["rules"]

put "passconf" into sConfig["signup"][3]["field"]
put "Password Confirmation" into sConfig["signup"][3]["label"]
put "requiredR" into sConfig["signup"][3]["rules"]

put "email" into sConfig["signup"][4]["field"]
put "Email" into sConfig["signup"][4]["label"]
put "requiredR" into sConfig["signup"][4]["rules"]


put "emailaddress" into sConfig["email"][1]["field"]
put "EmailAddress" into sConfig["email"][1]["label"]
put "requiredR|validEmailR" into sConfig["email"][1]["rules"]

put "name" into sConfig["email"][2]["field"]
put "Name" into sConfig["email"][2]["label"]
put "requiredR|alphaR" into sConfig["email"][2]["rules"]

put "title" into sConfig["email"][3]["field"]
put "Title" into sConfig["email"][3]["label"]
put "requiredR" into sConfig["email"][3]["rules"]

put "message" into sConfig["email"][4]["field"]
put "MessageBody" into sConfig["email"][4]["label"]
put "requiredR" into sConfig["email"][4]["rules"]


# THIS FUNCTION IS MANDATORY
function rigFetchValidationConf
  return sConfig
end rigFetchValidationConf


Similar to the simple array example above there is an alternative to generate rules organized into "sets" too. Here is an example using the rules above:

<?lc


local sConfig


rigAddValidationGrp "signup"
rigAddValidationRules "username", "Username", "requiredR", sConfig
rigAddValidationRules "password", "Password", "requiredR", sConfig
rigAddValidationRules "passconf", "Password", "requiredR", sConfig
rigAddValidationRules "email", "Email", "requiredR", sConfig

rigAddValidationGrp "email"
rigAddValidationRules "emailaddress", "EmailAddress", "requiredR|validEmailR", sConfig
rigAddValidationRules "name", "Name", "requiredR|alphaR", sConfig
rigAddValidationRules "title", "Title", "requiredR", sConfig
rigAddValidationRules "message", "MessageBody", "requiredR", sConfig



# THIS FUNCTION IS MANDATORY
function rigFetchValidationConf
  return sConfig
end rigFetchValidationConf

Calling a Specific Rule Group

In order to call a specific group you will pass its name to the rigFormValidRun() function. For example, to call the signup rule you will do this:

if rigFormValidRun("signup") is FALSE then
  get rigLoadView("myForm")
else
  get rigLoadView("formSuccess")
end if

Associating a Controller Handler with a Rule Group

An alternate (and more automatic) method of calling a rule group is to name it according to the controller controller/handler you intend to use it with. For example, let's say you have a controller named member and a handler named signup. Here's what your controller might look like:

<?lc

# PUT YOUR HANDLER NAMES  INTO THE GLOBAL gControllerHandlers AS A COMMA SEPARATED LIST
put "index,member,signup" into gControllerHandlers

# PUT ALL THE VARIABLES TO BE MERGED WITH VIEWS INTO THE ARRAY VARIABLE gData



command member
  rigLoaderLoadLibrary "Formvalidation"
end member


command index
  -- YOUR CODE HERE
end index


command signup

  if rigFormValidRun() is FALSE then
    get rigLoadView("myForm")
  else
    get rigLoadView("formSuccess")
  end if
end signup

In your validation config file, you will name your rule group member/signup:

<?lc


local sConfig


put "username" into sConfig["member/signup"][1]["field"]
put "Username" into sConfig["member/signup"][1]["label"]
put "requiredR" into sConfig["member/signup"][1]["rules"]

put "password" into sConfig["member/signup"][2]["field"]
put "Password" into sConfig["member/signup"][2]["label"]
put "requiredR" into sConfig["member/signup"][2]["rules"]

put "passconf" into sConfig["member/signup"][3]["field"]
put "Password Confirmation" into sConfig["member/signup"][3]["label"]
put "requiredR" into sConfig["member/signup"][3]["rules"]

put "email" into sConfig["member/signup"][4]["field"]
put "Email" into sConfig["member/signup"][4]["label"]
put "requiredR" into sConfig["member/signup"][4]["rules"]


# THIS FUNCTION IS MANDATORY
function rigFetchValidationConf
  return sConfig
end rigFetchValidationConf

When a rule group is named identically to a controller/handler it will be used automatically when the rigFormValidRun() function is invoked from that controller/handler.


Similar to examples above you can reduce the amount of required code using the following approach:

<?lc


local sConfig


rigAddValidationGrp "member/signup"
rigAddValidationRules "username", "Username", "requiredR", sConfig
rigAddValidationRules "password", "Password", "requiredR", sConfig
rigAddValidationRules "passconf", "Password", "requiredR", sConfig
rigAddValidationRules "email", "Email", "requiredR", sConfig



# THIS FUNCTION IS MANDATORY
function rigFetchValidationConf
  return sConfig
end rigFetchValidationConf

 

Using Arrays as Field Names

The Form Validation library supports the use of arrays as field names. Consider this example:

<input type="text" name="options[]" value="" size="50" />

If you do use an array as a field name, you must use the EXACT array name in the Helper Handlers that require the field name, and as your Validation Rule field name.

For example, to set a rule for the above field you would use:

rigSetRules "options[]", "Options", "requiredR"

Or, to show an error for the above field you would use:

put rigFormError("options[]") into gData["optionsError"]

Or to re-populate the field you would use:

put rigSetValue("options[]") into gData["options"]

You can use multidimensional arrays as field names as well. For example:

<input type="text" name="options[size]" value="" size="50" />

Or even:

<input type="text" name="sports[nba][basketball]" value="" size="50" />

As with our first example, you must use the exact array name in the helper functions:

put rigFormError("sports[nba][basketball]") into gData["basketballError"]

If you are using checkboxes (or other fields) that have multiple options, don't forget to leave an empty bracket after each option, so that all selections will be added to the POST array:

<input type="checkbox" name="options[]" value="red" />
<input type="checkbox" name="options[]" value="blue" />
<input type="checkbox" name="options[]" value="green" />

Or if you use a multidimensional array:

<input type="checkbox" name="options[color][]" value="red" />
<input type="checkbox" name="options[color][]" value="blue" />
<input type="checkbox" name="options[color][]" value="green" />

When you use a helper function you'll include the bracket as well:

put rigFormError("options[color][]") into gData["colorError"]

 

Rule Reference

The following is a list of all the native rules that are available to use:

Rule Parameter Description Example
requiredR No Returns FALSE if the form element is empty.  
matchesR Yes Returns FALSE if the form element does not match the one in the parameter. matchesR[form_item]
minLengthR Yes Returns FALSE if the form element is shorter than the parameter value. minLengthR[6]
maxLengthR Yes Returns FALSE if the form element is longer than the parameter value. maxLengthR[12]
exactLengthR Yes Returns FALSE if the form element is not exactly the parameter value. exactLengthR[8]
greaterThanR Yes Returns FALSE if the form element is less than the parameter value or not numeric. greaterThanR[8]
lessThanR Yes Returns FALSE if the form element is greater than the parameter value or not numeric. lessThanR[8]
alphaR No Returns FALSE if the form element contains anything other than alphabetical characters.  
alphaNumericR No Returns FALSE if the form element contains anything other than alpha-numeric characters.  
alphaDashR No Returns FALSE if the form element contains anything other than alpha-numeric characters, underscores or dashes.  
alphaAccentR No Returns FALSE if the form element contains anything other than alphabetical or accented characters.  
alphaNumericAccentR No Returns FALSE if the form element contains anything other than alpha-numeric or accented characters.  
alphaDashAccentR No Returns FALSE if the form element contains anything other than alpha-numeric characters, accented characters, underscores or dashes.  
numericR No Returns FALSE if the form element contains anything other than numeric characters.  
isNumericR No Returns FALSE if the form element contains anything other than digits, optional leading minus sign, optional decimal point, and optional "E" or "e" (scientific notation) and !!!!!!! optional comma.  
integerR No Returns FALSE if the form element contains anything other than an integer.  
decimalR No Returns FALSE if the form element contains anything other than a decimal number.  
isNaturalR No Returns FALSE if the form element contains anything other than a natural number: 0, 1, 2, 3, etc.  
isNaturalNoZeroR No Returns FALSE if the form element contains anything other than a natural number, but not zero: 1, 2, 3, etc.  
validEmailR No Returns FALSE if the form element does not contain a valid email address.  
validEmailsR No Returns FALSE if any value provided in a comma separated list is not a valid email.  
validIpR No Returns FALSE if the supplied IP is not valid. Accepts an optional parameter of "IPv4" or "IPv6" to specify an IP format. The default checks for both formats.  
validBase64R No Returns FALSE if the supplied string contains anything other than valid Base64 characters.  

Note: These rules can also be called as discrete handlers. You need to prefix the rules with rig. For example:

rigRequiredR tString
put the result into tStringValidResult

 

Prepping Reference

The following is a list of all the prepping handlers that are available to use:

Name Parameter Description
xssClean No Runs the data through the XSS filtering handler, described in the Input Library page.
prepForForm No Converts special characters so that HTML data can be shown in a form field without breaking it.
prepURL No Adds "http://" to URLs if missing.
stripImageTags No Strips the HTML from image tags leaving the raw URL.
encodeLCTags No Converts rev / lc tags to entities.
trim No Trims whitespace at the start and at the end of a field.
md5 No Converts a field to md5.
sha1 No Converts a field to a base64 encoded SHA-1 digest.
sha3 No Converts a field to a base64 encoded SHA3-384 digest. Note: This handler requires LC server version 9 or higher.
htmlSpecialChars No Converts special characters to HTML entities.
urlDecodeStr No Decodes a URL that was encoded for posting to an HTTP server.

 

Handler Reference

The following handlers are intended for use in your controller handlers.

rigSetRules

Permits you to set validation rules, as described in the tutorial sections above:

rigAddValidationGrp pGroup

Defines a group name for a set of validation rules used in a validation configuration file, see the examples in the tutorial section Saving Groups of Validation Rules to a Config File

Parameters

rigAddValidationRules pField, pLabel, pRules, pConfArray

Adds rules to a validation array in a configuration file.

Parameters

Please see the examples in the tutorial section Saving Groups of Validation Rules to a Config File.

rigFormValidRun(pGroup, pData)

This function runs the validation routines. It returns boolean TRUE on success and FALSE on failure. You can optionally pass the name of the validation group via the function, as described in: Saving Groups of Validation Rules to a Config File.

Parameters

rigSetMessage

Permits you to set custom error messages. See Setting Error Messages above.

rigSetPrefilledValues pPrefilledValues

This command is needed if you use any prefilled form fields in combination with the rigRequiredR validation rule so that the validator yields an error whenever the user leaves a required prefilled form field untouched. You may store the values of your prefilled fields either in a comma delimited list or in an array.

Parameters

Let's say the default values of your form fields are "First Name", "Last Name" and "name@any.com". Then you would store these values in a validator variable like in the following example:

rigSetPrefilledValues "First Name,Last Name,name@any.com"
  
# OR ALTERNATIVELY
put "First Name" into tPrefilledArray[1]
put "Last Name" into tPrefilledArray[2]
put "name@any.com" into tPrefilledArray[3]
rigSetPrefilledValues tPrefilledArray

 

Helper Reference

The following helper handlers are available for use in the view files containing your forms.

rigFormError()

Shows an individual error message associated with the field name supplied to the function. Example:

put rigFormError("username") into gData["nameError"]

The error delimiters can be optionally specified. See the Changing the Error Delimiters section above.

rigValidationErrors()

Shows all error messages as a string: Example:

put rigValidationErrors() into gData["formErrors"]

The error delimiters can be optionally specified. See the Changing the Error Delimiters section above.

rigSetErrorDelimiters pOpenTag, pCloseTag

Use this handler to change error delimiters globally in your controller. Please see the Changing the Error Delimiters section above.

Parameters

rigSetValue()

Permits you to set the value of an input form or textarea. You must supply the field name via the first parameter of the function. The second (optional) parameter allows you to set a default value for the form. Example:

put rigSetValue("quantity", "0") into gData["quantity"]

The above form will show "0" when loaded for the first time.

rigSetSelect()

If you use a <select> menu, this function permits you to display the menu item that was selected. The first parameter must contain the name of the select menu, the second parameter must contain the value of each item, and the third (optional) parameter lets you set an item as the default (use boolean TRUE/FALSE).

Example:

put rigSetSelect("mySelect", "one") into gData["mySelectOne"]
put rigSetSelect("mySelect", "two", TRUE) into gData["mySelectTwo"]
put rigSetSelect("mySelect", "three") into gData["mySelectThree"]

Your view file should look like this:

<select name="mySelect">
<option value="one" [[gData["mySelectOne"]]] >One
<option value="two" [[gData["mySelectTwo"]]] >Two
<option value="three" [[gData["mySelectThree"]]] >Three
</select>

rigSetCheckbox()

Permits you to display a checkbox in the state it was submitted. The first parameter must contain the name of the checkbox, the second parameter must contain its value, and the third (optional) parameter lets you set an item as the default (use boolean TRUE/FALSE). Example:

put rigSetCheckbox("myCheck[]", "A") into gData["myCheckA"]
put rigSetCheckbox("myCheck[]", "B") into gData["myCheckB"]
put rigSetCheckbox("myCheck[]", "C") into gData["myCheckC"]

Your view file should look like this:

<input type="checkbox" name="myCheck[]" value="A" [[gData["myCheckA"]]] />
<input type="checkbox" name="myCheck[]" value="B" [[gData["myCheckB"]]] />
<input type="checkbox" name="myCheck[]" value="C" [[gData["myCheckC"]]] />

rigSetRadio()

Permits you to display radio buttons in the state they were submitted. This function is identical to the set_checkbox() function above.

put rigSetRadio("myRadio", "1", TRUE) into gData["myRadio1"]
put rigSetRadio("myRadio", "2") into gData["myRadio2"]

Your view file should look like this:

<input type="radio" name="myRadio" value="1" [[gData["myRadio1"]]] />
<input type="radio" name="myRadio" value="2" [[gData["myRadio2"]]] />