FormCheck

Performs different tests on forms and indicates errors.

Usage

Works with these types of fields :

  • input (text, radio, checkbox)
  • textarea
  • select

You just need to add a specific class to each fields you want to check.  For example, if you add the class

validate['required','length[4, -1]','differs:email','digit']

the value’s field must be set (required) with a minimum length of four chars (4, -1), must differs of the input named email (differs:email), and must be digit.

You can perform check during the datas entry or on the submit action, shows errors as tips or in a div before or after the field, show errors one by one or all together, show a list of all errors at the top of the form, localize error messages, add new regex check, ...

The layout is design only with css.  Now I added a hack to use transparent png with IE6, so you can use png images in formcheck.css (works only for theme, so the file must be named formcheck.css).  It can also works with multiple forms on a single html page.  The class supports now internationalization.  To use it, simply specify a new <script> element in your html head, like this : <script type=”text/javascript” src=”formcheck/lang/fr.js”></script>.

If you add the class

validate['submit']

to an element like an anchor (or anything else), this element will act as a submit button.

N.B.  : you must load the language script before the formcheck and this method overpass the old way.  You can create new languages following existing ones.  You can otherwise still specifiy the alerts’ strings when you initialize the Class, with options.  If you don’t use a language script, the alert will be displayed in english.

Test type

You can perform various test on fields by adding them to the validate class.  Be careful to not use space chars.  Here is the list of them.

requiredThe field becomes required.  This is a regex, you can change it with class options.
alphaThe value is restricted to alphabetic chars.  This is a regex, you can change it with class options.
alphanumThe value is restricted to alphanumeric characters only.  This is a regex, you can change it with class options.
nodigitThe field doesn’t accept digit chars.  This is a regex, you can change it with class options.
digitThe value is restricted to digit (no floating point number) chars, you can pass two arguments (f.e. digit[21,65]) to limit the number between them.  Use -1 as second argument to set no maximum.
numberThe value is restricted to number, including floating point number.  This is a regex, you can change it with class options.
emailThe value is restricted to valid email.  This is a regex, you can change it with class options.
imageThe value is restricted to images (jpg, jpeg, png, gif, bmp).  This is a regex, you can change it with class options.
phoneThe value is restricted to phone chars.  This is a regex, you can change it with class options.
phone_interThe value is restricted to international phone number.  This is a regex, you can change it with class options.
url:The value is restricted to url.  This is a regex, you can change it with class options.
confirmThe value has to be the same as the specified. f.e. confirm:password.
differsThe value has to be diferent as the one specifies. f.e. differs:user.
lengthThe value length is restricted by argument (f.e. length[6,10]).  Use -1 as second argument to set no maximum.
groupUse to validate several checkboxes as a group.  Requires 2 arguments, the second one being optional (1 by default): the group id and the minimum amount of boxes to check.  The second argument may be set on any or all items of the group.  See example below.
wordsThe words number is limited by arguments. f.e. words[1,13].  Use -1 as second argument to don’t have a max limit.
targetIt’s not really a validation test, but it allows you to attach the error message to an other element, usefull if the input you validate is hidden.  You must specifiy target id, f.e. target:myDiv.

You can also use a custom function to check a field.  For example, if you have a field with class

validate['required','%customCheck']

the function customCheck(el) will be called to validate the field.  ‘%customcheck’ works with other validate(s) together, and ‘~customcheck’ works if the element pass the other validate(s).  Here is an example of what customCheck could look :

function customCheck(el){
    if (!el.value.test(/^[A-Z]/)) {
        el.errors.push("Username should begin with an uppercase letter");
        return false;
    } else {
        return true;
    }
}

To validate checkoxes group, you could make something like :

<input type="checkbox" name="dog" class="validate['group[1,2]']">
<input type="checkbox" name="cat" class="validate['group[1]']">
<input type="checkbox" name="mouse" class="validate['group[1]']">

