← Script library

Client Scripts

Real-time Field Validation

Validate field input in real-time and provide immediate feedback to users (e.g., check format, valid values, etc.).

JavaScript
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
  // Exit if form is loading
  if (isLoading) {
    return;
  }

  // Configuration: Define validation rules for different scenarios
  var fieldName = 'u_email';  // Change to your field name
  var value = newValue;

  // Clear any previous validation messages
  g_form.hideFieldMsg(fieldName, true);

  // Skip validation if field is empty
  if (!value || value === '') {
    return;
  }

  // Example 1: Email validation
  var emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  if (!emailRegex.test(value)) {
    g_form.showFieldMsg(fieldName, 'Please enter a valid email address', 'error');
    return;
  }

  // Example 2: Phone number validation (US format)
  // Uncomment and modify for phone validation
  /*
  var phoneRegex = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
  if (!phoneRegex.test(value)) {
    g_form.showFieldMsg('phone', 'Please enter a valid phone number (xxx-xxx-xxxx)', 'error');
    return;
  }
  */

  // Example 3: Minimum/Maximum length validation
  /*
  if (value.length < 5) {
    g_form.showFieldMsg(fieldName, 'Must be at least 5 characters long', 'error');
    return;
  }
  if (value.length > 100) {
    g_form.showFieldMsg(fieldName, 'Cannot exceed 100 characters', 'error');
    return;
  }
  */

  // Example 4: Numeric range validation
  /*
  var numValue = parseFloat(value);
  if (isNaN(numValue)) {
    g_form.showFieldMsg(fieldName, 'Please enter a valid number', 'error');
    return;
  }
  if (numValue < 0 || numValue > 100) {
    g_form.showFieldMsg(fieldName, 'Value must be between 0 and 100', 'error');
    return;
  }
  */

  // Example 5: URL validation
  /*
  var urlRegex = /^(https?:\/\/)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/;
  if (!urlRegex.test(value)) {
    g_form.showFieldMsg(fieldName, 'Please enter a valid URL', 'error');
    return;
  }
  */

  // Show success message (optional)
  g_form.showFieldMsg(fieldName, 'Valid email format', 'info');
}

How to use it

1. Create an onChange Client Script on your table 2. Set the field to the one you want to validate 3. Customize the validation logic using the examples provided 4. Uncomment and modify examples as needed 5. Test with various valid and invalid inputs

Adapt the table names, fields, and conditions to your instance. Test the behavior in a development environment before using it in production.