All samples are using Ink.requireModules, please read how to use it at Ink.requireModules section

FormValidator.FormElement class

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.

Methods
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.

new FormValidator.FormElement(element, options)

Accepts

  • element

    DOM Element
  • options

    Object with configuration options
  • options.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 error
  • options.autoReparse

    Set to `true` to reparse data-rules every time this is submitted.
  • options.form

    FormValidator instance.

.displayErrors() method

Displays error messages and marks as invalid, if this is invalid.

.forceInvalid([message]) method

Forcefully mark this FormElement as invalid. Use unsetInvalid() to remove this forced invalidation.

Accepts

  • message

    '(generic error string)'] The error message to show.

.forceValid() method

Forcefully mark this FormElement as valid

.getControl() method

Returns the .control element. Might not exist

.getControlGroup() method

Returns the element which gets the .validation.error classes. Might not exist.

.getElement() method

Gets the DOM element related to the instance.

.getErrors() method

Gets the constructed errors' object.

.getFormElements() method

Gets other elements in the same form.

.getLabel() method

Gets this FormElement's display label, as passed to the error messages.

.getValue() method

Gets an element's value

.removeErrors() method

Remove error marking and any error paragraphs

.setRules(rulesStr) method

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.

Accepts

  • rulesStr

    String with rules

.unforceInvalid() method

Undo a forceInvalid() call on this FormElement.

.unforceValid() method

Undo a forceValid() call

.validate() method

Validates the element based on the rules defined.
It parses the rules defined in the _options.rules property.

FormValidator.validationFunctions namespace

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:

  • Required field;
  • Number in which the decimal separator is a dot (.) and has at most 2 decimal places;
  • Field with at most 8 characters;
Methods
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

.alpha(supportSpaces) method

Checks if a value only contains alphabetical values.

Accepts

  • supportSpaces

    Allow whitespace

.alpha_dash() method

Checks if a value contains only alphabetical, dash or underscore characteres.

.alpha_numeric() method

Checks if a value contains only alphabetical or numerical characters.

.color() method

Checks if a value is a valid color.

.credit_card(cardType) method

Checks if a value is a valid credit card.

Accepts

  • cardType

    Type of credit card to be validated. The card types available are in the Ink.Util.Validator class.

.date(format) method

Checks if a value is a valid date.

Accepts

  • format

    Specific format of the date.

.decimal(decimalSeparator, [decimalPlaces], [leftDigits]) method

Checks if a value is a valid decimal number.

Accepts

  • 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.

.digit() method

Checks if a value is a single digit.

.email() method

Checks if a value is a valid email address

.exact_length(exactSize) method

Checks if a value has an exact length

Accepts

  • exactSize

    Exact number of characters.

.integer(positive) method

Checks if a value is a valid integer.

Accepts

  • positive

    Flag that specifies if the integer is must be positive (unsigned).

.ip(ipType) method

Checks if a value is a valid IP. Supports ipv4 and ipv6

Accepts

  • ipType

    Type of IP to be validated. The values are: ipv4, ipv6. By default is ipv4.

.matches(fieldToCompare) method

Checks if a value matches the value of a different field.

Accepts

  • fieldToCompare

    Name or ID of the field to compare.

.max_length(maxSize) method

Checks if a value has a maximum length

Accepts

  • maxSize

    Maximum number of characters.

.min_length(minSize) method

Checks if a value has a minimum length

Accepts

  • minSize

    Minimum number of characters.

.numeric(decimalSeparator, [decimalPlaces], [leftDigits]) method

Checks if a value is a numeric value.

Accepts

  • 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.

.phone(phoneType) method

Checks if a value is a valid phone number.
Supports several countries, based in the Ink.Util.Validator class.

Accepts

  • phoneType

    Country's initials to specify the type of phone number to be validated. Ex: 'AO'.

.range(minValue, maxValue, [multipleOf]) method

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.

Accepts

  • 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.

.required() method

Checks if a value is defined and not empty

.url(fullCheck) method

Checks if a value has a valid URL

