jQuery Form Validation with Multi-File Upload - FormXpress

File Size: 29 KB
Views Total: 8
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
jQuery Form Validation with Multi-File Upload - FormXpress

FormXpress is a jQuery form enhancement plugin that automates form validation and multi-file uploads with real-time feedback. 

It handles client-side validation for standard HTML5 input types, displays humanized error messages, and manages AJAX submissions with progress tracking. 

The plugin weighs around 11KB minified and has no dependencies beyond jQuery 3.x. It runs in all browsers that support the File API, including IE11.

Features

  • Automatic HTML5 Validation: Validates required fields, email addresses, URLs, phone numbers, min/max lengths, number ranges, and custom patterns based on HTML5 attributes without writing validation logic.
  • Humanized Error Messages: Converts field names like email_address or firstName into readable labels such as "Email Address" or "First Name" in error messages.
  • Custom Validation Rules: Accepts field-specific validation functions through the customRules option.
  • Multi-File Upload with Previews: Displays thumbnail previews for image files, shows individual file names, includes per-file remove buttons, and renders progress bars for each uploaded file.
  • File Validation: Checks file size against configurable limits and validates file types using MIME type matching with wildcard support.
  • AJAX Submission Hooks: Provides lifecycle callbacks including beforeValidate, afterValidate, beforeSubmit, onSuccess, onError, and onProgress for controlling form behavior at each stage.
  • Public API Methods: Exposes validate(), reset(), and clearErrors() methods on the plugin instance for programmatic form control.
  • Zero CSS Dependencies: Automatically injects minimal required styles into the document head, with class names that can be overridden for custom styling.

Use Cases:

  • Legacy application modernization: Adds modern validation and upload features to older jQuery-based systems without rewriting the entire frontend.
  • Complex multi-file forms: Builds project submission forms where users can upload images and documents with instant preview and validation feedback.
  • Custom business validation: Implements company-specific rules like checking if a username exists or if an order number matches your format.
  • AJAX-driven interfaces: Creates single-page form experiences where users never leave the page during submission.

How To Use It:

1. Install FormXpress with NPM.

# NPM
$ npm install jquery-formxpress

2. Or download the package and load the form-xpress.min.js file in the document.

<script src="/dist/form-xpress.min.js"></script>
<!-- Or from a CDN -->
<script src="https://cdn.jsdelivr.net/npm/jquery-formxpress/dist/form-xpress.min.js"></script>

3. For a standard contact form, you only need to add HTML5 validation attributes to your inputs. FormXpress picks them up automatically.

<form id="contactForm" action="/api/contact" method="POST">
  <div class="form-group">
    <label>Full Name *</label>
    <input type="text" name="full_name" required minlength="3">
  </div>
  <div class="form-group">
    <label>Email Address *</label>
    <input type="email" name="email_address" required>
  </div>
  <div class="form-group">
    <label>Phone Number</label>
    <input type="tel" name="phone_number" pattern="[\d\s\-\+\(\)]+">
  </div>
  <div class="form-group">
    <label>Message *</label>
    <textarea name="message" required minlength="10" rows="4"></textarea>
  </div>
  <button type="submit">Send Message</button>
</form>
$('#contactForm').FormXpress({
  successMessage: "Thank you! Your message has been sent.",
  ajax: true,
  onSuccess: function(response, form) {
    alert('Success! Response: ' + JSON.stringify(response));
    form.data('FormXpress').reset();
  },
  onError: function(xhr, form) {
    alert('Error: ' + xhr.status);
  }
});

4. For forms handling file uploads, configure file size limits and allowed MIME types:

<form id="uploadForm" action="/api/upload" method="POST" enctype="multipart/form-data">
  <div class="form-group">
    <label>Project Name *</label>
    <input type="text" name="project_name" required>
  </div>
  <div class="form-group">
    <label>Upload Images (Max 5MB each) *</label>
    <input type="file" name="project_images" multiple accept="image/*" required>
  </div>
  <div class="form-group">
    <label>Upload Documents</label>
    <input type="file" name="project_docs" multiple>
  </div>
  <button type="submit">Upload Files</button>
</form>
$('#uploadForm').FormXpress({
  maxFileSize: 5242880, // 5MB
  allowedFileTypes: ['image/*', 'application/pdf', 'application/msword'],
  onProgress: function(percent, form) {
    console.log('Upload progress: ' + percent.toFixed(2) + '%');
  },
  onSuccess: function(response, form) {
    alert('Files uploaded successfully!');
    form.data('FormXpress').reset();
  },
  messages: {
    fileSize: "File is too large! Maximum {size}MB allowed",
    fileType: "Only images, PDFs, and Word documents are allowed"
  }
});

6. Create custom validation rules using the customRules option:

<form id="registerForm" action="/api/register" method="POST">
  <div class="form-group">
    <label>Username *</label>
    <input type="text" name="username" required minlength="4" maxlength="20">
  </div>
  <div class="form-group">
    <label>Email *</label>
    <input type="email" name="email" required>
  </div>
  <div class="form-group">
    <label>Password *</label>
    <input type="password" name="password" id="password" required minlength="8">
  </div>
  <div class="form-group">
    <label>Confirm Password *</label>
    <input type="password" name="confirm_password" required>
  </div>
  <div class="form-group">
    <label>Age *</label>
    <input type="number" name="age" min="18" max="100" required>
  </div>
  <div class="form-group">
    <label>Website</label>
    <input type="url" name="website">
  </div>
  <button type="submit">Register</button>