For checkboxes from group 1, you will need to check at least 2 boxes.

It is now possible to register new fields after a new FormCheck call by using FormCheck::register (see <FormCheck::dispose> too).  You need first to add the validate class to the element you want to register ( $(‘myInput’).addClass(“validate[‘required’]”) ).

Parameters

When you initialize the class with addEvent, you can set some options.  If you want to modify regex, you must do it in a hash, like for display or alert.  You can also add new regex check method by adding the regex and an alert with the same name.

Required

form_idThe id of the formular.  This is required.

Optional

submitIf you turn this option to false, the FormCheck will only perform a validation, without submitting the form, even on success.  You can use validateSuccess event to execute some code.
submitByAjaxyou can set this to true if you want to submit your form with ajax.  You should use provided events to handle the ajax request (see below).  By default it is false.
ajaxResponseDivid of element to inject ajax response into (can also use onAjaxSuccess).  By default it is false.
ajaxEvalScriptsuse evalScripts in the Request response.  Can be true or false, by default it is false.
onAjaxRequestFunction to fire when the Request event starts.
onAjaxCompleteFunction to fire when the Request event completes regardless of and prior to Success or Failure.
onAjaxSuccessFunction to fire when the Request receives . Args: response [the request response] - see Mootools docs for Request.onSuccess.
onAjaxFailureFunction to fire if the Request fails.
onSubmitFunction to fire when form is submited (so before validation)
onValidateSuccessFunction to fire when validation pass (you should prevent form submission with option submit:false to use this)
onValidateFailureFunction to fire when validation fails
tipsClassThe class to apply to tipboxes’ errors.  By default it is ‘fc-tbx’.
errorClassThe class to apply to alertbox (not tips).  By default it is ‘fc-error’.
fieldErrorClassThe class to apply to fields with errors, except for radios.  You should also turn on options.addClassErrorToField.  By default it is ‘fc-field-error’
trimValueIf set to true, strip whitespace (or other characters) from the beginning and end of values.  By default it is false.
validateDisabledIf set to true, disabled input will be validated too, otherwise not.

Display

This is a hash of display settings. in here you can modify.

showErrors0 : onSubmit, 1 : onSubmit & onBlur, by default it is 0.
titlesInsteadNames0 : When you do a check using differs or confirm, it takes the field name for the alert.  If it’s set to 1, it will use the title instead of the name.
errorsLocation1 : tips, 2 : before, 3 : after, by default it is 1.
indicateErrors0 : none, 1 : one by one, 2 : all, by default it is 1.
indicateErrorsInit0 : determine if the form must be checked on initialize.  Could be usefull to force the user to update fields that don’t validate.
keepFocusOnError0 : normal behaviour, 1 : the current field keep the focus as it remain errors.  By default it is 0.
checkValueIfEmpty0 : When you leave a field and you have set the showErrors option to 1, the value is tested only if a value has been set.  1 : The value is tested in any case.  By default it is 1.
addClassErrorToField0 : no class is added to the field, 1 : the options.fieldErrorClass is added to the field with an error (except for radio).  By default it is 0.
removeClassErrorOnTipClosure0 : Error class is kept when the tip is closed, 1 : Error class is removed when the tip is closed
fixPngForIe0 : do nothing, 1 : fix png alpha for IE6 in formcheck.css.  By default it is 1.
replaceTipsEffect0 : No effect on tips replace when we resize the broswer, 1: tween transition on browser resize;
closeTipsButton0 : the close button of the tipbox is hidden, 1 : the close button of the tipbox is visible.  By default it is 1.
flashTips0 : normal behaviour, 1 : the tipbox “flash” (disappear and reappear) if errors remain when the form is submitted.  By default it is 0.
tipsPosition’right’ : the tips box is placed on the right part of the field, ‘left’ to place it on the left part.  By default it is ‘right’.
tipsOffsetXHorizontal position of the tips box (margin-left), , by default it is 100 (px).
tipsOffsetYVertical position of the tips box (margin-bottom), , by default it is -10 (px).
listErrorsAtTopList all errors at the top of the form, , by default it is false.
scrollToFirstSmooth scroll the page to first error and focus on it, by default it is true.
fadeDurationTransition duration (in ms), by default it is 300.

