Hi, I´ve trying to change the registration form and i added some custom attributes. The thing is i wanted to validate one of them called DNI with an external API, which if happens that the DNI is not valid then the user should not be created and there should be me a message that says invalid DNI. My problem is that i am getting CORS policy problems and the user is still being created even if it is invalid. I tried with this in the script.js file :
async function validateDNIandName() {
const dni = document.getElementById(‘user.attributes.DNI’).value;
const firstName = document.getElementById(‘firstName’).value.toUpperCase();
const lastName = document.getElementById(‘lastName’).value.toUpperCase();
const dniErrorElement = document.getElementById(‘input-error-user.attributes.DNI’);
if (dni && firstName && lastName) {
try {
const response = await fetch('https://api.apis.net.pe/v2/reniec/dni?numero=' + dni, {
method: 'GET',
headers: {
'Referer': 'https://apis.net.pe/consulta-dni-api',
'Authorization': 'my token'
},
});
const persona = await response.json(); // Get the persona object
const firstPersonaName = persona.nombres ? persona.nombres.split(' ')[0].toUpperCase() : '';
if (persona && firstPersonaName === firstName && persona.apellidoPaterno.toUpperCase() === lastName) {
dniErrorElement.textContent = '';
dniErrorElement.style.display = 'none';
return true;
} else {
dniErrorElement.textContent = 'DNI and Name do not match.';
dniErrorElement.style.display = 'block';
return false;
}
} catch (error) {
console.error('Error validating DNI and Name:', error);
dniErrorElement.textContent = 'Error validating DNI and Name. Please try again.';
dniErrorElement.style.display = 'block';
return false;
}
}
return true;
}
async function handleSubmit(event) {
const isValid = await validateDNIandName();
if (!isValid) {
event.preventDefault(); // Prevent form submission if validation fails
console.log(“Form submission prevented due to invalid DNI and Name.”);
} else {
console.log(“Form is valid. Submitting.”);
}
}
document.addEventListener(‘DOMContentLoaded’, () => {
const form = document.getElementById(‘kc-register-form’);
if (form) {
form.addEventListener(‘submit’, handleSubmit);
} else {
console.error(“Form not found.”);
}
});