Accepts

  • fullCheck

    Flag to validate a full url (with the protocol).

FormValidator_2 class

Methods
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

new FormValidator_2(selector, [options])

Accepts

  • selector

    Either a CSS Selector string, or the form's Element
  • options

    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 callback
  • options.onSuccess

    Validation success callback

Sample validated form. Try to submit it.

Please select one option

Code

<form id="my-form" class="ink-form" method="post" action="#">
    <fieldset>
        <div class="control-group required">
            <label for="name">Name:</label>
            <div class="control">
                <input type="text" data-rules="required|text[true,false]" name="name" id="name" />
            </div>
        </div>

        <div class="control-group required">
            <label for="ip">IP address:</label>
            <div class="control">
                <input type="text" data-rules="required|ip" name="ip" id="ip" />
            </div>
        </div>

        <div class="control-group required">
            <label for="mail">Email:</label>
            <div class="control">
                <input type="text" name="mail" id="mail" data-rules="required|email" />
            </div>
        </div>

        <div class="control-group required">
            <label for="pass">Password: </label>
            <div class="control">
                <input type="password" name="pass" id="pass" data-rules="required|min_length[8]" />
            </div>
        </div>

        <div class="control-group required">
            <label for="confpass">Confirm Password:</label>
            <div class="control">
                <input type="password" name="confpass" id="confpass" data-rules="matches[pass]" />
            </div>
        </div>

        <div class="control-group required">
            <label for="number">A number between -1.23 and 2.25 with at most 2 decimal points!</label>
            <div class="control">
                <input type="text" name="number" id="number" data-rules="required|numeric[.,2]|range[-1.23,2.25]" />
            </div>
        </div>

        <div class="control-group required">
            <label for="creditcard">Credit card</label>
            <div class="control">
                <input type="text" name="creditcard" id="creditcard" data-rules="credit_card" />
            </div>
        </div>

        <div class="control-group required" data-rules="atLeastOne">
            <p class="label">Please select one option</p>
            <ul class="control unstyled">
                <li>
                    <input type="radio" name="radio1" id="radio1_g" value="1"/>
                    <label for="radio1_g">radio 1</label>
                </li>
                <li>
                    <input type="radio" name="radio1" id="radio2_g" value="2"/>
                    <label for="radio2_g">radio 2</label>
                </li>
                <li>
                    <input type="radio" name="radio1" id="radio3_g" value="3"/>
                    <label for="radio3_g">radio 3</label>
                </li>
            </ul>
        </div>
    </fieldset>
    <div>
        <input type="submit" name="sub" value="Submit" class="ink-button success" />
    </div>
</form>

<script>
Ink.requireModules( ['Ink.UI.FormValidator_2', 'Ink.Dom.Selector_1'], function( FormValidator, Selector ){
    FormValidator.setRule('atLeastOne', 'Select at least one of the radio options', function( value ){
        return !!Selector.select('input[type="radio"]:checked',this.getElement()).length;
    });
    var myValidator = new FormValidator( '#my-form' );
});
</script>

.appendI18n() method

Add to the I18n dictionary.
See Ink.Util.I18n.append() documentation.

.getElements() method

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.

.getI18n() method

Gets the i18n object in charge of the error messages

.getI18n() method

Get my I18n instance with the validation messages.

.getLanguage() method

Gets the language code string (pt_PT or en_US for example) currently in use by this formvalidator.
May be global

.getRules() method

Method used to get the existing defined validation functions

.setI18n(i18n) method

Sets the I18n object for validation error messages

Accepts

  • i18n

    The I18n object.

.setI18n(i18n) method

Set my I18n instance with the validation messages.

Accepts

  • i18n

    I18n instance

.setLanguage(language) method

Sets 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

Accepts

  • language

    The language to set i18n to.

.setLanguage(language) method

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.

Accepts

  • language

    Language code (ex: en_US, pt_PT)

.setRule(name, errorMessage, cb) method

Sets or modifies validation functions

Accepts

  • 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 rule

.validate(event) method

Validates 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.

Accepts

  • event

    Window.event object