Skip to content

Commit

Permalink
Merge pull request #17 from hsztan/form-validation
Browse files Browse the repository at this point in the history
Email validation and suggestion
  • Loading branch information
hsztan authored Mar 2, 2022
2 parents 60e8ae1 + eedc088 commit d471654
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
1 change: 1 addition & 0 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,7 @@ <h2 class="intro">
maxlength="500"
required
></textarea>
<small id="warnings"></small>
<button class="form-btn btn btn-main" type="submit">
Get in touch
</button>
Expand Down
7 changes: 7 additions & 0 deletions main.css
Original file line number Diff line number Diff line change
Expand Up @@ -838,6 +838,13 @@ nav ul .email-icon {
margin-top: 25px;
}

#warnings {
color: #ff6b00;
padding-top: 5px;
padding-left: 16px;
font-family: 'Crete Round', Arial, Helvetica, sans-serif;
}

.contact textarea {
padding: 12px;
margin-top: 24px;
Expand Down
46 changes: 46 additions & 0 deletions main.js
Original file line number Diff line number Diff line change
Expand Up @@ -193,4 +193,50 @@ const displayModal = (event) => {

workButtons.forEach((btn) => {
btn.addEventListener('click', displayModal);
});

// Validate email input in form

const validateEmail = (inputElement) => {
const username = inputElement.value.split('@')[0];
const emailRegex = /^[a-z_.\-|1-9]+$/;
return emailRegex.test(username);
};

const showMessage = (message, element, email) => {
const correctEmail = email.toLowerCase();
message += ` Did you mean this? ${correctEmail}`;
element.innerText = message;
};

// Disable hidden required fields in order to submit
const toggleDisableFields = () => {
const firstName = document.querySelector('#first-name');
const lastName = document.querySelector('#last-name');
const fullName = document.querySelector('#name');
if (window.innerWidth <= 992) {
firstName.setAttribute('disabled', true);
lastName.setAttribute('disabled', true);
fullName.removeAttribute('disabled');
} else {
firstName.removeAttribute('disabled');
lastName.removeAttribute('disabled');
fullName.setAttribute('disabled', true);
}
};

// In order to disable the hidden fields
window.addEventListener('resize', toggleDisableFields);
window.addEventListener('load', toggleDisableFields);

document.querySelector('.contact-form').addEventListener('submit', (e) => {
const emailInput = document.querySelector('#email');
const isValid = validateEmail(emailInput);
if (!isValid) {
e.preventDefault();
const msgErrorOutContainer = document.querySelector('#warnings');
showMessage('Please enter your email in lower-case letters.', msgErrorOutContainer, emailInput.value);
return false;
}
return true;
});

0 comments on commit d471654

Please sign in to comment.