Simple form validation / submission jQuery plugin
Demo
Installation
npm i ssd-form
Set up
Please select your title Selected value must be Mr Select title Mr Mrs Miss Ms Please provide your first name Length must be at least 3 characters Validation triggered by ajax response Please provide your last name Length must be at least 3 characters Please provide your email address Invalid email address Please choose your password Length must be at least 6 characters, one capital letter and one number Passwords do not match Please confirm your password Length must be at least 5 characters Please select delivery option You must select one option Option 1 Option 2 Option 3 You must agree to our newsletter and conditions At least one option must be selected You must select at least one option Option 1 Option 2 Option 3 Exactly one option must be selected You must select exactly one option You must select exactly one option Option 1 Option 2 Option 3 I agree to the terms and conditions PROCESSING
Include the necessary styles for the plugin to work
To instantiate the form simply call it on the form
;
Options
There are several options available
// form wrapper
dataFormWrapper: 'data-form-wrapper',
// confirmation element (if form behaviour shows confirmation)
dataConfirmation: 'data-confirmation',
// validation segment (wraps validation cases)
dataValidationSegment: 'data-validation',
// validation case (wraps each validation message for a given form element)
dataValidationCase: 'data-case',
// submit button
dataSubmitTrigger: 'data-submit-trigger',
// button that is shown when the form is being submitted (pending)
dataSubmitPending: 'data-submit-pending',
// class indicating that the given input's value
// is to be fetched from CKEDITOR.instances
classCkEditor: 'editor',
// class that hides pending button
classHide: 'hide',
// class that shows validation case
classShow: 'show',
// allows you to add more behaviours
extendBehaviours: {},
// allows you to add more validation rules
extendValidationRules: {}
// allows you to run custom behaviour on successful ajax response
postAjaxSuccess: function(form, form_model, data) {}
// allows you to run custom behaviour on failed ajax response
postAjaxFailure: function(form, form_model, jqXHR, textStatus, errorThrown) {}
// allows you to specify which attributes should be used
// during data serialization instead of default 'name' attribute
// example would be for instance 'data-field'
serializeAttribute: null,
// action that overwrites default behaviour
// of the validated form submission
// default one submits form using $.ajax()
// and form 'method' and 'action' attributes
actionMethod: function(form, form_model, success, error) {}
Validation
To apply validation to a given element, apply data-validate
attribute to it with the validation type. i.e.
data-validate="required|min:3"
Validation options
required
: input must have a valuechecked
: input must be checkedradio
: input of typeradio
must have one option selectedvalue_is:n
: input value must equaln
(value:10
would mean that value must equal 10)email
: input value must be a valid email address - regex /^[a-zA-Z0-9._-]+@[a-zA-Z0-9]+([.-]?[a-zA-Z0-9]+)?([.]{1}[a-zA-Z]{2,4}){1,4}$/password
: input value must match the following regex/(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/
min:n
: input value's length must be minimum ofn
characters (or for array types - number of items in array). i.e.min:10
would mean that the value has to be at least 10 characters long / array has to have at least 10 itemsmax:n
: input value's length must be maximum ofn
characters (or for array types - number of items in array). i.e.max:10
would mean that the value has to be maximum 10 characters long / array must not have more than 10 itemsconfirmed
: input must have a matching input with the same name and_confirmation
appended and both have to have the same value i.epassword
andpassword_confirmation
regex
: input must match the regex associated withdata-regex
Form submission
Form will submit the input to the uri associated with its action
attribute.
If response is to return any errors it should return them as json in the following format:
Response keys represent the field (associated with data-validation
) and value (or array of values) representing given case (associated with data-case
).
Please note that if returned validation field contains array of cases, then only the first one will be displayed above the field.
For the validation to work, the response needs to return status code that would trigger error
callback of the $.ajax() method - for instance 422
(please see example in submit.php).
Successful behaviour
Once the form has been processed successfully it will trigger one of the following methods, associated with the data-success-behaviour
attribute:
redirect
: redirects to a given url/i. Response needs to containredirect
entry{ "redirect" : "/confirmation" }
reload
: reloads the pagefadeOutShowMessage
: fades out the form and displays the message in its place. Response has to containmessage
entry{ "message" : "Your request has been processed successfully." }
fadeOutShowMessageRedirect
: fades out the form, displays the message and after 3 seconds redirects to a given url/i. Response needs to containmessage
andredirect
entry{ "message" : "Your request has been processed successfully.", "redirect" : "/confirmation" }
fadeOutShowMessageReload
: fades out the form, displays the message and after 3 seconds reloads the page. Response needs to containmessage
entry { "message" : "Your request has been processed successfully." }`fadeOutShowMessageResetFadeIn
: fades out the form, displays the message, resets the form and fades it back in. Response needs to containmessage
entry{ "message" : "Your request has been processed successfully." }
callReplaceRemove
: makes ajax call and replaces and removes elements specified in the response.
Extending validation rules and form behaviours
If you'd like to add more validation rules, use the extendValidationRules
option, which will extend the internal ValidationRules
object. Each new method takes the element
argument. element.rules_collection
represents any value that's after the rules colon i.e. min:5
would return 5
, something:5,6,7
would return 5,6,7
:
; <input type="text" name="year" id="year" data-validate="required|number_is:2016" placeholder="Provide current year">
Other options available on the element
object:
// name attribute
name,
// type attribute
type,
// value of the input
value,
// validation rules associated with the data-validate attribute
rules: obj.data('validate'),
// returns true if element name is of the array type
// i.e. name="category[]"
isArray,
// returns true if checkbox / radio button is checked
isChecked,
// returns true if given input is visible / not hidden
isVisible,
// returns true if given input has class 'editor' associated with it
// this option is useful if you're using wysiwyg editor etc.
isEditor,
// returns associated regex rule
regex
For behaviours you do the same with extendBehaviours
option, methods which take two arguments form
(instance of the FormModel
object) and data
(ajax json response):
; <form method="post" action="./submit.php" data-ajax-form data-success-behaviour="alertMessage" novalidate>...</form>
Custom serialize attribute
There might be some situations where you might want to use different attribute on your form fields to represent the identity of your input than the default name
.
This might be useful in situations where you might be sending request to the external service over the ssl and don't want your server to receive any data when the form is submitted.
You can specify what field attribute should be used by overwriting the serializeAttribute
property.
$('form[data-ajax-form]').ssdForm({ serializeAttribute: 'data-field' });
Custom action
If you'd like to perform custom action once the form has been successfully validated, you can overwrite the default one by using the actionMethod
property. This property is of a function type and takes 4 arguments.
form
: instance of the main Form objectform_model
: instance of the FormModelsuccess
: default success callbackerror
: default error callback
;
CKEDITOR field
To fetch data from the CKEDITOR instance, please use the classCkEditor
config option to specify what css class is representing input associated with te CKEDITOR instance. Input also has to have associated id
attribute. You will have to bind CKEDITOR instance with the input yourself, but form will fetch the correct data on submit.
$('form[data-ajax-form]').ssdForm({ classCkEditor: 'ckeditor' });