JAVASCRIPT
Form Validation
All samples are using Ink.requireModules
, please read how to use it at Ink.requireModules section
A FormElement represents a single form element to be validated.
It is constructed with a DOM form element, and options.
This class contains methods to parse rules and apply them to its element, and also formats the error messages to be displayed in case of an error.
You don't normally call "new FormElement" yourself. This is done internally.
Method name | Description |
---|---|
new FormElement(element, options) | Constructor |
.displayErrors() | Displays error messages and marks as invalid, if this is invalid. |
.forceInvalid([message]) | Forcefully mark this FormElement as invalid. Use unsetInvalid() to remove this forced invalidation. |
.forceValid() | Forcefully mark this FormElement as valid |
.getControl() | Returns the .control element. Might not exist |
.getControlGroup() | Returns the element which gets the .validation.error classes. Might not exist. |
.getElement() | Gets the DOM element related to the instance. |
.getErrors() | Gets the constructed errors' object. |
.getFormElements() | Gets other elements in the same form. |
.getLabel() | Gets this FormElement's display label, as passed to the error messages. |
.getValue() | Gets an element's value |
.removeErrors() | Remove error marking and any error paragraphs |
.setRules(rulesStr) | Sets the rules string (just as passed in data-rules) of this FormElement. |
.unforceInvalid() | Undo a forceInvalid() call on this FormElement. |
.unforceValid() | Undo a forceValid() call |
.validate() | Validates the element based on the rules defined. |
element
DOM Elementoptions
Object with configuration optionsoptions.label
Label for this element. It is used in the error message. If not specified, the text in the `label` tag in the control-group is used.options.rules
Rules string to be parsed.options.error
Error message to show in case of erroroptions.autoReparse
Set to `true` to reparse data-rules every time this is submitted.options.form
FormValidator instance.Displays error messages and marks as invalid, if this is invalid.
Forcefully mark this FormElement as invalid. Use unsetInvalid() to remove this forced invalidation.
message
'(generic error string)'] The error message to show.Forcefully mark this FormElement as valid
Returns the .control element. Might not exist
Returns the element which gets the .validation.error classes. Might not exist.
Gets the DOM element related to the instance.
Gets the constructed errors' object.
Gets other elements in the same form.
Gets this FormElement's display label, as passed to the error messages.
Gets an element's value
Remove error marking and any error paragraphs
Sets the rules string (just as passed in data-rules) of this FormElement.
Use this if a form's rules need to be dynamically modified.
rulesStr
String with rulesUndo a forceInvalid() call on this FormElement.
Undo a forceValid() call
Validates the element based on the rules defined.
It parses the rules defined in the _options.rules property.
Validation Functions used in the rules (data-rules) option to FormValidator_2.
This option is a string with a special syntax: function_name|function2_name|...
. Optionally you can pass parameters to these methods using square brackets ([]
)
For instance:
data-rules="required|numeric[.,2]|max_length[8]"
Meaning:
Method name | Description |
---|---|
.alpha(supportSpaces) | Checks if a value only contains alphabetical values. |
.alpha_dash() | Checks if a value contains only alphabetical, dash or underscore characteres. |
.alpha_numeric() | Checks if a value contains only alphabetical or numerical characters. |
.color() | Checks if a value is a valid color. |
.credit_card(cardType) | Checks if a value is a valid credit card. |
.date(format) | Checks if a value is a valid date. |
.decimal(decimalSeparator, [decimalPlaces], [leftDigits]) | Checks if a value is a valid decimal number. |
.digit() | Checks if a value is a single digit. |
.email() | Checks if a value is a valid email address |
.exact_length(exactSize) | Checks if a value has an exact length |
.integer(positive) | Checks if a value is a valid integer. |
.ip(ipType) | Checks if a value is a valid IP. Supports ipv4 and ipv6 |
.matches(fieldToCompare) | Checks if a value matches the value of a different field. |
.max_length(maxSize) | Checks if a value has a maximum length |
.min_length(minSize) | Checks if a value has a minimum length |
.numeric(decimalSeparator, [decimalPlaces], [leftDigits]) | Checks if a value is a numeric value. |
.phone(phoneType) | Checks if a value is a valid phone number. |
.range(minValue, maxValue, [multipleOf]) | Checks if a value is in a specific range of values. |
.required() | Checks if a value is defined and not empty |
.url(fullCheck) | Checks if a value has a valid URL |
Checks if a value only contains alphabetical values.
supportSpaces
Allow whitespaceChecks if a value contains only alphabetical, dash or underscore characteres.
Checks if a value contains only alphabetical or numerical characters.
Checks if a value is a valid color.
Checks if a value is a valid credit card.
cardType
Type of credit card to be validated. The card types available are in the Ink.Util.Validator class.Checks if a value is a valid date.
format
Specific format of the date.Checks if a value is a valid decimal number.
decimalSeparator
Character that splits the integer part from the decimal one. By default is '.'.decimalPlaces
Maximum number of digits that the decimal part must have.leftDigits
Maximum number of digits that the integer part must have, when provided.Checks if a value is a single digit.
Checks if a value is a valid email address
Checks if a value has an exact length
exactSize
Exact number of characters.Checks if a value is a valid integer.
positive
Flag that specifies if the integer is must be positive (unsigned).Checks if a value is a valid IP. Supports ipv4 and ipv6
ipType
Type of IP to be validated. The values are: ipv4, ipv6. By default is ipv4.Checks if a value matches the value of a different field.
fieldToCompare
Name or ID of the field to compare.Checks if a value has a maximum length
maxSize
Maximum number of characters.Checks if a value has a minimum length
minSize
Minimum number of characters.Checks if a value is a numeric value.
decimalSeparator
Checks if it's a valid decimal. Otherwise checks if it's a valid integer.decimalPlaces
Maximum number of digits the decimal part must have.leftDigits
Maximum number of digits the integer part must have, when provided.Checks if a value is a valid phone number.
Supports several countries, based in the Ink.Util.Validator class.
phoneType
Country's initials to specify the type of phone number to be validated. Ex: 'AO'.Checks if a value is in a specific range of values.
The parameters after the first one are used to specify the range, and are similar in function to python's range() function.
minValue
Left limit of the range.maxValue
Right limit of the range.multipleOf
In case you want numbers that are only multiples of another number.Checks if a value is defined and not empty
Checks if a value has a valid URL
fullCheck
Flag to validate a full url (with the protocol).Method name | Description |
---|---|
new FormValidator_2(selector, [options]) | Constructor |
.appendI18n() | Add to the I18n dictionary. |
.getElements() | Searches for the elements in the form. |
.getI18n() | Gets the i18n object in charge of the error messages |
.getI18n() | Get my I18n instance with the validation messages. |
.getLanguage() | Gets the language code string (pt_PT or en_US for example) currently in use by this formvalidator. |
.getRules() | Method used to get the existing defined validation functions |
.setI18n(i18n) | Sets the I18n object for validation error messages |
.setI18n(i18n) | Set my I18n instance with the validation messages. |
.setLanguage(language) | Sets the language of the error messages. |
.setLanguage(language) | Set the language of this form validator to the given language code |
.setRule(name, errorMessage, cb) | Sets or modifies validation functions |
.validate(event) | Validates every registered FormElement |
selector
Either a CSS Selector string, or the form's Elementoptions
Options object, containing the following options:options.lang
Set the language of the error messages. This internally sets the lang of our Ink.Util.I18n instance. pt_PT and en_US are available, but using getI18n().append({ lang_CODE: {...} }) you can create your own language.options.eventTrigger
Event that will trigger the validation. Defaults to 'submit'.options.neverSubmit
Flag to cancel the submit event. Use this to avoid submitting the form.options.searchFor
Selector containing the validation data-attributes. Defaults to 'input, select, textarea, .control-group'.options.beforeValidation
Callback to be executed before validating the form. Takes { validator (this FormValidator), elements (Object containing arrays of FormElement) } as an argument. Use this callback to preemptively mark fields as invalid or valid using forceInvalid or forceValid.options.autoReparse
Set to `true` to reparse data-rules in input elements every time this is submitted.options.extraValidation
Use this callback to perform extra validation on the form. Useful for cross-validation of several fields, for example. Takes { validator (this FormValidator), elements (Object containing arrays of FormElement), errorCount (errors the form had before calling the function) } as an argument, and is called at the end of validate(). Return false to force the form to be invalid. You are responsible for showing any visual feedback to the user for now. This might change later.options.onError
Validation error callbackoptions.onSuccess
Validation success callbackSample validated form. Try to submit it.
Code
Add to the I18n dictionary.
See Ink.Util.I18n.append()
documentation.
Searches for the elements in the form.
This method is based in the this._options.searchFor configuration.
Returns an object mapping names of object to arrays of FormElement instances.
Gets the i18n object in charge of the error messages
Get my I18n instance with the validation messages.
Gets the language code string (pt_PT or en_US for example) currently in use by this formvalidator.
May be global
Method used to get the existing defined validation functions
Sets the I18n object for validation error messages
i18n
The I18n object.Set my I18n instance with the validation messages.
i18n
I18n instanceSets the language of the error messages.
pt_PT and en_US are available, but you can add new languages by using append()
See the Ink.Util.I18n.lang()
setter
language
The language to set i18n to.Set the language of this form validator to the given language code
If we don't have an i18n instance, create one which is a copy of the global one.
language
Language code (ex: en_US, pt_PT)Sets or modifies validation functions
name
Name of the function. E.g. 'required'errorMessage
Error message to be displayed in case of returning false. E.g. 'Oops, you passed {param1} as parameter1, lorem ipsum dolor...'cb
Function to be executed when calling this ruleValidates every registered FormElement
This method looks inside the this._formElements object for validation targets.
Also, based on the this._options.beforeValidation, this._options.onError, and this._options.onSuccess, this callbacks are executed when defined.
event
Window.event object