#196 - Verify Member Information v0.1
Validate form inputs against member data in Memberstack with real-time feedback.
<!-- 💙 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!
Création du scénario Make.com
1. Téléchargez le modèle JSON ci-dessous pour commencer.
2. Naviguez jusqu'à Make.com et créez un nouveau scénario...

3. Cliquez sur la petite boîte avec trois points, puis sur Import Blueprint...

4. Téléchargez votre fichier et voilà ! Vous êtes prêt à relier vos propres comptes.
Besoin d'aide avec ce MemberScript ?
Tous les clients de Memberstack peuvent demander de l'aide dans le Slack 2.0. Veuillez noter qu'il ne s'agit pas de fonctionnalités officielles et que le support ne peut être garanti.
Rejoignez le Slack 2.0Auth & paiements pour les sites Webflow
Ajoutez des logins, des abonnements, du contenu à accès limité, et plus encore à votre site Webflow - facile et entièrement personnalisable.
.webp)
"Nous utilisons Memberstack depuis longtemps et il nous a aidé à réaliser des choses que nous n'aurions jamais imaginées avec Webflow. Il nous a aidé à réaliser des choses que nous n'aurions jamais cru possibles en utilisant Webflow. Il nous a permis de construire des plateformes avec beaucoup de profondeur et de fonctionnalité et l'équipe derrière lui a toujours été super utile et réceptif à la rétroaction"

"J'ai construit un site d'adhésion avec Memberstack et Jetboost pour un client. On a l'impression de construire quelque chose de magique avec ces outils. J'ai travaillé dans une agence où certaines de ces applications ont été codées à partir de zéro, je comprends enfin l'engouement suscité par ces outils. C'est beaucoup plus rapide et beaucoup moins cher."

"L'un des meilleurs produits pour lancer un site d'adhésion - J'aime la facilité d'utilisation de Memberstack. J'ai pu mettre en place mon site d'adhésion en l'espace d'une journée.. Il n'y a rien de plus facile. Il fournit également les fonctionnalités dont j'ai besoin pour rendre l'expérience de l'utilisateur plus personnalisée."

"Mon entreprise ne serait pas ce qu'elle est sans Memberstack. Si vous pensez que 30 $/mois c'est cher, essayez d'engager un développeur pour intégrer des recommandations personnalisées à votre site pour ce prix-là. Un ensemble d'outils incroyablement flexibles pour ceux qui sont prêts à faire quelques efforts minimes pour regarder leur documentation bien faite."


"La communauté Slack est l'une des plus actives que j'ai vues et les autres clients sont prêts à intervenir pour répondre aux questions et proposer des solutions. J'ai effectué des évaluations approfondies d'outils alternatifs et nous revenons toujours à Memberstack - gagnez du temps et tentez votre chance."

Besoin d'aide avec ce MemberScript ? Rejoignez notre communauté Slack !
Rejoignez le Slack de la communauté Memberstack et posez vos questions ! Attendez-vous à une réponse rapide d'un membre de l'équipe, d'un expert Memberstack ou d'un autre membre de la communauté.
Rejoignez notre Slack
.png)