Alerts

This is a hash of alerts settings. in here you can modify strings to localize or wathever else.  %0 and %1 represent the argument.

required”This field is required.”
alpha”This field accepts alphabetic characters only.”
alphanum”This field accepts alphanumeric characters only.”
nodigit”No digits are accepted.”
digit”Please enter a valid integer.”
digitmin”The number must be at least %0”
digitltd”The value must be between %0 and %1”
number”Please enter a valid number.”
email”Please enter a valid email: <br /><span>E.g.  email target=”yourname@domain.com” name=”yourname@domain.com”</span>”
phone”Please enter a valid phone.”
phone_inter”Please enter a valid international phone number.”
url”Please enter a valid url: <br /><span>E.g.  url target=”http://www.domain.com” name=”http://www.domain.com”</span>”
image”This field should only contain image types”
confirm”This field is different from %0”
differs”This value must be different of %0”
length_str”The length is incorrect, it must be between %0 and %1”
length_fix”The length is incorrect, it must be exactly %0 characters”
lengthmax”The length is incorrect, it must be at max %0”
lengthmin”The length is incorrect, it must be at least %0”
words_min”This field must concain at least %0 words, now it has %1 words”
words_range”This field must contain between %0 and %1 words, now it has %2 words”
words_max”This field must contain at max %0 words, now it has %1 words”
checkbox”Please check the box”
checkboxes_group”Please check at least %0 box(es)”
radios”Please select a radio”
select”Please choose a value”

Example

You can initialize a formcheck (no scroll, custom classes and alert) by adding for example this in your html head this code :

<script type="text/javascript">
    window.addEvent('domready', function() {
        var myCheck = new FormCheck('form_id', {
            tipsClass : 'tips_box',
            display : {
                scrollToFirst : false
            },
            alerts : {
                required : 'This field is ablolutely required! Please enter a value'
            }
        })
    });
</script>

About

formcheck.js v.1.6 for mootools v1.203 / 2010

