Docs

Everything You Need to Know

Forms & Validation

API

Form Methods

  • $(form).serialize()
  • $(form).serializeArray()

Form Validation

  • $.Form(arguments)
  • myForm.errors()
  • myForm.getErrors()
  • myForm.get()
  • $(selector).isNotEmpty()
  • $(selector).validateAlphabetic()
  • $(selector).validateText()
  • $(selector).validateNumber()
  • $(selector).validateAlphaNumeric()
  • $(selector).validateUserName()
  • $(selector).validateEmail()
  • $(selector).validatePhoneNumber()
  • $(selector).validateUrl()
  • $(selector).validateAge()
  • $(selector).validateCheckbox()
  • $(selector).validateRadioButtons()
  • $(selector).validateSelectBox()
  • $(selector).validateSwitch()
  • $(selector).validateSelectList()
  • $(selector).validateMultiSelectList()
  • $.validatePassword(password1, password2, minimum)
  • $.validateWithRegex(input, regex)
  • $.registerCustomValidator(name, regex)

$(form).serialize()

This method when executed on a form encodes the values of its elements as a string for submission in a Ajax post.

$(form).serializeArray()

This method when executed returns the values of a form's elements as an array of names and values.

Because of limitations to language support for various types of encoding, if the data you need to pass is complex, it is better to pass it as a stringified JSON object. You can use the $.Form() method for that purpose.

$.Form(arguments)

$.Form is unique to ChocolateChip-UI. It takes an array of form elements to validate and returns an object with the validation state. The return object also lets you extract the form's data as a JSON object, which you can strigify and post to the server.

No Actual Form Required. Because $.Form directly accesses the inputs passed as arguments, you do not need to wrap those inputs in a form element. This gives you considerable freedom about how to structure your layout.

Extracting JSON from a Form

To extract JSON from a form you do need to set up your form elements. This involves some naming conventions for the inputs. Underscores are used to define the structure for your JSON object. These would be equival to the dot notation used to access the final object. So, to get a person object from a form, you could setup the elements like this:

<input type='text' id='firstName' name='person_name_first'>
<input type='text' id='lastName' name='person_name_last'>
<input type='text' id='age' name='person_age'>
<input type='text' id='job' name='person_job'>

For this we'll assume the user enterd "Joe" as the first name, "Bodoni" as the last name, "32" as the age and "Developer" as the job. To extract this data from this form, we can do the following:

var myForm = $.Form([
  {
    element: '#firstName',
    type: 'text'
  },
  {
    element: '#lastName',
    type: 'text'
  },
  {
    element: '#age',
    type: 'age',
  },
  {
    element: '#job',
    type: 'text'
  }
])

myForm.get()
/*
returns:
{
  person: {
    age: 32,
    job: "Developer",
    name: {
      first: "Joe",
      last: "Bodoni"
    }
  }
}
*/

The form object also allows you to track errors:

var myForm = $.Form([
  {
    element: '#name',
    type: 'text'
  }
  {
    element: '#age',
    type: 'age'
  }
])
// Check for errors:
if (myForm.errors()) {
  // Output the errors:
  var errors = myForm.getErrors()
  console.dir(errors)
// Otherwise output value:
} else {
  // Get the JSON from $.From object:
  var results = myForm.get()
  console.dir(results)
}

No Validation, Just Data

If you are not interested in validation and just want to get the data from your form elements as JSON, you can pass the options to $.Form with nothing but the element selectors:

<!-- Markup for form elements -->
<ul class="list">
  <li>
    <label for="nameFirst">First Name: </label>
    <input type="text" name='person_name_first' id='nameFirst'>
  </li>
  <li>
    <label for="nameLast">Last Name: </label>
    <input type="text" name='person_name_last' id='nameLast'>
  </li>
  <li>
    <label for="age">Age: </label>
    <input type="number" name='person_age' id='age'>
  </li>
  <li>
    <button class='raised' id='validateForm'>Validate</button>
  </li>
</ul>
// Get input values without validation:
var myForm = $.Form([
  {
    element: '#nameFirst'
  },
  {
    element: '#nameLast'
  },
  {
    element: '#age'
  }
])

// Returns JSONified data for these elements:
{
  "person":{
    "name":{
      "first":"John",
      "last":"Doe"
    },
    "age":"23"
  }
}

Validation Types

When you provide a type for a form element, this tells $.Form to do a validity test. At minimum it will check that each element has a value. If it does not, it will flag that element by attaching a class that causes the element to show a red border. It will still return an object, but those inputs without value will be excluded from the final object.

