Overview

A form validation class based on formvalidation.io.
Note: The parent element of the validation item must have the fv-row CSS class to display error messages.

Reference

Instance Methods
Name Description
public constructor() Create a new instance of the FormValidation class.
Parameters:
  • form: string|HTMLFormElement|JQuery
    HTMLFormElement selector, element, or JQuery object.
  • fields: FormValidation.core.FieldsOptions
    Validate Options.
  • enableSubmitTrigger: boolean
    If true, validation is performed when the submit button is pressed. Default is true.
  • enableSequence: boolean
    If true, if the validation fails, the remaining validators will not be run. Default is true.
  • shouldFocus: boolean
    If true, focus on the first element of the form. Default is true.
                    import {components} from 'metronic-extension';

// Initialize form validation.
const validation = new components.Validation(document.getElementById('myForm'), {
  firstName: {
    validators: {
      notEmpty: {message: 'First name is required.'},
    }
  },
  lastName: {
    validators: {
      notEmpty: {message: 'Last name is required.'},
    }
  },
});
                  
public validate() Validate all fields. If it is valid, it returns true, if invalid, it returns false.
Return:
  • Promise<boolean> true if the validation passes, false if it fails.
                    await validation.validate();
                  
public onValid() Sets the callback function to be called when all fields pass validation.
Parameters:
  • handler: (event: any) => void
    Callback function.
Return:
  • Validation
                    validation.onValid(async event => {});
                  
public onInvalid() Sets the callback function to be called when the validation fails.
Parameters:
  • handler: (event: any) => void
    Callback function.
Return:
  • Validation
                    validation.onInvalid(async event => {});
                  
public onFieldValid() Sets the callback function to be called when the field passes validation. The callback function will receive the name of the field that passed validation.
Parameters:
  • handler: (name: string) => void
    Callback function.
Return:
  • Validation
                    validation.onFieldValid(name => {});
                  
public onFieldInvalid() Sets the callback function to be called when the field fails validation. The callback function will receive the name of the field that failed validation.
Parameters:
  • handler: (name: string) => void
    Callback function.
Return:
  • Validation
                    validation.onFieldInvalid(name => {});
                  
public onIndicator() Display the loader on the form.
Return:
  • Validation
                    validation.onIndicator();
                  
public offIndicator() Release the form loader.
Return:
  • Validation
                    validation.offIndicator();
                  
public setError() Displays validation error messages for the specified fields.
Parameters:
  • field: string
    The name attribute of the field.
  • validator: string
    The name of the validation rule.
Return:
  • Validation
                    validation.setError('firstName', 'notEmpty');
                  
public enableValidator() Activates the validator rules for the field.
Parameters:
  • field: string
    The name attribute of the field.
  • validator?: string
    The name of the validation rule. The default is none (undefined). If none, all validator rules are active.
Return:
  • Validation
                    // Activate all validator rules.
validation.enableValidator('firstName');

// Activate only mandatory check validator rules.
validation.enableValidator('firstName', 'notEmpty');
                  
public disableValidator() Deactivates the validator rule for the field.
Parameters:
  • field: string
    The name attribute of the field.
  • validator?: string
    The name of the validation rule. Default is none (undefined). If none, all validator rules are deactivated.
Return:
  • Validation
                    // Deactivate all validator rules.
validation.disableValidator('firstName');

// Deactivate only mandatory check validator rules.
validation.disableValidator('firstName', 'notEmpty');
                  
public validateField() Validate a specific field.
Parameters:
  • field: string
    The name attribute of the field.
Return:
  • Promise<boolean> true if the validation passes, false if it fails.
                    await validation.validateField('firstName');
                  
public resetField() Clears error messages in the field.
Parameters:
  • field: string
    The name attribute of the field.
  • reset: boolean
    If true, clears the input value of the field. Default is false.
Return:
  • Validation
                    // Clear error message.
validation.resetField('firstName');

// Clear error messages and input values.
validation.resetField('firstName', true);
                  
public resetForm() Clears error messages for all fields.
Parameters:
  • reset: boolean
    If true, clears the input value of the field. Default is false.
Return:
  • Validation
                    // Clear error messages for all fields.
validation.resetForm();

// Clear error messages and input values for all fields.
validation.resetForm(true);
                  
public addField() Adds a validator rule to the specified field.
Parameters:
  • field: string
    The name attribute of the field.
  • validators: {[validatorName: string]: FormValidation.core.ValidatorOptions}
    Validate Rule.
Return:
  • Validation
                    validation.addField(`firstName`, {
  notEmpty: {message: 'First name is required.'},
});
                  
public getFields() Get validate options for all fields.
Return:
  • FormValidation.core.FieldsOptions Validate Option.
public removeField() Remove fields from validation.
Parameters:
  • field: string
    The name attribute of the field.
