Webshim's forms
feature implements the hole constraint validation API (validity, checkValidity, setCustomValidity, required, pattern, novalidate ...) and some other really nice form features (output and progress element, form-attribute, fieldset[disabled] [list]/datalist, setSelectionRange etc.) in incapable browsers.
This document does not describe how to use those native/polyfilled features. It only describes the extensions build on top of it.
Changes to the locale settings normally only affect polyfilled browsers. To get those changes visible in capable browsers either the replaceValidationUI
or the iVal
(instant/live validation) feature should be used.
webshim.activeLang
The used locale settings can be read or changed using the webshim.activeLang
method.
webshim.activeLang(); //returns current set language
webshim.activeLang('en'); //set locale to en
Webshim supports the following locales out of the box: .
Existing locale setting files can be found in the shims/i18n directory. Simply take one of those files (save as new), embed it after the polyfiller.js and adjust it to your needs.
Note: webshim.activeLang
with the corresponding language code has to be called to activate the locale
//locale definition with the locale code 'cd'
webshim.validityMessages.cd = {
//your errormessages
};
webshim.formcfg.cd = {
//locale settings
};
//activate locale 'cd'
webshim.activeLang('cd');
customMessages
/lazyCustomMessages
Normally the validationMessages are only loaded by incapable browsers with the options customMessages
or lazyCustomMessages
those can be loaded and used in all browsers.
lazyCustomMessages
loads the messages only after window onload and therefore has no negative impact on the network performance.
webshim.setOptions('forms', {
//set lazyCustomMessages to true
lazyCustomMessages: true,
//show custom styleable validation bubble
replaceValidationUI: true
});
//start polyfilling
webshim.polyfill('forms');
data-errormessage
attributeThe used validation message can also be controlled by markup using the data-errormessage
attribute.
The value of the data-errormessage attribute is either a simple string containing the errormessage or a valid JSON with different keys representing the different HTML5 validity constraints (["valueMissing", "typeMismatch", "patternMismatch", "customError", "tooLong", "badInput", "rangeUnderflow", "rangeOverflow","stepMismatch"]
)
In case customMessages
or lazyCustomMessages
are set to true the data-errormessage as a JSON can be also written as flattened data-errormessage-[dashed-key] attribute.
$.getErrorMessage
method.getErrorMessage
returns the validationMessage of an invalid form field. As an enhancement to the native validationMessage
property the return value can be simpler controlled by the developer. It uses the first possible found message set by a) data-errormessage attribute, b) validityMessages
object or last c) native/polyfilled validationMessage
property.
$('input').getErrorMessage();
HTML5 constraint form validation implements a very simple UI for form validation. In most cases developers want to enhance this UI. Webshim implementation allows this by using all native form features (noValidate
or preventing default behavior of the invalid
event), but also gives some pre-build configuration options to implement form validation with a very good user experience and great control over style and behavior.
replaceValidationUI
and .user-error
/.user-success
With replaceValidationUI
set to true the validation bubble of the browser will be replaced with a webshims popover with the additional class validity-alert
. Additionally all form fields can be styled using the classes .user-error
and .user-success
iVal
The instant form validation (iVal
= instant validation) feature of webshims is a simple to use but powerfull and UX enhanced feature. Simply put a ws-validate
class to your form element:
The instant validation feature can be controlled through the iVal
option object. The iVal
option has the following defaults.
webshim.setOptions('forms', {
//instant validation options
iVal: {
//a simple selector of your form element[s]
"sel": ".ws-validate",
//wether webshim should show a bubble on invalid event: "hide" | true | false
"handleBubble": "hide",
//selector or function to find the wrapper of the form field[s] (if there are more than one form field in the wrapper they will be handled as a group with one combined errormessage)
"fieldWrapper": ":not(span):not(label):not(em):not(strong):not(p)",
//wether an invalid input should be re-checked while user types
"recheckDelay": 400,
//in case a developer has set novalidate attribute to a form element and wants the form validated on submit, this should be set to true
"submitCheck": false,
//Events to check for validity/update validation UI
"events": "focusout change", //Note: The 'invalid' and 'updatevalidation' events will be always used
//the class of the errorbox, which is normally appended to the fieldWrapper
"errorBoxClass": "ws-errorbox",
//the html tag used for error boxes, to adjust to your page structure / semantics
"errorBoxWrapper": "div",
//the html tag used for messages in error boxes, to adjust to your page structure / semantics
"errorMessageWrapper": "p",
//classes to adjust to your CSS/CSS-framework
"errorMessageClass": "ws-errormessage",
"errorWrapperClass": "ws-invalid",
"successWrapperClass": "ws-success",
//show/hide effect: 'no' | 'slide' | 'fade'
"fx": "slide"
}
});
//start polyfilling
webshim.polyfill('forms');
The iVal feature integrates well into different CSS-frameworks like bootstrap or jQuery mobile:
iVal.fieldWrapper
optioniVal.fieldWrapper
defines a selector, which matches the closest ancestor element to a form field and gets the classes ws-invalid
(iVal.errorWrapperClass
) or ws-success
(iVal.successWrapperClass
).
iVal.fieldWrapper
can be used to group multiple form fields to one "validation group" with one errormessage (i.e.: radio buttons or separated telephone fields) or to control the placement of errormessages.
Grouping multiple form fields to one validation group can be achieved with the following code:
iVal.fieldWrapper
in conjunction with iVal.errorBoxClass
(ws-errorbox
) can be also used to place the errormessages.
Normally the ws-errorbox
is automatically created and appended to the fieldWrapper
. If a ws-errorbox
already exists inside of fieldWrapper
or is associated with a fieldWrapper
using the data-errorbox
attribute this ws-errorbox
is used.
Among other ways to control errormessages. Forms matching the iVal.sel
can have a more descriptive way to define errormessages. Simply by adding one or more child elements to ws-errorbox
. The data-errortype
can be used to switch between the different error types. The value of the data-errortype
attribute is case-sensitive. All standard validity
properties als can be written as dashed classes (i.e.: .value-missing is treated as [data-errortype="valueMissing"]).
In case a value was changed, through script the validation UI can be updated by triggering the updatevalidation
on the given element:
$('input.foo').val('bar').trigger('updatevalidation');
Often a developer wants to only update the validation UI, if the field already was marked as invalid or valid. This can be done by the following code:
$('input.foo').val('bar').trigger('refreshvalidationui');
The UI can be reseted by triggering the resetvalidation
event on the input or the form element.
There are 3 ways to add/use custom validation constraints with HTML5.
addValidators
Webshim Lib comes with a simple custom validity helper and some predefined typical validation constraints. To turn this feature on, simply set addValidators
to true:
webshim.setOptions('forms', { addValidators: true });
luhn
All elements with a data-luhn
should have a valid credit card number following the Luhn algorithm.
<input data-luhn="" />
grouprequired
If a checkbox has an attribute data-grouprequired
at least one of the checkboxes with the same name inside the form has to be checked.
<input data-grouprequired="" name="a" type="checkbox" />
<input name="a" type="checkbox" />
dependent
Dependent validation dynamically changes the validation constraints depending on another elements value or other property.
The attribute data-dependent-validation
either takes an IDREF or a JSON-String with the dependency options.
The options are as follows:
Examples:
ajaxvalidate
An input with the attribute data-ajaxvalidate
referencing a validation service will start an AJAX validation.
<input data-ajaxvalidate="path-to-validation-service.js" />
The response has to be a valid JSON or JSON-P either with the key valid
or the key message
Valid response:
{"valid": true}
Invalid response:
{"valid": false}
Valid response providing the message:
{"message": ""}
Invalid response:
{"message": "Something wrong"}
In a lot of cases the validity of one input's value, depends on other entered values. In those cases the data-ajaxvalidate
attribute can take a valid JSON string with the keys url
and depends
. The depends
value is either an array or a whitespace separated list of ids or names of the related form fields.
<input data-ajaxvalidate='{
"url": "path-to-validation-service.js",
"depends": "field-a field-b"
}' />
The customError helper hook into the descriptive ways to define errormessage in webshim. Therefore the data-errormessage
attribute and in case of the iVal feature the data-errortype
can be used to define errormessages for the field.
For a more general way the JS API can be used to change the errormessage for the given type:
While webshim allows the developer to use the native or polyfilled setCustomValidity
method to add custom errors. Webshims provides two additional ways to add new constraints:
validatevalue
eventThe non-bubbling validatevalue
event is the preferred way to add new custom constraints and is an easy to use API. Simply listen to the event and return a truthy
value, if the form control does not satisfy the constraint. If the value is a string, this will be the errormessage.
To get the value
/valueAsDate
for the given form control, do not use .val()
, but use the provided extra event parameter.
$('.only-foo').on('validatevalue', function(e, extra){
if(extra.value != 'foo'){
return 'Please enter foo.';
}
});
The validatevalue
event is also called while building input widgets like a datepicker:
webshims also exposes the custom error helper to generate new custom constraints
In case a script changes a value custom constraints might need to be updated. This can be done either with the updatevalidation
or updatecustomvalidity
event.
$('input.foo').val('bar').trigger('updatecustomvalidity');
While the updatecustomvalidity
event will update all custom rules on the target element, the updatevalidation
event additionally also updates the validation UI.
The datalist element can be used to create autocomplete/combobox widgets. With the customDatalist
option the UI can be even replaced in supporting browsers to have more control over this widget.
webshim.setOptions('forms', {
customDatalist: 'auto' // default: false || true || set to 'auto' to only replace in non-mobile browsers.
});
webshim.setOptions("forms", {
list: {
// how should the options be filtered * = wildcard | ^ = beginning | ! = no filter
"filter": "*",
// whether multiple values can be entered separated with a ","
"multiple": false,
// opens the datalist on focus
"focus": false,
// highlights matching parts in the datalist
"highlight": false,
// inline first found value with a selection range while user types
"valueCompletion": false,
// inline value while user navigates inside the datalist using cursor up/cursor down
"inlineValue": false,
// normally HTML will be escaped
"noHtmlEscape": false,
// popover options
"popover": {
"constrainWidth": true
}
}
});
The list option can be also controlled by markup using either data-list attribute with a JSON string or dashed data-list-property-name attributes.
<input data-list='{"multiple": true, "valueCompletion": true}' list="datalist" />
<!-- or --/>
<input data-list-multiple="true" data-list-value-completion="true" list="datalist" />
See also the datalist configurator to play with the widget.