by Mootools.Floor (http://mootools.floor.ch) MIT-style license

Created by Luca Pillonel (luca-at-nolocation.org), Last modified by Luca Pillonel

Credits

This class was inspired by fValidator by Fabio Zendhi Nagao (http://zend.lojcomm.com.br)

Thanks to all contributors from groups.google.com/group/moofloor (and others as well!) providing ideas, translations, fixes and motivation!

Summary
FormCheckPerforms different tests on forms and indicates errors.
Functions
initializeConstructor
registerAllows you to declare afterward new fields to the formcheck, to check dynamically loaded fields for example.
disposeAllows you to remove a declared field from formCheck
addListenerPrivate method
manageErrorPrivate method
validatePrivate method
simpleValidatePrivate method
validateRegexPrivate method
validateConfirmPrivate method
validateDiffersPrivate method
validateWordsPrivate method
isFormValidpublic method
isChildTypePrivate method
validateGroupPrivate method
listErrorsAtTopPrivate method
addErrorPrivate method
addPositionEventUpdate tips position after a browser resize
removeErrorPrivate method
focusOnErrorPrivate method
fixIeStuffsPrivate method
makeTipsPrivate method
reinitializeReinitialize form before submit check.
submitByAjaxPrivate method
onSubmitPrivate method

Functions

initialize

initialize : function(form,
options)

Constructor

Add event on formular and perform some stuff, you now, like settings, ...

register

register : function(el,
position)

Allows you to declare afterward new fields to the formcheck, to check dynamically loaded fields for example.  By default it will be the last element to be validated as it’s added after others inputs, but you can define a position with second parameter.

Example

<script type="text/javascript">
    window.addEvent('domready', function() {
        formcheck = new FormCheck('form_id');
    });

    // ...some code...

    var newField = new Element('input', {
        class   : "validate['required']",
        name    : "new-field"
    }).inject('form_id');
    formcheck.register(newField, 3);

    new Element('input', {
        class   : "validate['required']",
        name    : "another-field",
        id      : "another-field"
    }).inject('form_id');
    formcheck.register($('another-field'));
</script>

See also

FormCheck::dispose

dispose

dispose : function(element)

Allows you to remove a declared field from formCheck

Example

<script type="text/javascript">
    window.addEvent('domready', function() {
        formcheck = new FormCheck('form_id');
    });

    // ...some code...

    formcheck.dispose($('obsolete-field'));
</script>

See also

FormCheck::register

addListener

addListener : function(el)

Private method

Add listener on fields

manageError

manageError : function(el,
method)

Private method

Manage display of errors boxes

validate

validate : function(el)

Private method

Dispatch check to other methods

simpleValidate

simpleValidate : function(el)

Private method

Perform simple check for select fields and checkboxes

validateRegex

validateRegex : function(el,
ruleMethod,
ruleArgs)

Private method

Perform regex validations

validateConfirm

validateConfirm: function(el,
ruleArgs)

Private method

Perform confirm validations

validateDiffers

validateDiffers: function(el,
ruleArgs)

Private method

Perform differs validations

validateWords

validateWords: function(el,
ruleArgs)

Private method

Perform word count validation

isFormValid

isFormValid: function()

public method

Determine if the form is valid

Return true or false

isChildType

isChildType: function(el,
validators)

Private method

Determine if the field is a group of radio, of checkboxes or not.

validateGroup

validateGroup : function(el)

Private method

Perform radios validations

listErrorsAtTop

listErrorsAtTop : function(obj)

Private method

Display errors

addError

addError : function(obj)

Private method

Add error message

addPositionEvent

addPositionEvent : function(obj)

Update tips position after a browser resize

removeError

removeError : function(obj,
method)

Private method

Remove the error display

focusOnError

focusOnError : function (obj)

Private method

Create set the focus to the first field with an error if needed

fixIeStuffs

fixIeStuffs : function ()

Private method

Fix png for IE6

makeTips

makeTips : function(txt)

Private method

Create tips boxes

reinitialize

reinitialize: function(forced)

Reinitialize form before submit check.  You can use this also to remove all tips from a form, passing the argument “forced” ( formcheck.reinitialize(‘forced’); )

submitByAjax

submitByAjax: function()

Private method

Send the form by ajax, and replace the form with response

onSubmit

onSubmit: function(event)

Private method

Perform check on submit action

initialize : function(form,
options)
Constructor
register : function(el,
position)
Allows you to declare afterward new fields to the formcheck, to check dynamically loaded fields for example.
dispose : function(element)
Allows you to remove a declared field from formCheck
addListener : function(el)
Private method
manageError : function(el,
method)
Private method
validate : function(el)
Private method
simpleValidate : function(el)
Private method
validateRegex : function(el,
ruleMethod,
ruleArgs)
Private method
validateConfirm: function(el,
ruleArgs)
Private method
validateDiffers: function(el,
ruleArgs)
Private method
validateWords: function(el,
ruleArgs)
Private method
isFormValid: function()
public method
isChildType: function(el,
validators)
Private method
validateGroup : function(el)
Private method
listErrorsAtTop : function(obj)
Private method
addError : function(obj)
Private method
addPositionEvent : function(obj)
Update tips position after a browser resize
removeError : function(obj,
method)
Private method
focusOnError : function (obj)
Private method
fixIeStuffs : function ()
Private method
makeTips : function(txt)
Private method
reinitialize: function(forced)
Reinitialize form before submit check.
submitByAjax: function()
Private method
onSubmit: function(event)
Private method