Many of the validators have options you can provide for refining how validation works. You can also provide a callback to execute with validation fails. You could use this to popup a message explaining the failure.

Options for Validators

Some validation types can have additional options to fine tune the validation:

notempty

This will check that the input is not empty.

var myForm = $.Form([{
  element: '#myInput',
  type: 'notempty',
  callback: function() {
    alert('The input cannot be empty.')
  }
}])

number

This will check that the value is a number.

var myForm = $.Form([{
  element: '#numberInput',
  type: 'number'
}])

text

This will check that the value is text.

var myForm = $.Form([{
  element: '#textInput',
  type: 'text'
}])

alphanumeric

This will check that the value is text, number or a mix.

var myForm = $.Form([{
  element: '#myInput',
  type: 'alphanumeric'
}])

username

This will check that two usernames match. This can take a min value to indicate the minimum number of characters for a username:

var myForm = $.Form([{
  element: '#userName',
  type: 'username',
  // Minimum number of characters:
  min: 6,
  callback: function() {
    alert('The user name must have at least 6 characters.')
  }
}])

email

This will check that the value is a valid email.

var myForm = $.Form([{
  element: '#emailInput',
  type: 'email',
  callback: function() {
    alert('This is not a valid email!')
  }
}])

phone

This will check that the value is a valid phone number in North American format. For other international number formats you will have to create your own custom validator using

var myForm = $.Form([{
  element: '#phoneInput',
  type: 'phone',
  callback: function() {
    alert('Please enter a valid phone number.')
  }
}])

url

This will check that the value is a valid url.

var myForm = $.Form([{
  element: '#urlInput',
  type: 'url',
  callback: function() {
    alert('This is not a valid url.')
  }
}])

age

This will check that the value is a number. This can take a min value to indicate the minimum age to pass validation:

var myForm = $.Form([{
  element: '#age',
  type: 'age',
  // Minimum age requried:
  min: 21,
  callback: function() {
    alert('You are not old enough!')
  }
}])

checkbox

This will check that a checkbox is selected.

var myForm = $.Form([{
  element: '#myCheckbox',
  type: 'checkbox'
}])

radio

This will check that a radio button is selected.

var myForm = $.Form([{
  element: '#myRadio',
  type: 'radio'
}])

selectbox

This will check that a selection was made on a select box.

var myForm = $.Form([{
  element: '#selectBox',
  type: 'selectbox'
}])

password

This will check that the value to two password inputs are identical. This can take a min value to indicate the minimum number of characters required to pass validation:

var myForm = $.Form([{
  element: '#password1',
  element2: '#password2'
  type: 'password',
  // Minimum characters requried:
  min: 8,
  callback: function() {
    alert('The passwords to not match!')
  }
}])

switch

This will check that a switch is on.

var myForm = $.Form([{
  element: '#mySwitch',
  type: 'switch'
}])

selectlist

This will check that a select has been made on a select list.

var myForm = $.Form([{
  element: '#selectList',
  type: 'selectlist'
}])

multiselectlist

This will check that a select has been made in a multi-select list.

var myForm = $.Form([{
  element: '#multiSelectList',
  type: 'multiselectlist'
}])

Custom Validation

You can write your own regular expression to run again an input value. To do that you use $.validateWithRegex(input, regex). You pass the method the input whose value you want to check and a regular expression to use against that value. This returns an object just like $.Form with the same methods for error tracking and data extraction.

var price = $.validateWithRegex('price', /^(\d*([,](?=\d{3}))?\d+)+((?!\2)[.]\d\d)?$/);
// Check for errors:
if (price.errors()) {
  console.dir(price.getErrors());
} else {
  // Otherwise output value:
  console.dir(price.get())
}

Custom Validator

You can also write your own custom validators to use with $.Form. To do so, use $.registerCustomValidator(name, regex). You write a custom validator the same as you do with $.validateWithRegex. The difference is that the name you provide this custom validator can be used as a type with $.Form like other types. A custom validator name must begin with custom- or it will not work:

// Define custom validator
// that check for words with possible spaces.
// Notice that the custom name begins with 'custom-':
$.registerCustomValidator('custom-textWithSpaces', /^[A-Za-z\W]+$/);

// Use custom validator with $.Form:
$('#customValidatorBtn').on('click', function() {
  var customValidator = $.Form([
    {
      element: '#customFormInput',
      // Important: prefix custom validator with "custom-":
      type: 'custom-textWithSpaces',
      callback: function() {
        alert('The first name needs to be text!')
      }
    }
  ])
  if(!customValidator.errors()) {
    var formData = customValidator.get()
    console.dir(formData)
  }
})