document.addEventListener('DOMContentLoaded', function () { var fullName = document.querySelector('input[name="full_name"]'); var email = document.querySelector('input[name="email"]'); var phone = document.querySelector('input[name="phone"]'); var submit = document.querySelector('button[type="submit"]'); const emailRegex = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i; const phoneRegex = /^(\+?0?1\s?)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/; const fullNameRegex = /[^\s.]{2,} [^\s.]{2,}/; fullName.addEventListener('input', function (e) { if (! fullName.value.toLowerCase().match(fullNameRegex)) { fullName.classList.add('invalid'); } else { fullName.classList.remove('invalid'); } }); email.addEventListener('input', function (e) { if (! email.value.toLowerCase().match(emailRegex)) { email.classList.add('invalid'); } else { email.classList.remove('invalid'); } }); phone.addEventListener('input', function (e) { if (! phone.value.match(phoneRegex)) { phone.classList.add('invalid'); } else { phone.classList.remove('invalid'); } }); submit.addEventListener('click', function (e) { e.preventDefault(); if (! fullName.value.toLowerCase().match(fullNameRegex)) { alert("Your full name appears invalid."); return; } if (! email.value.toLowerCase().match(emailRegex)) { alert("Your email address is invalid."); return; } if (! phone.value.match(phoneRegex)) { alert("Your phone number is invalid."); return; } var fd = new FormData(); fd.append('full_name', fullName.value); fd.append('email', email.value); fd.append('phone', phone.value); var req = fetch('/subscribe.php', { method: 'POST', body: fd }).then(function (res) { if (!res.ok) { res.json().then(function (err) { if ('field' in err) { document.querySelector('input[name="'+ err.field + '"]').classList.add('invalid'); } alert(err.message); }); } else { alert("You have subscribed successfully."); fullName.value = ""; email.value = ""; phone.value = ""; } }); }); });