</form>
$('#registerForm').FormXpress({
  customRules: {
    confirm_password: function(value, input) {
      const password = $('#password').val();
      if (value !== password) {
        return "Passwords do not match";
      }
      return null;
    },
    username: function(value, input) {
      if (!/^[a-zA-Z0-9_]+$/.test(value)) {
        return "Only letters, numbers, and underscores allowed";
      }
      return null;
    },
    password: function(value, input) {
      if (!/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(value)) {
        return "Must contain uppercase, lowercase, and number";
      }
      return null;
    }
  },
  beforeSubmit: function(form, formData) {
    console.log('About to submit...');
    return true; // return false to cancel submission
  },
  onSuccess: function(response, form) {
    alert('Registration successful!');
    window.location.href = '/dashboard';
  },
  resetAfterSubmit: false
});

7. Customize the plugin's behavior with the following options:

Option Type Default Description
submitButton string | null null jQuery selector for the submit button. If null, finds the first submit button in the form.
errorClass string "input-error" CSS class applied to invalid input elements.
errorSpanClass string "error-text" CSS class for error message spans inserted below invalid inputs.
progressBarClass string "file-progress" CSS class for file upload progress bars.
previewClass string "file-preview" CSS class for file preview containers.
showNameError boolean true Whether to include the field name in error messages.
humanizeNames boolean true Converts field names like email_address to "Email Address" in error messages.
successMessage string "Form submitted successfully!" Default success alert message when no onSuccess callback is provided.
ajax boolean true Submit form via AJAX. Set to false for standard form submission.
resetAfterSubmit boolean false Automatically reset the form after successful submission.
maxFileSize number 10485760 Maximum file size in bytes (default is 10MB).
allowedFileTypes string[] [] Array of allowed MIME types. Supports wildcards like "image/*". Empty array allows all types.
customRules object {} Object mapping field names to validation functions. Functions receive (value, input) and return an error string or null.
beforeValidate function null Callback executed before validation starts. Receives the form jQuery object.
afterValidate function null Callback executed after validation completes. Receives the form jQuery object and a boolean indicating validity.
beforeSubmit function null Callback executed before form submission. Receives the form jQuery object and FormData object. Return false to cancel submission.
onSuccess function null Callback executed on successful AJAX submission. Receives the response object and form jQuery object.
onError function null Callback executed on AJAX submission failure. Receives the XMLHttpRequest object and form jQuery object.
onProgress function null Callback executed during file upload. Receives the upload percentage and form jQuery object.
messages object {} Custom error message strings. Keys include required, email, url, number, minLength, maxLength, min, max, pattern, fileSize, fileType, and phone.
$('#registerForm').FormXpress({
  submitButton: null,
  errorClass: "input-error",
  errorSpanClass: "error-text",
  progressBarClass: "file-progress",
  previewClass: "file-preview",
  showNameError: true,
  humanizeNames: true, // Convert field names to readable format
  successMessage: "Form submitted successfully!",
  ajax: true,
  resetAfterSubmit: false,
  maxFileSize: 10485760, // 10MB in bytes
  allowedFileTypes: [], // ['image/*', 'application/pdf']
  customRules: {}, // { fieldName: function(value, input) { return null or error } }
  // Hooks
  beforeValidate: null, // function(form) {}
  afterValidate: null, // function(form, isValid) {}
  beforeSubmit: null, // function(form, formData) { return true/false }
  onSuccess: null, // function(response, form) {}
  onError: null, // function(xhr, form) {}
  onProgress: null, // function(percent, form) {}
  // Messages
  messages: {
    required: "This field is required",
    email: "Please enter a valid email address",
    url: "Please enter a valid URL",
    number: "Please enter a valid number",
    minLength: "Minimum {min} characters required",
    maxLength: "Maximum {max} characters allowed",
    min: "Value must be at least {min}",
    max: "Value must be no more than {max}",
    pattern: "Invalid format",
    fileSize: "File size exceeds {size}MB limit",
    fileType: "Invalid file type",
    phone: "Please enter a valid phone number",
  },
});

8. Access the plugin instance through jQuery data and call public methods:

const formInstance = $("#myForm").data("FormXpress");

// Validate the form programmatically
const isValid = formInstance.validate(); // Returns boolean

// Reset the form and clear all errors
formInstance.reset();

// Clear error messages and classes without resetting field values
formInstance.clearErrors();

FAQs:

Q: How do I validate a field based on another field's value?
A: Use the customRules option to define interdependent validation. Your validation function receives the field's value and the input element as a jQuery object. Use the input element to traverse the form and access other field values. For password confirmation, find the password field using input.closest('form').find('input[name="password"]') and compare values. Return an error string if validation fails or null if valid.

Q: Can I disable AJAX submission and use standard form posting?
A: Set the ajax option to false during initialization. The plugin will validate the form client-side but allow the browser to handle submission normally. The form will post to the URL specified in the action attribute using the method defined in the form element. Lifecycle hooks like beforeSubmit, onSuccess, and onError will not execute in this mode since the plugin does not intercept the actual submission.

Q: Why are my file previews not showing thumbnails for images?
A: Image previews require the browser to read file contents using the FileReader API. Check that your file input has the correct MIME type by ensuring the uploaded files match the accept attribute or allowedFileTypes configuration.

Q: How do I handle validation errors returned from the server?
A: Server-side validation errors arrive in the onError callback with the XMLHttpRequest object. Parse the response body to extract error messages, then manually display them using jQuery. Select the relevant input fields by name and call the same error injection logic the plugin uses, or define your own error display method. Access the plugin's error class via form.data('FormXpress') if you need consistency with client-side errors.

Related Resources:


This awesome jQuery plugin is developed by masum-excellisit. For more Advanced Usages, please check the demo page or visit the official website.