I need help with form validation. I would like for the error messages to not move the entire input field when they show up. This way, I can put them on my #media queries without them moving down and taking up another section below the ones they belong on. I have tried to add margins beneath the input fields but that doesn't work, it just increases the space between the input fields. Is there a work around here? I have just learned this JS yesterday.
Here is my codepen:
https://codepen.io/drxl/pen/WNpVQaQ
<form action="" method="POST" id="contact-form" class="contact">
<div class="name-form">
<label for="name">Your Name</label>
<input id="name" type="text" placeholder=" Your name..." required>
</div>
<div class="email-form">
<label for="email">Your Email</label>
<input id="email" type="email" placeholder=" Your email..." required>
</div>
<div class="contact__txtarea">
<label for="text">Message</label>
<textarea class="textarea" id="text" placeholder=" Your message here..." required></textarea>
</div>
<div class="btn">
<input class="contact-section__btn" type="submit" value="Send Message" required>
</div>
</form>
label {
display: none;
font-size: 1px;
}
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
input:-webkit-autofill:active {
-webkit-transition: "color 9999s ease-out, background-color 9999s ease-out";
-webkit-transition-delay: 9999s;
}
.contact input,
.contact textarea {
margin: .5rem;
font-weight: 1000;
font-family: "Roboto", sans-serif;
font-size: 1.1rem;
}
.name-form label,
.email-form label,
.contact__textarea label {
display: none;
}
input[type="text"],
[type="email"],
textarea {
background-color: rgb(223, 198, 182, 0.875);
border-color: rgb(201, 83, 5);
width: 550px;
height: 40px;
-webkit-box-shadow: rgb(36, 36, 36) 10px 10px 10px;
box-shadow: rgb(36, 36, 36) 10px 10px 10px;
}
::-webkit-input-placeholder {
color: black;
}
::-moz-placeholder {
color: black;
}
:-ms-input-placeholder {
color: black;
}
::-ms-input-placeholder {
color: black;
}
::placeholder {
color: black;
}
.name-form,
.email-form,
.contact__txtarea {
margin-bottom: 20px;
}
.contact__txtarea label,
.textarea {
width: 550px;
height: 300px;
vertical-align: top;
}
.error-message {
color: red;
font-size: 1rem;
}
.contact-section__btn {
padding: 12px 52px;
background: rgb(201, 83, 5);
border: none;
color: white;
font-size: 1rem;
margin-right: 200rem;
-webkit-appearance: none;
}
.contact-section__btn:hover,
.contact-section__btn:focus {
background-color: rgb(209, 179, 124, 0.7);
opacity: .7;
color: black;
cursor: pointer;
transform: scale(0.85);
transition: ease .45s;
margin: 12px;
}
(function() {
let form = document.querySelector('#contact-form');
let nameInput = document.querySelector('#name');
let emailInput = document.querySelector('#email');
let textAreaInput = document.querySelector('#text');
function showErrorMessage(input, message) {
let container = input.parentElement;
let error = container.querySelector('.error-message');
if (error) {
container.removeChild(error);
}
if (message) {
let error = document.createElement('div')
error.classList.add('error-message');
error.innerText = message;
container.appendChild(error);
}
}
function validateName() {
let value = nameInput.value;
if(!value) {
showErrorMessage(nameInput, 'Name is a required field.');
return false;
}
showErrorMessage(nameInput, null);
return true;
}
function validateEmail() {
let value = emailInput.value;
if (!value) {
showErrorMessage(emailInput, 'Email is a required field.');
return false;
}
if (value.indexOf('#') === -1) {
showErrorMessage(emailInput, 'You must enter a valid email address.');
return false;
}
showErrorMessage(emailInput, null);
return true;
}
function validateTextArea() {
let value = textAreaInput.value;
if (!value) {
showErrorMessage(textAreaInput, 'You must enter a message.');
return false;
}
showErrorMessage(textAreaInput, null);
return true;
}
function validateForm() {
let isValidName = validateName;
let isValidEmail = validateEmail;
let isValidTextArea = validateTextArea;
return isValidName && isValidEmail && isValidTextArea;
}
form.addEventListener('submit', (e) => {
e.preventDefault();
if (validateForm()) {
alert('Success!');
}
});
nameInput.addEventListener('input', validateName);
emailInput.addEventListener('input', validateEmail);
textAreaInput.addEventListener('input', validateTextArea);
})();
Related
I'm new here :)
I've been trying to built a form with 2 inputs and one textarea. When I check the inputs, everything goes fine, but the problem occurs when I try to submit my form. Even though the textarea field is not empty, the function doesn't change my border into green color, and the text in below doesn't dissaper.
On the other hand, when I put an eventlistener while checking inputs - form closes, after filling textarea with any letter.
I cannot think of any solution, I would like an eventlistener to work exactly the same as it works on inputs.
I hope you understand my problem, I attach my code to show you my point of view.
Hope I get some answers from you! :)
Thanks!
// Formularz - the form
const form = document.querySelector('form');
const yourName = document.getElementById('name');
const email = document.getElementById('email');
const msg = document.getElementById('message');
form.addEventListener('submit', (e) => {
e.preventDefault();
checkInputs();
})
yourName.addEventListener('input', () => {
checkInputs();
})
email.addEventListener('input', () => {
checkInputs();
})
function checkInputs() {
const yourNameValue = yourName.value.trim();
const emailValue = email.value.trim();
const msgValue = msg.value.trim();
if(yourNameValue === '') {
setErrorFor(yourName, 'Name is required')
}
else {
setSuccesFor(yourName);
}
if(emailValue === "") {
setErrorFor(email, 'Email is required')
}
else if(!isEmail(emailValue)) {
setErrorFor(email, 'Email is not valid')
}
else {
setSuccesFor(email)
}
if (msgValue === "") {
setTextError(msg, 'Message is required')
}
else {
setTextSuccess(msg)
}
// zamykanie formularza - closing the form
if (yourNameValue && emailValue && msgValue) {
form.classList.add('close');
}
}
function setTextError(textarea, message) { // funkcja odpowiedzialna za textarea - function responsible for textarea
const formControl = textarea.parentElement;
const small = formControl.querySelector('small');
small.innerText = message;
formControl.className = 'form-control error';
}
function setTextSuccess(textarea) {
const formControl = textarea.parentElement;
formControl.className = 'form-control success';
}
function setErrorFor(input, message) {
const formControl = input.parentElement;
const small = formControl.querySelector('small')
// add error message inside small
small.innerText = message;
// add error class
formControl.className = 'form-control error';
}
function setSuccesFor(input) {
const formControl = input.parentElement;
formControl.className = 'form-control success';
}
function isEmail(email) {
return /^\S+#\S+\.\S+$/.test(email);
}
.form-parent {
background-color: lightblue;
color: white;
}
textarea {
resize: none;
padding: 5px;
}
form {
display: block;
margin-top: 20px;
padding: 20px 20px 0;
}
input, label, textarea {
width: 100%;
font-family: Roboto, sans-serif;
}
.form-control label {
display: inline-block;
margin-bottom: 5px;
color: black;
}
.form-control input {
display: block;
padding: 5px;
}
.form-control {
position: relative;
margin-bottom: 10px;
padding-bottom: 20px;
}
#submit {
padding: 10px 30px;
margin:10px 0 20px;
background-color: lightblue;
color: black;
border: solid white 1px;
font-family: Roboto, sans-serif;
font-size: 1rem;
}
small {
font-family: Roboto, sans-serif;
margin-top: 5px;
visibility: hidden;
color: rgb(182, 19, 19);
position: absolute;
bottom: 0;
left: 0;
}
/* input check */
.form-control.success input {
border: 2px solid green;
}
.form-control.error input {
border: 2px solid rgb(182, 19, 19);
}
.form-control.error textarea {
border: 2px solid rgb(182, 19, 19);
}
/* textarea check */
.form-control.success textarea {
border: 2px solid green;
}
.form-control.error small {
visibility: visible;
}
/* zamykanie formularza */ - closing the form
form.close {
visibility: hidden;
}
<div class="form-parent">
<form action="/" method="get">
<div class="form-control">
<label for="name">Name</label>
<input id="name" name="name" type="text">
<small></small>
</div>
<div class="form-control">
<label for="email">Email</label>
<input id="email" type="email">
<small></small>
</div>
<div class="form-control">
<label for="message">Message</label>
<textarea id="message" cols="10" rows="10"></textarea>
<small></small>
</div>
<button id="submit" type="submit">Submit</button>
</form>
</div>
the form never gets submitted, and the close is added whenever all three fields are filled (you might add textarea minimum characters check)... The problem seems to be the submitting. Try this:
add input listener for textarea
when setting close, also return true to submit check method, which will indicate that the form is valid, and then submit the form programmatically from there
change submit button's submit id to submit-btn in HTML and CSS, to allow form.submit method
const form = document.querySelector('form');
const yourName = document.getElementById('name');
const email = document.getElementById('email');
const msg = document.getElementById('message');
form.addEventListener('submit', (e) => {
e.preventDefault();
const check = checkInputs();
if (check) form.submit();
})
yourName.addEventListener('input', () => {
checkInputs();
})
email.addEventListener('input', () => {
checkInputs();
})
msg.addEventListener('input', () => {
checkInputs();
})
function checkInputs() {
const yourNameValue = yourName.value.trim();
const emailValue = email.value.trim();
const msgValue = msg.value.trim();
if (yourNameValue === '') {
setErrorFor(yourName, 'Name is required')
} else {
setSuccesFor(yourName);
}
if (emailValue === "") {
setErrorFor(email, 'Email is required')
} else if (!isEmail(emailValue)) {
setErrorFor(email, 'Email is not valid')
} else {
setSuccesFor(email)
}
if (msgValue === "") {
setTextError(msg, 'Message is required')
} else {
setTextSuccess(msg)
}
// zamykanie formularza - closing the form
if (yourNameValue && emailValue && msgValue) {
form.classList.add('close');
return true;
}
}
function setTextError(textarea, message) { // funkcja odpowiedzialna za textarea - function responsible for textarea
const formControl = textarea.parentElement;
const small = formControl.querySelector('small');
small.innerText = message;
formControl.className = 'form-control error';
}
function setTextSuccess(textarea) {
const formControl = textarea.parentElement;
formControl.className = 'form-control success';
}
function setErrorFor(input, message) {
const formControl = input.parentElement;
const small = formControl.querySelector('small')
// add error message inside small
small.innerText = message;
// add error class
formControl.className = 'form-control error';
}
function setSuccesFor(input) {
const formControl = input.parentElement;
formControl.className = 'form-control success';
}
function isEmail(email) {
return /^\S+#\S+\.\S+$/.test(email);
}
.form-parent {
background-color: lightblue;
color: white;
}
textarea {
resize: none;
padding: 5px;
}
form {
display: block;
margin-top: 20px;
padding: 20px 20px 0;
}
input,
label,
textarea {
width: 100%;
font-family: Roboto, sans-serif;
}
.form-control label {
display: inline-block;
margin-bottom: 5px;
color: black;
}
.form-control input {
display: block;
padding: 5px;
}
.form-control {
position: relative;
margin-bottom: 10px;
padding-bottom: 20px;
}
#submit-btn {
padding: 10px 30px;
margin: 10px 0 20px;
background-color: lightblue;
color: black;
border: solid white 1px;
font-family: Roboto, sans-serif;
font-size: 1rem;
}
small {
font-family: Roboto, sans-serif;
margin-top: 5px;
visibility: hidden;
color: rgb(182, 19, 19);
position: absolute;
bottom: 0;
left: 0;
}
/* input check */
.form-control.success input {
border: 2px solid green;
}
.form-control.error input {
border: 2px solid rgb(182, 19, 19);
}
.form-control.error textarea {
border: 2px solid rgb(182, 19, 19);
}
/* textarea check */
.form-control.success textarea {
border: 2px solid green;
}
.form-control.error small {
visibility: visible;
}
/* zamykanie formularza */
- closing the form form.close {
visibility: hidden;
}
<div class="form-parent">
<form action="/" method="get">
<div class="form-control">
<label for="name">Name</label>
<input id="name" name="name" type="text">
<small></small>
</div>
<div class="form-control">
<label for="email">Email</label>
<input id="email" type="email">
<small></small>
</div>
<div class="form-control">
<label for="message">Message</label>
<textarea id="message" cols="10" rows="10"></textarea>
<small></small>
</div>
<button id="submit-btn" type="submit">Submit</button>
</form>
</div>
I made a form with js validation that sets an error function (setErrorFor) if the input is not valid.
The form has a submit button that shows an animated checkmark if the input is valid (function showSucces). When the input is not valid it needs to not show that checkmark.
So I created a function (stopSendingData) to prevent the succes function from executing. But now the checkmark is not showing at all, even if the input is valid.
So I tried to change the if statement in the stopSendingData function and I tried it by changing the way to stop it but non of the attempts made the checkmark only showing when the input is valid.
I really look forward to hear from what I am doing wrong and how to solve this.
// Listen for a submit
document.querySelector(".contactForm").addEventListener("submit", submitForm);
function submitForm(e) {
e.preventDefault();
checkInputs(); //val
showSucces();
}
function showSucces() {
document.getElementById("submitButton").classList.add("clicked");
setTimeout(() => {
document.getElementById("submitButton").classList.remove("clicked");
}, 4000);
}
//form validaton
const namecontact = document.getElementById('namecontact'); //Val
const email = document.getElementById('email'); //Val
const message = document.getElementById('message'); //Val
function checkInputs() {
//Get the values from the inputs
const nameValue = namecontact.value.trim();
const emailValue = email.value.trim();
const messageValue = message.value.trim();
const numbers = /^[0-9]+$/;
if (nameValue === '') {
setErrorFor(namecontact, "Name cannot be blank.");
}
if (nameValue.match(numbers)) {
setErrorFor(namecontact, "Name can not contain number(s).");
}
if (emailValue === '') {
setErrorFor(email, "Email cannot be blank.");
}
else if (!isEmail(emailValue)) {
setErrorFor(email, 'Email is not valid.');
}
if (messageValue === '') {
setErrorFor(message, "Message cannot be blank.");
}
stopSendingData();
}
function setErrorFor(input, errorMessage) {
const formControl = input.parentElement; //.form-control
const small = formControl.querySelector('small');
//add error message inside small
small.innerText = errorMessage;
// add error class
formControl.className = 'form-control error';
}
function isEmail(email) {
return /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email);
}
function stopSendingData() {
// const small = document.querySelector('small');
const small = getElementsByTagName('small');
const formControl = small.parentElement; //.form-control
if (formControl.className = 'form-control error') {
return false;
}
}
.contactForm {
flex: 0%;
margin: 0px 0px;
width: 21%;
position: absolute;
margin: 90px 0px 0px 10.5px;
left: 0px;
/* max-width : 100%; */
/* opacity : 0.39; */
}
.name,
.email,
.subject {
position: relative;
width: 279px;
height: 39px;
padding: 9px 15px 15px 15px;
margin-left: 39.9px;
font-size: 13.2px;
}
.message {
position: relative;
width: 279px;
height: 60px;
padding: 9px 15px 15px 15px;
margin-left: 39.9px;
font-size: 13.2px;
}
::placeholder {
margin-top: 0px;
font-size: 12px;
}
.fas.fa-exclamation-circle {
color: red;
width: 15px;
height: 15px;
position: absolute;
/* visibility : visible; */
top: 15px;
right: 60px;
}
/*
.form-control input {
border : 1px solid transparent;
} */
.form-control {
position: relative;
}
.form-control i.fas.fas.fa-exclamation-circle {
visibility: hidden;
}
small {
position: absolute;
left: 75px;
visibility: hidden;
top: 24.9px;
font-size: 13.5px;
font-weight: bolder;
z-index: 9;
width: 300px;
}
.form-control.error input {
border-color: red;
}
.form-control.error textarea {
border-color: red;
}
.form-control.error i.fas.fas.fa-exclamation-circle {
visibility: visible;
color: red;
}
.form-control.error small {
color: red;
visibility: visible;
}
#submitButton {
margin: 9px 0px 0px 42px;
width: 277.2px;
height: 27px;
}
#submitButton {
position: relative;
cursor: pointer;
height: 30px;
width: 90px;
transition: all 1250ms cubic-bezier(0.19, 1, 0.22, 1);
}
#submitButton.clicked {
background-color: rgb(4, 221, 250);
color: rgb(21, 21, 24);
font-weight: bold;
font-size: 16.2px;
opacity: 0.6;
padding-top: 1.7px;
}
#submitButton.clicked span {
animation: spanShrink 1.8s ease-in-out forwards;
}
#keyframes spanShrink {
15% {
opacity: 0;
}
85% {
opacity: 0;
}
100% {
opacity: 1;
}
}
#submitButton .checkmark {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
stroke-width: 3;
stroke: rgb(18, 19, 19);
stroke-miterlimit: 10;
width: 51px;
height: 51px;
transform-origin: 50% 50%;
stroke-dasharray: 48;
stroke-dashoffset: 48;
}
#submitButton.clicked .checkmark {
animation: stroke 1.5s ease-in-out 0.6s forwards;
}
#keyframes stroke {
20% {
stroke-dashoffset: 0;
}
50% {
stroke-dashoffset: 0;
}
70% {
stroke-dashoffset: 48;
}
}
<form method="POST" class="contactForm" id="form">
<div class="form-control">
<input class="name" id="namecontact" type="text" placeholder="Name" /><br>
<i class="fas fa-exclamation-circle" id="exclamation1"></i>
<small></small>
</div>
<div class="form-control">
<input class="email" id="email" placeholder="E-mail" /><br>
<i class="fas fa-exclamation-circle" id="exclamation2"></i>
<small></small>
</div>
<div class="form-control">
<input class="subject" type="text" placeholder="Subject" /><br>
</div>
<div class="form-control">
<textarea class="message" id="message" cols="30" rows="10" placeholder="Message"></textarea><br>
<i class="fas fa-exclamation-circle" id="exclamation4"></i>
<small></small>
</div>
<button id="submitButton" type="submit">
<span>Launch</span>
<svg class="checkmark" viewBox="0 0 52 52">
<path fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8"/>
</svg>
</button>
</div>
</form>
To solve your problem you simply have to move the call of showSucces() to the end of stopSendingData(). Otherwise you call it everytime when the form is submitted, even if the check failes.
By the way: There are some issues in your code:
you have to call getElementsByTagName() with document. before it:
const small = document.getElementsByTagName('small');
getElementsByTagName() produces a collection of elements, not a single one, so that you can't get a parent element this way. Therefor you have to loop over the collection:
for (i = 0; i < small.length; i++) {
if (small[i].parentElement.classList.contains('error')) {
return false;
}
}
you have a closing div to much (at the end of the form)
Working example:
// Listen for a submit
document.querySelector(".contactForm").addEventListener("submit", submitForm);
function submitForm(e) {
e.preventDefault();
checkInputs(); //val
}
function showSucces() {
document.getElementById("submitButton").classList.add("clicked");
setTimeout(() => {
document.getElementById("submitButton").classList.remove("clicked");
}, 4000);
}
//form validaton
const namecontact = document.getElementById('namecontact'); //Val
const email = document.getElementById('email'); //Val
const message = document.getElementById('message'); //Val
function checkInputs() {
//Get the values from the inputs
const nameValue = namecontact.value.trim();
const emailValue = email.value.trim();
const messageValue = message.value.trim();
const numbers = /^[0-9]+$/;
if (nameValue === '') {
setErrorFor(namecontact, "Name cannot be blank.");
}
if (nameValue.match(numbers)) {
setErrorFor(namecontact, "Name can not contain number(s).");
}
if (emailValue === '') {
setErrorFor(email, "Email cannot be blank.");
} else if (!isEmail(emailValue)) {
setErrorFor(email, 'Email is not valid.');
}
if (messageValue === '') {
setErrorFor(message, "Message cannot be blank.");
}
stopSendingData();
}
function setErrorFor(input, errorMessage) {
const formControl = input.parentElement; //.form-control
const small = formControl.querySelector('small');
//add error message inside small
small.innerText = errorMessage;
// add error class
formControl.className = 'form-control error';
}
function isEmail(email) {
return /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email);
}
function stopSendingData() {
const small = document.getElementsByTagName('small');
for (i = 0; i < small.length; i++) {
if (small[i].parentElement.classList.contains('error')) {
return false;
}
}
showSucces();
}
.contactForm {
flex: 0%;
margin: 0px 0px;
width: 21%;
position: absolute;
margin: 90px 0px 0px 10.5px;
left: 0px;
}
.name,
.email,
.subject {
position: relative;
width: 279px;
height: 39px;
padding: 9px 15px 15px 15px;
margin-left: 39.9px;
font-size: 13.2px;
}
.message {
position: relative;
width: 279px;
height: 60px;
padding: 9px 15px 15px 15px;
margin-left: 39.9px;
font-size: 13.2px;
}
::placeholder {
margin-top: 0px;
font-size: 12px;
}
.fas.fa-exclamation-circle {
color: red;
width: 15px;
height: 15px;
position: absolute;
top: 15px;
right: 60px;
}
.form-control {
position: relative;
}
.form-control i.fas.fas.fa-exclamation-circle {
visibility: hidden;
}
small {
position: absolute;
left: 75px;
visibility: hidden;
top: 24.9px;
font-size: 13.5px;
font-weight: bolder;
z-index: 9;
width: 300px;
}
.form-control.error input {
border-color: red;
}
.form-control.error textarea {
border-color: red;
}
.form-control.error i.fas.fas.fa-exclamation-circle {
visibility: visible;
color: red;
}
.form-control.error small {
color: red;
visibility: visible;
}
#submitButton {
margin: 9px 0px 0px 42px;
width: 277.2px;
height: 27px;
}
#submitButton {
position: relative;
cursor: pointer;
height: 30px;
width: 90px;
transition: all 1250ms cubic-bezier(0.19, 1, 0.22, 1);
}
#submitButton.clicked {
background-color: rgb(4, 221, 250);
color: rgb(21, 21, 24);
font-weight: bold;
font-size: 16.2px;
opacity: 0.6;
padding-top: 1.7px;
}
#submitButton.clicked span {
animation: spanShrink 1.8s ease-in-out forwards;
}
#keyframes spanShrink {
15% {
opacity: 0;
}
85% {
opacity: 0;
}
100% {
opacity: 1;
}
}
#submitButton .checkmark {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
stroke-width: 3;
stroke: rgb(18, 19, 19);
stroke-miterlimit: 10;
width: 51px;
height: 51px;
transform-origin: 50% 50%;
stroke-dasharray: 48;
stroke-dashoffset: 48;
}
#submitButton.clicked .checkmark {
animation: stroke 1.5s ease-in-out 0.6s forwards;
}
#keyframes stroke {
20% {
stroke-dashoffset: 0;
}
50% {
stroke-dashoffset: 0;
}
70% {
stroke-dashoffset: 48;
}
}
<form method="POST" class="contactForm" id="form">
<div class="form-control">
<input class="name" id="namecontact" type="text" placeholder="Name" /><br>
<i class="fas fa-exclamation-circle" id="exclamation1"></i>
<small></small>
</div>
<div class="form-control">
<input class="email" id="email" placeholder="E-mail" /><br>
<i class="fas fa-exclamation-circle" id="exclamation2"></i>
<small></small>
</div>
<div class="form-control">
<input class="subject" type="text" placeholder="Subject" /><br>
</div>
<div class="form-control">
<textarea class="message" id="message" cols="30" rows="10" placeholder="Message"></textarea><br>
<i class="fas fa-exclamation-circle" id="exclamation4"></i>
<small></small>
</div>
<button id="submitButton" type="submit">
<span>Launch</span>
<svg class="checkmark" viewBox="0 0 52 52">
<path fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8"/>
</svg>
</button>
</form>
The answer to you question is pretty easy,
just create a class say animating and write the code:
.animating{
animation: animation-name 1s 1;
}
and then go to javascript file and add the lines as required with some changes:
//let the element to be animated have id = 'input1'
document.getElementById('input1').classList.add('animating');//to add animation
//or
document.getElementById('input1').classList.remove('animating');//to remove animation
well, apart from the fact that you are visibly annoyed with the indentation and that it makes reading your code painful, the first problem with your code is that you do not use any name attributes in your form, whereas those- these are essential because they are the reference used on the data sent to the server
They are also very useful in JS, because they also serve as a direct reference in forms
<form name="my-form-name" id="my-form-id" ....
<input name="namecontact" type="text" placeholder="Name" />
javascript use:
const myForm = document.forms['my-form-name']
// or myForm = document.querySelector("#my-form-id")
// usage
function checkInputs()
{
const nameValue = myForm.namecontact.value.trim()
// | |
// | name attribute
// |
// form element
// ...
myForm.onsubmit = e =>
{
e.preventDefault()
checkInputs()
showSucces()
}
I need to format a 10 digit string to this format: '(123) 456-7890'.
However, I need this to happen as the user types. So if the user has inputted only 3 digits, the input should display: '(123)'.
If they've inputted 5 digits the input should display: '(123) 45'
With my current code, the formatting only takes place after the 10th character is entered. I'd like it so that it formats it from the third character onwards.
const phoneRegex = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/
const handleInput = (value) => {
return (
value.replace(phoneRegex, '($1) $2-$3')
)
}
class FindASubscriber extends React.Component {
constructor(props) {
super(props)
this.state = {
value: ''
}
}
render() {
const { label, placeholder, feedback } = this.props
const { value} = this.state
return (
<div className="find__a__subscriber">
<FlexGrid>
<FlexGrid.Col>
<FlexGrid.Row>
<Input
feedback={feedback}
label={label}
type="text"
pattern="[0-9]*"
placeholder={placeholder}
value={handleInput(value)}
maxLength="10"
onChange={
(event) => this.setState({value: event.target.value})
}
/>
</FlexGrid.Row>
</FlexGrid.Col>
</FlexGrid>
</div>
)
}
}```
You can normalize the input like so
the value is up-to-date in relation to event.target.value
previousValue is what has already been validated and set to state
This is structured in a way to prevent invalid characters from updating the input and also limits the input to 10 numbers.
Click the Run code snippet button below for a working example.
const normalizeInput = (value, previousValue) => {
// return nothing if no value
if (!value) return value;
// only allows 0-9 inputs
const currentValue = value.replace(/[^\d]/g, '');
const cvLength = currentValue.length;
if (!previousValue || value.length > previousValue.length) {
// returns: "x", "xx", "xxx"
if (cvLength < 4) return currentValue;
// returns: "(xxx)", "(xxx) x", "(xxx) xx", "(xxx) xxx",
if (cvLength < 7) return `(${currentValue.slice(0, 3)}) ${currentValue.slice(3)}`;
// returns: "(xxx) xxx-", (xxx) xxx-x", "(xxx) xxx-xx", "(xxx) xxx-xxx", "(xxx) xxx-xxxx"
return `(${currentValue.slice(0, 3)}) ${currentValue.slice(3, 6)}-${currentValue.slice(6, 10)}`;
}
};
const normalizeInput = (value, previousValue) => {
if (!value) return value;
const currentValue = value.replace(/[^\d]/g, '');
const cvLength = currentValue.length;
if (!previousValue || value.length > previousValue.length) {
if (cvLength < 4) return currentValue;
if (cvLength < 7) return `(${currentValue.slice(0, 3)}) ${currentValue.slice(3)}`;
return `(${currentValue.slice(0, 3)}) ${currentValue.slice(3, 6)}-${currentValue.slice(6, 10)}`;
}
};
const validateInput = value => {
let error = ""
if (!value) error = "Required!"
else if (value.length !== 14) error = "Invalid phone format. ex: (555) 555-5555";
return error;
};
class Form extends React.Component {
constructor() {
super();
this.state = { phone: "", error: "" };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleReset = this.handleReset.bind(this);
}
handleChange({ target: { value } }) {
this.setState(prevState=> ({ phone: normalizeInput(value, prevState.phone) }));
};
handleSubmit(e) {
e.preventDefault();
const error = validateInput(this.state.phone);
this.setState({ error }, () => {
if(!error) {
setTimeout(() => {
alert(JSON.stringify(this.state, null, 4));
}, 300)
}
});
}
handleReset() {
this.setState({ phone: "", error: "" });
};
render() {
return(
<form className="form" onSubmit={this.handleSubmit}>
<div className="input-container">
<p className="label">Phone:</p>
<input
className="input"
type="text"
name="phone"
placeholder="(xxx) xxx-xxxx"
value={this.state.phone}
onChange={this.handleChange}
/>
{this.state.error && <p className="error">{this.state.error}</p>}
</div>
<div className="btn-container">
<button
className="btn danger"
type="button"
onClick={this.handleReset}
>
Reset
</button>
<button className="btn primary" type="submit">Submit</button>
</div>
</form>
);
}
}
ReactDOM.render(
<Form />,
document.getElementById('root')
);
html {
font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";
font-size: 16px;
font-weight: 400;
line-height: 1.5;
-webkit-text-size-adjust: 100%;
background: #fff;
color: #666;
}
.btn {
color: #fff;
border: 1px solid transparent;
margin: 0 10px;
cursor: pointer;
text-align: center;
box-sizing: border-box;
padding: 0 30px;
vertical-align: middle;
font-size: .875rem;
line-height: 38px;
text-align: center;
text-decoration: none;
text-transform: uppercase;
transition: .1s ease-in-out;
transition-property: color,background-color,border-color;
}
.btn:focus {
outline: 0;
}
.btn-container {
text-align: center;
margin-top: 10px;
}
.form {
width: 550px;
margin: 0 auto;
}
.danger {
background-color: #f0506e;
color: #fff;
border: 1px solid transparent;
}
.danger:hover {
background-color: #ee395b;
color: #fff;
}
.error {
margin: 0;
margin-top: -20px;
padding-left: 26%;
color: red;
text-align: left;
}
.input {
display: inline-block;
height: 40px;
font-size: 16px;
width: 70%;
padding: 0 10px;
background: #fff;
color: #666;
border: 1px solid #e5e5e5;
transition: .2s ease-in-out;
transition-property: color,background-color,border;
}
.input-container {
width: 100%;
height: 60px;
margin-bottom: 20px;
display: inline-block;
}
.label {
width: 25%;
padding-top: 8px;
display: inline-block;
text-align: center;
text-transform: uppercase;
font-weight: bold;
height: 34px;
border-top-left-radius: 4px;
border-bottom-left-radius: 4px;
background: rgb(238, 238, 238);
}
.primary {
background-color: #1e87f0;
}
.primary:hover {
background-color: #0f7ae5;
color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id='root'>
</div>
Or... have 3 separate inputs and combine them when done.
const validateInput = value => {
let error = ""
if (!value) error = "Required!"
else if (value.length !== 14) error = "Invalid phone format. ex: (555) 555-5555";
return error;
};
const initialState = {
areaCode: "",
prefix: "",
suffix: "",
error: ""
};
class Form extends React.Component {
constructor() {
super();
this.state = initialState;
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleReset = this.handleReset.bind(this);
this.setInputRef = this.setInputRef.bind(this);
}
handleChange({ target: { name, value } }) {
let valueChanged = false;
this.setState(prevState => {
const nextValue = value.replace(/[^\d]/g, '');
const changedValue = prevState[name];
if (changedValue.length !== nextValue.length) valueChanged = true;
return { [name]: nextValue }
}, () => {
if(valueChanged) this.handleFocus(name)
});
};
setInputRef(name, element) {
this[name] = element;
}
handleFocus(name){
const { areaCode, prefix, suffix } = this.state;
const areaCodeFilled = areaCode.length === 3;
const prefixFilled = prefix.length === 3;
if(areaCodeFilled && name === "areaCode") {
this.prefix.focus();
this.prefix.selectionEnd = 0;
} else if(prefixFilled && name === "prefix") {
this.suffix.focus();
this.suffix.selectionEnd = 0;
}
}
handleSubmit(e) {
e.preventDefault();
const { areaCode, prefix, suffix } = this.state;
const phoneNumber = `(${areaCode}) ${prefix}-${suffix}`
const error = validateInput(phoneNumber);
this.setState({ error }, () => {
if(!error) {
setTimeout(() => {
alert(phoneNumber);
}, 300)
}
});
}
handleReset() {
this.setState(initialState);
};
render() {
return(
<form className="form" onSubmit={this.handleSubmit}>
<div className="input-container">
<div className="label">
Phone:
</div>
<div className="parenthesis" style={{ marginLeft: 10, marginRight: 2}}>(</div>
<input
className="input area-code"
type="text"
name="areaCode"
placeholder="xxx"
value={this.state.areaCode}
onChange={this.handleChange}
maxLength="3"
/>
<div className="parenthesis" style={{ marginRight: 2}}>)</div>
<input
ref={node => this.setInputRef("prefix", node)}
className="input prefix"
type="text"
name="prefix"
placeholder="xxx"
value={this.state.prefix}
onChange={this.handleChange}
maxLength="3"
/>
<div className="dash">-</div>
<input
ref={node => this.setInputRef("suffix", node)}
className="input suffix"
type="text"
name="suffix"
placeholder="xxxx"
value={this.state.suffix}
onChange={this.handleChange}
maxLength="4"
/>
</div>
<p className="error">{this.state.error}</p>
<div className="btn-container">
<button
className="btn danger"
type="button"
onClick={this.handleReset}
>
Reset
</button>
<button className="btn primary" type="submit">Submit</button>
</div>
</form>
);
}
}
ReactDOM.render(
<Form />,
document.getElementById('root')
);
html {
font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";
font-size: 16px;
font-weight: 400;
line-height: 1.5;
-webkit-text-size-adjust: 100%;
background: #fff;
color: #666;
}
.btn {
color: #fff;
border: 1px solid transparent;
margin: 0 10px;
cursor: pointer;
text-align: center;
box-sizing: border-box;
padding: 0 30px;
vertical-align: middle;
font-size: .875rem;
line-height: 38px;
text-align: center;
text-decoration: none;
text-transform: uppercase;
transition: .1s ease-in-out;
transition-property: color,background-color,border-color;
}
.btn:focus {
outline: 0;
}
.btn-container {
text-align: center;
margin-top: 10px;
}
.form {
width: 550px;
margin: 0 auto;
}
.danger {
background-color: #f0506e;
color: #fff;
border: 1px solid transparent;
}
.danger:hover {
background-color: #ee395b;
color: #fff;
}
.error {
margin: 0;
height: 24px;
margin-top: -20px;
padding-left: 26%;
color: red;
text-align: right;
}
.input {
display: flex;
height: 40px;
font-size: 16px;
width: 33%;
padding: 0 3px;
background: #fff;
color: #666;
outline: none;
border: 0;
}
.area-code,.prefix {
width: 27px;
}
.suffix {
width: 38px;
}
.dash,.parenthesis {
display: flex;
}
.input-container {
width: 100%;
margin-bottom: 20px;
display: flex;
flex-direction: row;
align-items: center;
border-top-left-radius: 4px;
border-bottom-left-radius: 4px;
border: 1px solid #e5e5e5;
transition: .2s ease-in-out;
transition-property: color,background-color,borde
}
.label {
height: 100%;
background: rgb(238, 238, 238);
width: 25%;
padding-top: 8px;
display: flex;
text-transform: uppercase;
justify-content: space-around;
font-weight: bold;
height: 34px;
}
.primary {
background-color: #1e87f0;
}
.primary:hover {
background-color: #0f7ae5;
color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id='root'>
</div>
It's all about formatting. Any key that prints a character
should cause a rewrite of the input field.
This way the user only sees valid formatted field, no matter what he does.
The regex is simple ^\D*(\d{0,3})\D*(\d{0,3})\D*(\d{0,4})
function getFormattedPhoneNum( input ) {
let output = "(";
input.replace( /^\D*(\d{0,3})\D*(\d{0,3})\D*(\d{0,4})/, function( match, g1, g2, g3 )
{
if ( g1.length ) {
output += g1;
if ( g1.length == 3 ) {
output += ")";
if ( g2.length ) {
output += " " + g2;
if ( g2.length == 3 ) {
output += " - ";
if ( g3.length ) {
output += g3;
}
}
}
}
}
}
);
return output;
}
console.log( getFormattedPhoneNum("") );
console.log( getFormattedPhoneNum("2") );
console.log( getFormattedPhoneNum("asdf20as3d") );
console.log( getFormattedPhoneNum("203") );
console.log( getFormattedPhoneNum("203-44") );
console.log( getFormattedPhoneNum("444sg52asdf22fd44gs") );
console.log( getFormattedPhoneNum("444sg526sdf22fd44gs") );
console.log( getFormattedPhoneNum("444sg526sdf2244gs") );
console.log( getFormattedPhoneNum(" ra098 848 73653k-atui ") );
You could even get fancier and show underscores where a character
should be at any given time.
Like
(___) ___ - ____
(20_) ___ - ____
(123) 456 - ____
etc... (let me know if you want this)
Your current code's regex only matches when ten digits are entered (3, 3, then 4). You could update the regex to accept a range of digits, such as:
^\(?([0-9]{0,3})\)?[-. ]?([0-9]{0,3})[-. ]?([0-9]{0,4})$
Or you could have the regex simply make sure that 0-10 digits are entered ([0-9]{0,10}) and then split the string yourself into substrings of length 3, 3, and 4. Doing it the latter way seems better since you only want to show certain characters depending on how many digits the user has entered:
1 -> (1
123 -> (123)
1234567 -> (123) 456-7
1234567890 -> (123) 456-7890
You would have to handle each of these cases which a simple replace won't do.
I have used this library: https://www.npmjs.com/package/libphonenumber-js it has a AsYouType function, that you can use on your inputs
perhaps, something as the following will work for someone:
onChange={(e) => {
if (e.target.value.length < 13) {
var cleaned = ("" + e.target.value).replace(/\D/g, "");
let normValue = `${cleaned.substring(0, 3)}${
cleaned.length > 3 ? "-" : ""
}${cleaned.substring(3, 6)}${
cleaned.length > 6 ? "-" : ""
}${cleaned.substring(6, 11)}`;
handleChange(normValue);
}
}}
Use this package https://www.npmjs.com/package/react-number-formatter
this input component formats number and returns just number.
I'm working on form validation. Everything is working fine what I actually want is I want to add some more input fields like checkbox, radio button, select and textarea, upload file and like so into the form I want them to be validated as well.
I got the email input error working but it is not working correctly as it should validate the email first and then it should remove the error message but it is removing the error message just after entering few characters.
I want the phone number to be validated. Like the user should enter 10 numeric digits that is in India if in another country that will differ I am a bit confused how to do it.
I want a success message to pop up when all the fields are correctly validated as they should. what I tried is this:
$('.success_msg').fadeIn().delay(3000).fadeOut();
$('input , textarea , select').val('').removeClass('valid');
event.preventDefault();
I want all the fields to be cleared when all the validations are done and the success message is sent.
Can anyone point me in the right direction?
var Validator = function(formObject) {
this.form = $(formObject);
var Elements = {
name: {
reg: /^[a-zA-Z]{2,20}$/,
error: "Not a valid name.",
},
email: {
reg: /^[a-z-0-9_+.-]+\#([a-z0-9-]+\.)+[a-z0-9]{2,7}$/i,
error: "Not a valid e-mail address.",
},
phone: {
reg: /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/,
error: "Not a valid number.",
},
message: {
reg: /^(?!\s*$).+/,
error: "Message field cannot be empty.",
},
};
var handleError = function(element, message) {
element.addClass('input-error');
var $err_msg = element.parent('div');
$err_msg.find('.error').remove();
var error = $('<div class="error"></div>').text(message);
error.appendTo($err_msg);
element.keyup(function() {
$(error).fadeOut(1000, function() {
element.removeClass('input-error');
});
});
};
this.validate = function() {
var errorCount = 0;
this.form.find("input, textarea").each(function(index, field) {
var type = $(field).data("validation");
var validation = Elements[type];
if (validation) {
if (!validation.reg.test($(field).val())) {
errorCount++;
handleError($(field), validation.error);
}
}
})
return errorCount == 0;
};
};
$(function() {
$("form#test").on("submit", function(event) {
//event.preventDefault();
return new Validator(this).validate(); // "this" here refers to the form
})
})
body {
background: #fff;
color: #333;
font: 76% Verdana, sans-serif;
}
form {
margin: 1em 0 0 2em;
width: 90%;
}
fieldset {
margin: 0;
border: 1px solid #ccc;
padding-bottom: 1em;
}
legend {
font-weight: bold;
text-transform: uppercase;
}
label {
float: left;
width: 5em;
padding-right: 2em;
font-weight: bold;
}
div {
margin-bottom: 30px;
}
input {
font: 1em Verdana, sans-serif;
}
fieldset ul li input {
float: left;
width: 120px;
border: 1px solid #ccc;
}
textarea {
width: 300px;
height: 200px;
border: 1px solid #ccc;
font: 1em Verdana, sans-serif;
}
form p {
margin: 0;
padding: 0.4em 0 0 7em;
}
form p input {
background: #666;
color: #fff;
font-weight: bold;
}
div.error {
clear: left;
margin-left: 5.3em;
color: red;
padding-right: 1.3em;
height: 100%;
padding-bottom: 0.3em;
line-height: 1.3;
}
.input-error {
background: #ff9;
border: 1px solid red;
}
.success_msg {
width: 350px;
line-height: 40px;
border: 1px solid green;
border-radius: 5px;
background-color: rgba(213, 255, 187, 0.7);
display: none;
position: absolute;
bottom: 5px;
left: 50%;
transform: translateX(-50%);
z-index: 999;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post" id="test">
<fieldset>
<legend>Contact information</legend>
<div>
<label for="firstname">Firstname:</label>
<input type="text" name="firstname" id="firstname" data-validation="name" />
</div>
<div>
<label for="lastname">Lastname:</label>
<input type="text" name="lastname" id="lastname" data-validation="name" />
</div>
<div>
<label for="email">Email:</label>
<input type="email" name="email" id="email" data-validation="email" />
</div>
<div>
<label for="phone">phone</label>
<input type="number" name="phone" id="phone" data-validation="phone" />
</div>
<div>
<label>Gender:</label>
<input type="radio" name="gender" value="male" data-validation="gender" />
<input type="radio" name="gender" value="female" data-validation="gender">
</div>
<div>
<label>select</label>
<input type="checkbox" name="checkbox" id="checkbox1" value="demo1" data-validation="checkbox" />
<input type="checkbox" name="checkbox" id="checkbox2" value="demo2" data-validation="checkbox" />
<input type="checkbox" name="checkbox" id="checkbox3" value="demo3" ata-validation="checkbox" />
</div>
<select data-validation="selectOption">
<option value="">Select any option</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>
<div>
<label>Upload:</label>
<input type="file" name="file" id="file" data-validation="file" />
</div>
<div>
<label for="message">Message:</label>
<textarea id="message" name="message" cols="30" rows="15" data-validation="message"></textarea>
</div>
<p><input type="submit" name="send" id="send" value="Send" /></p>
</fieldset>
<div class="success_msg">
<p>Form submitted Successfully</p>
</div>
</form>
Please feel free to clear your doubts before you invest your time answering the question.
Here is the working code:
https://jsfiddle.net/bhumi/o2gxgz9r/47570/
I have changed selector to use id
You need to use loop in handle error:
var Validator = function(form) {
this.form = $(form);
var Elements = {
name: {
selector: $('input[type=text]'),
reg: /^[a-zA-Z]{2,20}$/
},
email: {
selector: $('input[type=email]'),
reg: /^[a-z-0-9_+.-]+\#([a-z0-9-]+\.)+[a-z0-9]{2,7}$/i
},
message: {
selector: $('textarea'),
reg: /^\s+$/
}
};
var handleError = function(element, message, v1) {
if (v1.selector.length > 1) {
var ss = v1.selector;
$(ss).each(function(i, v) {
$(v).removeClass('input-error');
if($(v).val() == ''){
$(v).addClass('input-error');
var $err_msg = $(v).parent('div');
if($(v).parent('div').find('.error').length == 0) {
var error = $('<div class="error"></div>').text(message);
}else{
$(v).parent('div').find('.error').text('');
var error = $(v).parent('div').find('.error').text(message);
$(this).siblings('.error').show();
}
error.appendTo($err_msg);
}else{
$(v).siblings('.error').text('')
}
$(v).keyup(function() {
$(error).fadeOut(1000, function() {
element.removeClass('input-error');
});
});
});
} else {
element.addClass('input-error');
var $err_msg = element.parent('div');
if(element.parent('div').find('.error').length == 0) {
var error = $('<div class="error"></div>').text(message);
}else{
element.parent('div').find('.error').text('');
var error = element.parent('div').find('.error').text(message);
$(this).siblings('.error').show();
}
error.appendTo($err_msg);
element.keyup(function() {
$(error).fadeOut(1000, function() {
element.removeClass('input-error');
});
});
}
};
this.validate = function() {
this.form.submit(function(e) {
for (var i in Elements) {
var type = i;
var validation = Elements[i];
switch (type) {
case 'name':
if (!validation.reg.test(validation.selector.val())) {
handleError(validation.selector, 'Not a valid name.', validation);
}
break;
case 'email':
if (!validation.reg.test(validation.selector.val())) {
handleError(validation.selector, 'Not a valid e-mail address.', validation);
}
break;
case 'message':
if (validation.reg.test(validation.selector.val()) || validation.selector.val() == '') {
handleError(validation.selector, 'Message field cannot be empty.', validation);
}
break;
default:
break;
}
}
e.preventDefault();
});
};
};
var validator = new Validator('#test');
validator.validate();
I hope this is what you were trying to achieve. This took longer than expected but I tried to achieve it. This whole form is custom form. You could have used the existing plugins to achieve it. Any which ways it took much time to figure it out. Consider the question as most of things are working, ignore if something's not what you want.
$(document).ready(function() {
/* contact form validation */
var Validator = function(formObject) {
this.form = $(formObject);
var Elements = {
name: {
reg: /^[a-zA-Z ]{2,20}$/,
require: true,
error: "Not a valid name.",
},
email: {
reg: /^[a-z-0-9_+.-]+\#([a-z0-9-]+\.)+[a-z0-9]{2,7}$/i,
error: "Not a valid e-mail address.",
},
phone: {
reg: /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/,
error: "Not a valid number.",
},
message: {
reg: /^(?!\s*$).+/,
error: "Message field cannot be empty.",
},
gender: {
error: "gender is required",
},
selectOption: {
error: "this field is required",
required: true
}
};
var handleError = function(element, message) {
element.addClass('input-error');
var $err_msg = element.parent('div');
$err_msg.find('.error').remove();
var error = $('<div class="error"></div>').text(message);
error.appendTo($err_msg);
console.log(element);
element.on('keypress change', function() {
$(error).fadeOut(1000, function() {
console.log(element);
element.removeClass('input-error');
});
});
};
/* Select Option */
this.validate = function() {
var errorCount = 0;
this.form.find("select").each(function(index, field) {
var type = $(field).data("validation");
var validation = Elements[type];
if ($(field).val() == "") {
errorCount++;
handleError($(field), validation.error);
}
});
this.form.find("input, textarea").each(function(index, field) {
var type = $(field).data("validation");
var validation = Elements[type];
if (validation !== undefined) {
var re = new RegExp(validation.reg);
if (validation) {
if (!re.test($(field).val())) {
errorCount++;
handleError($(field), validation.error);
}
}
}
})
/* Radio button */
var radioList = $('input:radio');
var radioNameList = new Array();
var radioUniqueNameList = new Array();
var notCompleted = 0;
for (var i = 0; i < radioList.length; i++) {
radioNameList.push(radioList[i].name);
}
radioUniqueNameList = jQuery.unique(radioNameList);
console.log(radioUniqueNameList);
for (var i = 0; i < radioUniqueNameList.length; i++) {
var field = $('#' + radioUniqueNameList[i]);
var type = field.data("validation");
var validation = Elements[type];
if ($('input[name=' + type + ']:checked', '#test').val() == undefined) {
errorCount++;
handleError($(field), validation.error);
}
}
return errorCount == 0;
};
};
/* Submit form*/
$(function() {
$("form#test").on('submit', function(e) {
var NoErrors = new Validator(this).validate();
if (NoErrors == true) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function() {
// AJAX request finished, handle the results and error msg
$('.success_msg').fadeIn().delay(3000).fadeOut();
$('input[type!="submit"], textarea').val('').removeClass('error');
}
});
}
return false;
})
})
});
body {
background: #fff;
color: #333;
font: 76% Verdana, sans-serif;
}
form {
margin: 1em 0 0 2em;
width: 90%;
}
fieldset {
margin: 0;
border: 1px solid #ccc;
padding-bottom: 1em;
}
legend {
font-weight: bold;
text-transform: uppercase;
}
label {
float: left;
width: 5em;
padding-right: 2em;
font-weight: bold;
}
div {
margin-bottom: 30px;
}
input {
font: 1em Verdana, sans-serif;
}
fieldset ul li input {
float: left;
width: 120px;
border: 1px solid #ccc;
}
textarea {
width: 300px;
height: 200px;
border: 1px solid #ccc;
font: 1em Verdana, sans-serif;
}
form p {
margin: 0;
padding: 0.4em 0 0 7em;
}
form p input {
background: #666;
color: #fff;
font-weight: bold;
}
div.error {
clear: left;
margin-left: 5.3em;
color: red;
padding-right: 1.3em;
height: 100%;
padding-bottom: 0.3em;
line-height: 1.3;
}
.input-error {
background: #ff9;
border: 1px solid red;
}
.success_msg {
width: 350px;
line-height: 40px;
border: 1px solid green;
border-radius: 5px;
background-color: rgba(213, 255, 187, 0.7);
display: none;
position: absolute;
bottom: 5px;
left: 50%;
transform: translateX(-50%);
z-index: 999;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form action="#" method="post" id="test">
<fieldset>
<legend>Contact information</legend>
<div>
<label for="firstname">Firstname:</label>
<input type="text" name="firstname" id="firstname" data-validation="name" />
</div>
<div>
<label for="lastname">Lastname:</label>
<input type="text" name="lastname" id="lastname" data-validation="name" />
</div>
<div>
<label for="email">Email:</label>
<input type="email" name="email" id="email" data-validation="email" />
</div>
<div>
<label for="phone">phone</label>
<input type="number" name="phone" id="phone" data-validation="phone" />
</div>
<div>
<label>Gender:</label>
<input type="radio" name="gender" value="male" data-validation="gender" />
<input type="radio" name="gender" value="female" data-validation="gender">
</div>
<select data-validation="selectOption">
<option value="">Select any option</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>
<div>
<label for="message">Message:</label>
<textarea id="message" name="message" cols="30" rows="15" data-validation="message"></textarea>
</div>
<p><input type="submit" name="send" id="send" value="Send" /></p>
</fieldset>
<div class="success_msg">
<p>Form submitted Successfully</p>
</div>
</form>
I'd like to build a password prompt screen that redirects you somewhere after entering the correct password and pressing Enter. However, currently it only works by clicking the "Submit" button. I'd appreciate any help on how to adapt this code:
Here's what my code looks like for now:
function checkPswd() {
var confirmPassword = "asdf";
var password = document.getElementById("pswd").value;
if (password == confirmPassword) {
window.location.replace('http://www.google.com');
}
}
#import url('https://fonts.googleapis.com/css?family=VT323');
body {
background-color: #ffffff;
display: table;
}
.div1 {
height: 100%;
width: 100%;
display: table;
position: absolute;
top: 0;
left: 0;
}
.div2 {
text-align: center;
display: table-cell;
vertical-align: middle;
font-family: VT323;
font-size: 25px;
color: #656262;
}
.box {
text-align: center;
font-size: 20px;
font-family: VT323;
outline: none;
width: 250px;
height: 35px;
border: none;
border-bottom: 2px solid #656262;
}
.confirm {
border: none;
font-size: 20px;
font-family: VT323;
margin-top: 10px;
color: #656262;
background-color: rgba(0, 0, 0, 0);
cursor: pointer;
}
<div class="div1">
<div class="div2">
<form>
<input class="box" type="password" placeholder="123" id="pswd">
<br>
<input class="confirm" type="button" value="SUBMIT" onclick="checkPswd();" />
</form>
</div>
</div>
You can use the keyup event to detect when a key is pressed and then check if its code is 13, the code of Enter. If so, you can submit your form, or in your case call checkPswd.
Code:
/* Cache the password input. */
var pswd = document.getElementById("pswd");
/* Call 'checkPswd' when the 'Enter' key is released. */
pswd.onkeyup = function (e) {
if (e.which == 13) checkPswd();
};
/* Prevent the form from submitting. */
pswd.parentElement.onsubmit = function () {
return false;
};