#196 - Verify Member Information v0.1

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

Ver demostración


<!-- 💙 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!

Creación del escenario Make.com

1. Descargue el proyecto JSON a continuación para empezar.

2. Navegue hasta Make.com y Cree un nuevo escenario...

3. Haga clic en el pequeño cuadro con 3 puntos y luego Importar Blueprint...

4. Sube tu archivo y ¡voilá! Ya está listo para vincular sus propias cuentas.

¿Necesitas ayuda con este MemberScript?

Todos los clientes de Memberstack pueden solicitar asistencia en el Slack 2.0. Tenga en cuenta que no se trata de funciones oficiales y que no se puede garantizar la asistencia.

Únete al Slack 2.0
Notas de la versión
Atributos
Descripción
Atributo
No se han encontrado artículos.
Guías / Tutoriales
No se han encontrado artículos.
Tutorial
¿Qué es Memberstack?

Autenticación y pagos para sitios Webflow

Añada inicios de sesión, suscripciones, contenido cerrado y mucho más a su sitio Webflow: fácil y totalmente personalizable.

Más información

"Hemos estado utilizando Memberstack durante mucho tiempo, y nos ha ayudado a lograr cosas que nunca hubiéramos creído posible usando Webflow. Nos ha permitido construir plataformas con gran profundidad y funcionalidad y el equipo que hay detrás siempre ha sido súper servicial y receptivo a los comentarios"

Jamie Debnam
39 Digital

"He estado construyendo un sitio de membresía con Memberstack y Jetboost para un cliente. Se siente como magia construir con estas herramientas. Como alguien que ha trabajado en una agencia donde algunas de estas aplicaciones fueron codificadas desde cero, finalmente entiendo el bombo ahora. Esto es mucho más rápido y mucho más barato."

Félix Meens
Estudio Webflix

"Uno de los mejores productos para iniciar un sitio de membresía - Me gusta la facilidad de uso de Memberstack. Yo era capaz de mi sitio de membresía en marcha y funcionando dentro de un día. No hay nada más fácil que eso. También proporciona la funcionalidad que necesito para hacer la experiencia del usuario más personalizada."

Eric McQuesten
Nerds de la tecnología sanitaria
Depósito Off World

"Mi negocio no sería lo que es sin Memberstack. Si crees que 30 $/mes es caro, prueba a contratar a un desarrollador para que integre recomendaciones personalizadas en tu sitio por ese precio. Increíblemente flexible conjunto de herramientas para aquellos dispuestos a poner en algunos esfuerzos mínimos para ver su documentación bien elaborado."

Riley Brown
Depósito Off World

"La comunidad de Slack es una de las más activas que he visto y los clientes están dispuestos a responder preguntas y ofrecer soluciones. He realizado evaluaciones en profundidad de herramientas alternativas y siempre volvemos a Memberstack: ahórrate el tiempo y dale una oportunidad"."

Abadía Burtis
Nerds de la tecnología sanitaria
Slack

¿Necesitas ayuda con este MemberScript? ¡Únete a nuestra comunidad Slack!

Únete al Slack de la comunidad Memberstack y ¡pregunta! Espera una respuesta rápida de un miembro del equipo, un experto de Memberstack o un compañero de la comunidad.

Únete a nuestro Slack