Docs
Everything You Need to Know
Forms & Validation
Use
To validate and convert form elements into JSON you need to define a ChocolateChip-UI Form object. $.Form
expects an array of objects, each of which defines a form element to validate. A Form validation object have three parts: the element to validate, the type of validation, and a callback to execute if validation fails. If validation passes on all elements pass to $.Form, it converts the collection of values into a JSON object.
Because $.Form
takes individual node elements to validate, you do not need to enclose the elements in an actual form tag. This means you have to include every element whose data you want.
To set up a validation object, we need to providing a selector for each element, preferably this should be an ID. This is necessary since form elements can have the same name. Next you want to provide the type of validation to run on the element. ChocolateChip-UI has validators for the following types:
- notempty: check that an input is not empty
- number: check that a value is a number
- text: check that a value is pure text
- alphanumeric: check that a value is alphanumeric
- username: check that a value is alphanumeric and optional number of characters
- email: check that a value is a valid email
- phone: check US/Canada and international phone numbers
- url: check that a value is a valid url
- age: check that a value is a number above provide minimum
- checkbox: check that a checkbox is selected
- radio: check that a radio button is selected
- selectbox: check that an option is selected
- password: check that two passwords match and an optional minimum length
- switch: check that a switch is on
- selectlist: check that a select list item is selected
- multiselectlist: check that a multi-select list item is selected
JSON from Form
In order to get a JSON object from your form elements, you need to name your elements appropriately. $.Form
lets you use an underscore `_` as a delemiter to describe the structure of your JSON. So, if you wanted an object named `person` followed by `name` and `first` and `last`, you would create a name on elements as follows:
<input type='text' name='person_name_first'>
<input type='text' name='person_name_last'>
<input type='text' name='person_age'>
<input type='text' name='person_job'>
$.Form
will create the following object from the above names:
{ "person": { "age": 32, "job": "developer" "name": { "first": "John", "last": "Doe" } } }
After providing the type of validation, you can also provide a callback to execute if the element does not validate. You might do this to notify the user of the problem and how to address it.
Below is an example setup for form validation:
$('#validateForm').on('click', function() { var myForm = $.Form([ { element: '#firstName', type: 'text', callback: function() { alert('The first name needs to be text!') } }, { element: '#lastName', type: 'text' }, { element: '#age', type: 'age', min: 20, callback: function() { alert("Please provide a proper age.") } }, { element: '#fav1', type: 'checkbox' }, { element: '#fav2', type: 'checkbox' }, { element: '#fav3', type: 'checkbox' }, { element: '#fav4', type: 'checkbox' }, { element: '#fav5', type: 'checkbox' }, { element: '#fav6', type: 'checkbox' } ]) // Check that the validation passed, // then return the form's JSON: if(!myForm.errors()) { var formData = myForm.get() console.dir(formData) } })
Form Accessor Methods
When you use $.Form
, it returns an object that has three accessor methods:
- myForm.get()
- myForm.errors()
- myForm.getErrors()
As we saw above, using .get()
on your $.Form
object returns the values of the inputs as a JSON object. You can check if there were any errors using .errors()
. This returns a boolean true or false. Finally, .getErrors()
returns any error messages generated while processing the inputs. Notice how we use all three methods in this example:
$('#validateForm').on('click', function() { var myForm = $.Form([ { element: '#firstName', type: 'text' }, { element: '#lastName', type: 'text' } ]) // Check for errors using myForm.errors(): if(!myForm.errors()) { // Get the data using myForm.get(): var formData = myForm.get() console.dir(formData) } else { // If errors, output them using myFrom.getErrors(): var errors = myForm.getErrors() console.dir(errors) } })
Custom Validators
Out of the box ChocolateChip-UI has number of useful validators. If you need a validation that isn't provided, you can create a custom validator to use with $.Form
. This is done with the $.validateWithRegex()
method. This takes two arguments: the input to check and the regular expression to use. For example, this will let you set up a validator for a phone number that differs from the US/Canada or standard international form that ChocolateChip-UI provides.
/* Expression to parse Australian landline telephone numbers. Will only accept valid STD codes. Allows for parens around the STD code and either spaces or dashes between number groups. */ /* This can handle these formats: (02) 9323 1234 | 0293231234 | 02-9323-1234 */ var phoneRegex = /^\({0,1}0(2|3|7|8)\){0,1}(\ |-){0,1}[0-9]{4}(\ |-){0,1}[0-9]{4}$/ $.validateWithRegex('#australianPhoneNum', phoneRegex)
$.registerCustomValidator
If you want to use a custom validator with $.Form
so that you can get a JSON object, you need to do two things: register the custom validator and indicate it in the $.Form
setup. To register a custom validator you use $.registerCustomValidator
. This takes two arguments: a name for your validator and a regular express. The name should start with 'custom-'. This is required for registering it. The regular expression should be in the following format: /abc/
. Below is an example custom validator used with $.Form
:
$.registerCustomValidator('custom-textWithSpaces', /^[A-Za-z\W]+$/); // Setup Form validation: $('#validateForm').on('click', function() { var myForm = $.Form([ { element: '#name', // Important: prefix custom validator with "custom-": type: 'custom-textWithSpaces', callback: function() { alert('The first name needs to be text!') } } ]) if(!myForm.errors()) { $.formData = myForm.get() console.dir($.formData) } })
When you define a custom validator remember that you must prefix the name with "custom-". In the above example, notice how we registered out validator as "custom-textWithSpaces".
Importing Form Utilities
The previous utilities are included by default in ChocolateChip-UI. To use any of the following utilities you'll need to import them into the app
file inside your project's dev folder:
import './src/utils/form' import './src/utils/validators' import './src/utils/serialize'
You do not need to import all of these. If you want to use the form features that convert a form into a JSON object, you'll also need to import validators
. If all you want to do is serialize a form, you can import it individually.