#196 - Verify Member Information v0.1

Validate form inputs against member data in Memberstack with real-time feedback.

View demo


<!-- 💙 MEMBERSCRIPT #196 v0.1 💙 - VERIFY MEMBER INFORMATION -->
<script>
(function() {
  'use strict';
  
  document.addEventListener("DOMContentLoaded", async function() {
    try {
      // Check if Memberstack is loaded
      if (!window.$memberstackDom) {
        console.error('MemberScript #196: Memberstack DOM package is not loaded.');
        return;
      }
      
      const memberstack = window.$memberstackDom;
      
      // Wait for Memberstack to be ready
      await waitForMemberstack();
      
      // Get current member
      const { data: member } = await memberstack.getCurrentMember();
      
      // If no member is logged in, show warning and exit
      if (!member) {
        console.warn('MemberScript #196: No member logged in. Validation will not work.');
        return;
      }
      
      // Find the form with validation attribute
      const form = document.querySelector('[data-ms-code="validate-form"]');
      
      if (!form) {
        console.warn('MemberScript #196: Form with data-ms-code="validate-form" not found.');
        return;
      }
      
      // Get all inputs with validation attributes
      // Support both old format (validate-input-*) and new format (validate-input)
      // Also check for data-ms-custom-field attribute as primary identifier
      const inputs = form.querySelectorAll('[data-ms-code="validate-input"], [data-ms-code^="validate-input-"], [data-ms-custom-field]');
      
      // Filter to only inputs that have data-ms-custom-field
      const validationInputs = Array.from(inputs).filter(input => {
        return input.getAttribute('data-ms-custom-field') && 
               (input.tagName === 'INPUT' || input.tagName === 'TEXTAREA' || input.tagName === 'SELECT');
      });
      
      if (validationInputs.length === 0) {
        console.warn('MemberScript #196: No validation inputs found. Make sure inputs have data-ms-custom-field attribute.');
        return;
      }
      
      // Access custom fields - try different possible locations
      const customFields = member.customFields || member.data?.customFields || {};
      const auth = member.auth || member.data?.auth || {};
      
      // Helper function to get field value from nested paths (e.g., "auth.email" or "customFields.company-name")
      function getFieldValue(fieldPath) {
        if (!fieldPath) return null;
        
        // Handle nested paths like "auth.email" or "customFields.company-name"
        if (fieldPath.includes('.')) {
          const parts = fieldPath.split('.');
          let value = member;
          
          for (const part of parts) {
            if (value && typeof value === 'object') {
              value = value[part];
            } else {
              return null;
            }
          }
          
          return value;
        }
        
        // Try customFields first
        if (customFields[fieldPath] !== undefined) {
          return customFields[fieldPath];
        }
        
        // Try direct member property
        if (member[fieldPath] !== undefined) {
          return member[fieldPath];
        }
        
        return null;
      }
      
      // Set up validation for each input
      const validationRules = [];
      
      validationInputs.forEach(input => {
        const inputCode = input.getAttribute('data-ms-code');
        const customFieldId = input.getAttribute('data-ms-custom-field');
        const validationType = input.getAttribute('data-ms-validation-type') || 'exact';
        
        // Extract field name from data-ms-code (old format) or use customFieldId as fallback
        let fieldName;
        if (inputCode && inputCode.startsWith('validate-input-')) {
          fieldName = inputCode.replace('validate-input-', '');
        } else {
          // Use customFieldId as field name, removing dots and converting to readable format
          fieldName = customFieldId ? customFieldId.replace(/\./g, '-').replace(/-/g, ' ') : 'field';
        }
        
        if (!customFieldId) {
          console.warn(`MemberScript #196: Input "${fieldName}" missing data-ms-custom-field attribute.`);
          return;
        }
        
        // Get the custom field value from Memberstack
        let customFieldValue = getFieldValue(customFieldId);
        
        if (customFieldValue === undefined || customFieldValue === null) {
          console.warn(`MemberScript #196: Custom field "${customFieldId}" not found in member data.`);
          return;
        }
        
        // Convert to string, handling numbers and other types properly
        // For numbers, preserve leading zeros by converting carefully
        let customFieldValueString;
        if (typeof customFieldValue === 'number') {
          customFieldValueString = customFieldValue.toString();
        } else if (Array.isArray(customFieldValue)) {
          // If it's an array, take the first element
          customFieldValueString = String(customFieldValue[0] || '');
        } else {
          customFieldValueString = String(customFieldValue);
        }
        
        // Check if the field value is empty - if so, skip validation for this field
        // (there's nothing to validate against)
        if (!customFieldValueString || customFieldValueString.trim() === '') {
          console.warn(`MemberScript #196: Custom field "${customFieldId}" is empty. Skipping validation for this field.`);
          return;
        }
        
        // Find error message container
        // Try multiple methods: data-ms-error-for, data-ms-code="validate-error-[fieldName]", or generic validate-error
        let errorContainer = null;
        
        // Method 1: Look for error container with data-ms-error-for matching customFieldId
        if (customFieldId) {
          errorContainer = document.querySelector(`[data-ms-error-for="${customFieldId}"]`);
        }
        
        // Method 2: Look for error container with data-ms-code="validate-error-[fieldName]"
        if (!errorContainer) {
          errorContainer = document.querySelector(`[data-ms-code="validate-error-${fieldName}"]`);
        }
        
        // Method 3: Look for generic validate-error container that's a sibling or next element
        if (!errorContainer) {
          // Check if there's a sibling with validate-error
          const siblingError = input.parentElement?.querySelector('[data-ms-code="validate-error"]');
          if (siblingError) {
            errorContainer = siblingError;
          }
        }
        
        // Get a user-friendly label for the field
        // Try: data-ms-label attribute, associated label element, placeholder (cleaned), or fallback to fieldName
        let fieldLabel = input.getAttribute('data-ms-label');
        if (!fieldLabel) {
          // Try to find associated label (check parent label first, then for attribute)
          let labelElement = input.closest('label');
          if (!labelElement) {
            const labelId = input.getAttribute('id');
            if (labelId) {
              labelElement = document.querySelector(`label[for="${labelId}"]`);
            }
          }
          if (labelElement) {
            // Get label text, but remove the input text if it's nested
            fieldLabel = labelElement.textContent.trim();
            // Remove any input value that might be in the label
            const inputClone = labelElement.querySelector('input, textarea, select');
            if (inputClone && fieldLabel.includes(inputClone.value)) {
              fieldLabel = fieldLabel.replace(inputClone.value, '').trim();
            }
          }
          
          // If no label found, try placeholder (but clean it up)
          if (!fieldLabel) {
            const placeholder = input.getAttribute('placeholder');
            if (placeholder) {
              // Remove common prefixes like "Enter your", "Enter", "Type your", etc.
              fieldLabel = placeholder
                .replace(/^(enter your|enter|type your|type|your|please enter|please type)\s+/i, '')
                .replace(/\.$/, '') // Remove trailing period
                .trim();
            }
          }
          
          // Final fallback to fieldName
          if (!fieldLabel) {
            fieldLabel = fieldName;
          }
        }
        
        // Create validation rule
        const rule = {
          input: input,
          fieldName: fieldName,
          fieldLabel: fieldLabel,
          customFieldValue: customFieldValueString,
          validationType: validationType,
          errorContainer: errorContainer
        };
        
        validationRules.push(rule);
        
        // Add real-time validation on input
        input.addEventListener('input', function() {
          validateField(rule);
        });
        
        // Add validation on blur
        input.addEventListener('blur', function() {
          validateField(rule);
        });
      });
      
      // Add form submit handler
      form.addEventListener('submit', function(event) {
        let isValid = true;
        
        // Validate all fields
        validationRules.forEach(rule => {
          if (!validateField(rule)) {
            isValid = false;
          }
        });
        
        // Prevent submission if validation fails
        if (!isValid) {
          event.preventDefault();
          event.stopPropagation();
          
          // Focus on first invalid field
          const firstInvalid = validationRules.find(rule => !rule.isValid);
          if (firstInvalid && firstInvalid.input) {
            firstInvalid.input.focus();
          }
        }
      });
      
      // Validation function
      function validateField(rule) {
        const inputValue = rule.input.value.trim();
        const customValue = rule.customFieldValue ? rule.customFieldValue.trim() : '';
        
        // If the custom field value is empty, skip validation (always pass)
        if (!customValue || customValue === '') {
          // Clear any existing error state
          rule.input.style.borderColor = '';
          rule.input.setCustomValidity('');
          if (rule.errorContainer) {
            rule.errorContainer.textContent = '';
            rule.errorContainer.style.display = 'none';
          }
          rule.isValid = true;
          return true;
        }
        
        let isValid = false;
        let errorMessage = '';
        
        // Perform validation based on type
        switch (rule.validationType) {
          case 'exact':
            isValid = inputValue === customValue;
            errorMessage = isValid ? '' : `Value must match your registered ${rule.fieldLabel}.`;
            break;
            
          case 'contains':
            isValid = inputValue.includes(customValue);
            errorMessage = isValid ? '' : `Value must contain your registered ${rule.fieldLabel}.`;
            break;
            
          case 'startsWith':
            isValid = inputValue.startsWith(customValue);
            errorMessage = isValid ? '' : `Value must start with your registered ${rule.fieldLabel}.`;
            break;
            
          case 'endsWith':
            isValid = inputValue.endsWith(customValue);
            errorMessage = isValid ? '' : `Value must end with your registered ${rule.fieldLabel}.`;
            break;
            
          default:
            console.warn(`MemberScript #196: Unknown validation type "${rule.validationType}". Using "exact".`);
            isValid = inputValue === customValue;
            errorMessage = isValid ? '' : `Value must match your registered ${rule.fieldLabel}.`;
        }
        
        // Update rule state
        rule.isValid = isValid;
        
        // Update input styling
        if (isValid) {
          rule.input.style.borderColor = '';
          rule.input.setCustomValidity('');
        } else {
          rule.input.style.borderColor = '#ef4444';
          rule.input.setCustomValidity(errorMessage);
        }
        
        // Update error message container
        if (rule.errorContainer) {
          if (isValid) {
            rule.errorContainer.textContent = '';
            rule.errorContainer.style.display = 'none';
          } else {
            rule.errorContainer.textContent = errorMessage;
            rule.errorContainer.style.display = 'block';
            rule.errorContainer.style.color = '#ef4444';
            rule.errorContainer.style.fontSize = '14px';
            rule.errorContainer.style.marginTop = '4px';
          }
        }
        
        return isValid;
      }
      
    } catch (error) {
      console.error('MemberScript #196: Error setting up validation:', error);
    }
  });
  
  function waitForMemberstack() {
    return new Promise((resolve) => {
      if (window.$memberstackDom && window.$memberstackReady) {
        resolve();
      } else {
        document.addEventListener('memberstack.ready', resolve);
        // Fallback timeout
        setTimeout(resolve, 2000);
      }
    });
  }
})();
</script>