Return:
  • Validation
public removeAllField() Remove all fields from validation.
public addRule() Add a new validation rule.
Parameters:
  • validator: string
    The name of the validation rule.
  • func: () => FormValidation.core.ValidateFunction<FormValidation.core.ValidateOptions>
    Validate function.
Return:
  • Validation
                    
// Add the Validate rule.
validation.addRule(`isNumber`, () => {
  return {
    validate: input => {
      return {valid: !isNaN(input.value)};
    }
  }
});

// Add a validator rule with options.
validation.addRule(`isNumber`, () => {
  return {
    validate: input => {
      // Check if it is numeric.
      const valid = isNaN(input.value);
      if (!valid || input.options.allowNegative)
         // If negative numbers are allowed, return the result of the check.
         return {valid};

      // If negative numbers are not allowed, return pass only if greater than or equal to 0.
      return {valid: input.value > 0};
    }
  }
});
                  
public destroy() Destroy validation.
Instance Properties
Name Description
public form: HTMLFormElement Form Elements.
public submit: HTMLButtonElement|null A submit button element.
public fv: FormValidation.core.Core FormValidation instance.

Validators

Check the default validation here.
Below is a custom validation we have added specifically for this package.
Validator Description
isFQDN() Check if the domain name is fully qualified (e.g. domain.com).
Options:
  • requireFQDNTld: boolean If true, the TLD is required. Default is true.
  • allowFQDNWildcard: boolean If true, the validator will allow domain starting with `*.` (e.g. `*.example.com` or `*.shop.example.com`). Default is false.
isFQDNorIP() Check for a fully qualified domain name (e.g. domain.com) or IP (version 4 or 6).
Options:
  • requireFQDNTld: boolean If true, the TLD is required. Default is true.
  • allowFQDNWildcard: boolean If true, the validator will allow domain starting with `*.` (e.g. `*.example.com` or `*.shop.example.com`). Default is false.
  • ipVersion: '4'|'6'|4|6 4 or 6. The default is undefind (allows both versions 4 and 6).
  • allowIPRange: boolean If true, allow IP range input (127.0.0.1/24, 2001::/128, etc.). Default is false.
isHTML() Check if it is HTML.
isIP() Check for IP (version 4 or 6).
Options:
  • ipVersion: '4'|'6'|4|6 4 or 6. The default is undefind (allows both versions 4 and 6).
  • allowIPRange: boolean If true, allow IP range input (127.0.0.1/24, 2001::/128, etc.). Default is false.
isKana() Check if it is katakana (half-width and full-width numbers are also permitted).
isNumericRange() Check the range of numbers.
Options:
  • min: string|number Minimum value of the range. Required.
  • max: string|number Maximum value of the range. Required.
isPath() Check if it is a file (directory) path
isPhoneNumberJp() Check if it is a Japanese phone number.
isPort() Check if it is a port number.
isUnixUserName() Check if it is a unix user name.
isURL() Check if it is a URL.
Options:
  • requireFQDNTld: boolean If true, the TLD is required. Default is true.
  • allowFQDNWildcard: boolean If true, the validator will allow domain starting with `*.` (e.g. `*.example.com` or `*.shop.example.com`). Default is false.
  • allowFragments: boolean If true, allow fragment input. Default is false.
  • allowQueryComponents: boolean If true, allow input of query string. Default is false.

Basic

              <!--begin::Form-->
<form data-ref="myForm">
  <!--begin::Input group-->
  <div class="fv-row mb-10">
    <!--begin::Label-->
    <label class="required fw-semibold fs-6 mb-2">First name</label>
    <!--end::Label-->
    <!--begin::Input-->
    <input type="text" name="firstName" class="form-control form-control-solid" placeholder="Enter first name" />
    <!--end::Input-->
  </div>
  <!--end::Input group-->
  <!--begin::Actions-->
  <button type="submit" class="btn btn-primary">
    <span class="indicator-label">Validation Form</span>
    <span class="indicator-progress">Please wait... <span class="spinner-border spinner-border-sm align-middle ms-2"></span></span>
  </button>
  <!--end::Actions-->
</form>
<!--end::Form-->
            
              import {components} from 'metronic-extension';

// Get references to elements with data-ref attributes.
const ref = components.selectRef();

// Initialize form validation.
const validation = new components.Validation(ref.myForm, {
  firstName: {
    validators: {
      notEmpty: {message: 'First name is required.'},
    }
  },
});

// Set form validation events.
validation.onValid(async () => {
  // Show loader.
  validation.onIndicator();

  // Hide the loader after a certain time.
  setTimeout(() => {
    // Hide loader.
    validation.offIndicator();

    // Success Message.
    components.Dialog.success('Form has been successfully submitted!', {confirmButtonText: 'OK, got it!'});
  }, 2000);
});