Customer Showcase

Have you used a Memberscript in your project? We’d love to highlight your work and share it with the community!

Creating the Make.com Scenario

1. Download the JSON blueprint below to get stated.

2. Navigate to Make.com and Create a New Scenario...

3. Click the small box with 3 dots and then Import Blueprint...

4. Upload your file and voila! You're ready to link your own accounts.

Need help with this MemberScript?

All Memberstack customers can ask for assistance in the 2.0 Slack. Please note that these are not official features and support cannot be guaranteed.

Join the 2.0 Slack
Version notes
Attributes
Description
Attribute
No items found.
Guides / Tutorials
No items found.
Tutorial
What is Memberstack?

Auth & payments for Webflow sites

Add logins, subscriptions, gated content, and more to your Webflow site - easy, and fully customizable.

Learn more

"We've been using Memberstack for a long time, and it has helped us achieve things we would have never thought possible using Webflow. It's allowed us to build platforms with great depth and functionality and the team behind it has always been super helpful and receptive to feedback"

Jamie Debnam
39 Digital

"Been building a membership site with Memberstack and Jetboost for a client. Feels like magic building with these tools. As someone who’s worked in an agency where some of these apps were coded from scratch, I finally get the hype now. This is a lot faster and a lot cheaper."

Félix Meens
Webflix Studio

"One of the best products to start a membership site - I like the ease of use of Memberstack. I was able to my membership site up and running within a day. Doesn't get easier than that. Also provides the functionality I need to make the user experience more custom."

Eric McQuesten
Health Tech Nerds
Off World Depot

"My business wouldn't be what it is without Memberstack. If you think $30/month is expensive, try hiring a developer to integrate custom recommendations into your site for that price. Incredibly flexible set of tools for those willing to put in some minimal efforts to watch their well put together documentation."

Riley Brown
Off World Depot

"The Slack community is one of the most active I've seen and fellow customers are willing to jump in to answer questions and offer solutions. I've done in-depth evaluations of alternative tools and we always come back to Memberstack - save yourself the time and give it a shot."

Abbey Burtis
Health Tech Nerds
Slack

Need help with this MemberScript? Join our Slack community!

Join the Memberstack community Slack and ask away! Expect a prompt reply from a team member, a Memberstack expert, or a fellow community member.

Join our Slack