First of all, I'm new to website creation and especially to php.
I have created a contact form for my website with a validation and a message that is displayed if everything is filled in correctly (see the snippet below). I know that the validation has to be done on both the client and server side, but I know that I am dealing with something else.
I have created a php file that works: I get the email when the user clicks submit.
I am faced with two things.
How do I keep the javascript validation and the message on the front end?
How do I configure the php to stay on the page, or better yet, run in the back and only submit the form to my email?
<?php
if(isset($_POST['submit'])){
$mailto = "contact#statsmap.ch"; //Send the email to this adress
//All the inputs informations
$mailfrom = $_POST['email'];
$name = $_POST['name'];
$subject = $_POST['subject'];
//$message = "NAME: " .$name. "\r\n\n". "Wrote the following Message:" ."\r\n". $_POST['message'];
$message = $_POST['message'];
$headers = "From: ". $mailfrom;
$sendMail = mail($mailto, $subject, $message, $headers); // Send mail to website owner
}
?>
const form = document.getElementById('formContact');
const nameContact = document.getElementById('name');
const emailContact = document.getElementById('email');
const messageContact = document.getElementById('message');
const headerContact = document.querySelector('.headerContact')
const thankYou = document.querySelector('.Thankyou');
const isValidEmail = (email) => {
const re = /^(([^<>()\[\]\\.,;:\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,}))$/;
return re.test(String(email).toLowerCase());
};
let isValid = true;
function checkInputs(){
//get the values from the inputs or textarea
const nameValue = nameContact.value.trim();
const emailValue = emailContact.value.trim();
const messageValue = messageContact.value.trim();
if (nameValue === ''){
//show error
//add error class
setErrorFor(nameContact, 'Name cannot be blank');
} else{
//add success class
setSuccesFor(nameContact);
}
if (emailValue === ''){
//show error
//add error class
setErrorFor(emailContact, 'Email cannot be blank');
} else if(!isValidEmail(emailValue)){
setErrorFor(emailContact, 'Please add a valid email adress');
} else{
setSuccesFor(emailContact);
}
if (messageValue === ''){
//show error
//add error class
setErrorFor(messageContact, 'Message cannot be blank');
} else if (messageValue.length < 20){
setErrorFor(messageContact, 'Message need to be at least 20 characters');
}
else{
//add success class
setSuccesFor(messageContact);
}
}
function setErrorFor(input, message){
isValid=false;
const formControl = input.parentElement;
const errorContactMessage = formControl.querySelector('#Error');
//add error message inside the span
errorContactMessage.innerText = message;
//add error class
formControl.className = 'form-control error';
}
function setSuccesFor(input){
const formControl = input.parentElement;
const errorContactMessage = formControl.querySelector('#Error');
//remove message inside the span
errorContactMessage.innerText='';
//add success class
formControl.className = 'form-control success';
}
let nameThk = "";
nameContact.addEventListener('input', (e) =>{
nameThk = e.target.value;
});
form.addEventListener('submit', () =>{
checkInputs();
if(isValid){
form.remove();
headerContact.classList.add('hide');
thankYou.classList.remove('hide');
document.querySelector('#merci').innerHTML = `<h3>Dear ${nameThk}, thank you for reaching out ! </h3>`;
}
});
.containerContact {
background-color: #F8F8F8;
width: 100%;
max-width: 100%;
padding: 0.5rem;
display: block;
}
.containerContact h2 {
margin-bottom: 0.5rem;
}
.form-control {
margin-bottom: 0.25rem;
position: relative;
}
.form-control input {
display: block;
width: 100%;
height: 2rem;
padding-left: 0.5rem;
background: transparent;
border: 0.025rem solid #000000;
outline: none;
font-size: 0.8125rem;
color: #000000;
}
.form-control input::-webkit-input-placeholder {
color: #000000;
}
.form-control input:-ms-input-placeholder {
color: #000000;
}
.form-control input::-ms-input-placeholder {
color: #000000;
}
.form-control input::placeholder {
color: #000000;
}
.form-control textarea {
width: 100%;
height: 10rem;
background: transparent;
border: 0.025rem solid #000000;
outline: none;
font-family: Arial, Helvetica, sans-serif;
padding: 0.5rem;
font-size: 0.8125rem;
color: #000000;
resize: none;
}
.form-control textarea::-webkit-input-placeholder {
color: #000000;
}
.form-control textarea:-ms-input-placeholder {
color: #000000;
}
.form-control textarea::-ms-input-placeholder {
color: #000000;
}
.form-control textarea::placeholder {
color: #000000;
}
.form-control i {
position: absolute;
top: 0.5rem;
right: 0.5rem;
visibility: hidden;
}
.form-control #textareaChecks {
position: absolute;
top: 8.5rem;
right: 0.5rem;
}
.form-control.success input {
border-color: green;
}
.form-control.success i.fa-check-circle {
visibility: visible;
color: green;
}
.form-control.error input {
border-color: red;
}
.form-control.error i.fa-exclamation-circle {
visibility: visible;
color: red;
}
.form-control.success textarea {
border-color: green;
}
.form-control.success i.fa-check-circle {
visibility: visible;
color: green;
}
.form-control.error textarea {
border-color: red;
}
.form-control.error i.fa-exclamation-circle {
visibility: visible;
color: red;
}
#Error {
font-weight: 500;
font-size: 0.75rem;
font-style: italic;
color: red;
margin: 0;
padding: 0;
}
#ContactSubmit {
width: 100%;
height: 2rem;
background: #1e1e1e;
outline: none;
border: 0.025rem solid #000000;
color: #FFFFFF;
}
.containerThank {
height: 300px;
display: -ms-grid;
display: grid;
}
.containerThank h3 {
margin: 0;
text-align: center;
-ms-flex-item-align: end;
align-self: flex-end;
font-size: 18px;
font-weight: bold;
}
.containerThank p {
-ms-flex-item-align: start;
align-self: flex-start;
text-align: center;
font-size: 13px;
padding-top: 0.5rem;
}
.hide {
display: none;
}
<form action="/php/contactMail.php" method="POST" class="formContact" id="formContact" novalidate>
<div class="form-control">
<input type="text" name="name" id="name" placeholder="First and Last name">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<span id="Error"></span>
</div>
<div class="form-control">
<input type="email" name="email" id="email" placeholder="Please enter your email">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<span id="Error"></span>
</div>
<div class="form-control">
<input type="text" name="subject" id="subject" placeholder="Subject">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<span id="Error"></span>
</div>
<div class="form-control">
<textarea id="message" name="message" type="text" placeholder="Message"></textarea>
<i id="textareaChecks" class="fas fa-check-circle"></i>
<i id="textareaChecks" class="fas fa-exclamation-circle"></i>
<span id="Error"></span>
</div>
<button id="ContactSubmit" name="submit">Submit</button>
</form>
<div class="Thankyou hide">
<div class="containerThank">
<h3 id="merci"></h3>
<p>Our team is going to get back to you as soon as possible</p>
</div>
</div>
</div>
</div>
</section>
</div>
Looks like you checked the variable isValid for it to be true, but you didn't provide an alternative if isValid is false.
Basically, I edited this:
form.addEventListener('submit', (e) =>{
checkInputs();
if(isValid){
form.remove();
headerContact.classList.add('hide');
thankYou.classList.remove('hide');
document.querySelector('#merci').innerHTML = `<h3>Dear ${nameThk}, thank you for reaching out ! </h3>`;
} else {
e.preventDefault()
}
As you can see, if isValid is false, the script prevents the form from submitting.
Working snippet:
const form = document.getElementById('formContact');
const nameContact = document.getElementById('name');
const emailContact = document.getElementById('email');
const messageContact = document.getElementById('message');
const headerContact = document.querySelector('.headerContact')
const thankYou = document.querySelector('.Thankyou');
const isValidEmail = (email) => {
const re = /^(([^<>()\[\]\\.,;:\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,}))$/;
return re.test(String(email).toLowerCase());
};
let isValid = true;
function checkInputs(){
//get the values from the inputs or textarea
const nameValue = nameContact.value.trim();
const emailValue = emailContact.value.trim();
const messageValue = messageContact.value.trim();
if (nameValue === ''){
//show error
//add error class
setErrorFor(nameContact, 'Name cannot be blank');
} else{
//add success class
setSuccesFor(nameContact);
}
if (emailValue === ''){
//show error
//add error class
setErrorFor(emailContact, 'Email cannot be blank');
} else if(!isValidEmail(emailValue)){
setErrorFor(emailContact, 'Please add a valid email adress');
} else{
setSuccesFor(emailContact);
}
if (messageValue === ''){
//show error
//add error class
setErrorFor(messageContact, 'Message cannot be blank');
} else if (messageValue.length < 20){
setErrorFor(messageContact, 'Message need to be at least 20 characters');
}
else{
//add success class
setSuccesFor(messageContact);
}
}
function setErrorFor(input, message){
isValid=false;
const formControl = input.parentElement;
const errorContactMessage = formControl.querySelector('#Error');
//add error message inside the span
errorContactMessage.innerText = message;
//add error class
formControl.className = 'form-control error';
}
function setSuccesFor(input){
const formControl = input.parentElement;
const errorContactMessage = formControl.querySelector('#Error');
//remove message inside the span
errorContactMessage.innerText='';
//add success class
formControl.className = 'form-control success';
}
let nameThk = "";
nameContact.addEventListener('input', (e) =>{
nameThk = e.target.value;
});
form.addEventListener('submit', (e) =>{
checkInputs();
if(isValid){
form.remove();
headerContact.classList.add('hide');
thankYou.classList.remove('hide');
document.querySelector('#merci').innerHTML = `<h3>Dear ${nameThk}, thank you for reaching out ! </h3>`;
} else {
e.preventDefault()
}
});
.containerContact {
background-color: #F8F8F8;
width: 100%;
max-width: 100%;
padding: 0.5rem;
display: block;
}
.containerContact h2 {
margin-bottom: 0.5rem;
}
.form-control {
margin-bottom: 0.25rem;
position: relative;
}
.form-control input {
display: block;
width: 100%;
height: 2rem;
padding-left: 0.5rem;
background: transparent;
border: 0.025rem solid #000000;
outline: none;
font-size: 0.8125rem;
color: #000000;
}
.form-control input::-webkit-input-placeholder {
color: #000000;
}
.form-control input:-ms-input-placeholder {
color: #000000;
}
.form-control input::-ms-input-placeholder {
color: #000000;
}
.form-control input::placeholder {
color: #000000;
}
.form-control textarea {
width: 100%;
height: 10rem;
background: transparent;
border: 0.025rem solid #000000;
outline: none;
font-family: Arial, Helvetica, sans-serif;
padding: 0.5rem;
font-size: 0.8125rem;
color: #000000;
resize: none;
}
.form-control textarea::-webkit-input-placeholder {
color: #000000;
}
.form-control textarea:-ms-input-placeholder {
color: #000000;
}
.form-control textarea::-ms-input-placeholder {
color: #000000;
}
.form-control textarea::placeholder {
color: #000000;
}
.form-control i {
position: absolute;
top: 0.5rem;
right: 0.5rem;
visibility: hidden;
}
.form-control #textareaChecks {
position: absolute;
top: 8.5rem;
right: 0.5rem;
}
.form-control.success input {
border-color: green;
}
.form-control.success i.fa-check-circle {
visibility: visible;
color: green;
}
.form-control.error input {
border-color: red;
}
.form-control.error i.fa-exclamation-circle {
visibility: visible;
color: red;
}
.form-control.success textarea {
border-color: green;
}
.form-control.success i.fa-check-circle {
visibility: visible;
color: green;
}
.form-control.error textarea {
border-color: red;
}
.form-control.error i.fa-exclamation-circle {
visibility: visible;
color: red;
}
#Error {
font-weight: 500;
font-size: 0.75rem;
font-style: italic;
color: red;
margin: 0;
padding: 0;
}
#ContactSubmit {
width: 100%;
height: 2rem;
background: #1e1e1e;
outline: none;
border: 0.025rem solid #000000;
color: #FFFFFF;
}
.containerThank {
height: 300px;
display: -ms-grid;
display: grid;
}
.containerThank h3 {
margin: 0;
text-align: center;
-ms-flex-item-align: end;
align-self: flex-end;
font-size: 18px;
font-weight: bold;
}
.containerThank p {
-ms-flex-item-align: start;
align-self: flex-start;
text-align: center;
font-size: 13px;
padding-top: 0.5rem;
}
.hide {
display: none;
}
<form action="/php/contactMail.php" method="POST" class="formContact" id="formContact" novalidate>
<div class="form-control">
<input type="text" name="name" id="name" placeholder="First and Last name">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<span id="Error"></span>
</div>
<div class="form-control">
<input type="email" name="email" id="email" placeholder="Please enter your email">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<span id="Error"></span>
</div>
<div class="form-control">
<input type="text" name="subject" id="subject" placeholder="Subject">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<span id="Error"></span>
</div>
<div class="form-control">
<textarea id="message" name="message" type="text" placeholder="Message"></textarea>
<i id="textareaChecks" class="fas fa-check-circle"></i>
<i id="textareaChecks" class="fas fa-exclamation-circle"></i>
<span id="Error"></span>
</div>
<button id="ContactSubmit" name="submit">Submit</button>
</form>
<div class="Thankyou hide">
<div class="containerThank">
<h3 id="merci"></h3>
<p>Our team is going to get back to you as soon as possible</p>
</div>
</div>
</div>
</div>
</section>
</div>
Related
I have two classes 'signIn' and 'singUp'. So I need switch between them.
const form = document.getElementById('form');
const username = document.getElementById('username');
const email = document.getElementById('email');
const password = document.getElementById('password');
const password2 = document.getElementById('password2');
form.addEventListener('submit', (e) => {
e.preventDefault();
checkInputs();
});
function checkInputs() {
const usernameValue = username.value.trim();
const emailValue = email.value.trim();
const passwordValue = password.value.trim();
const password2Value = password2.value.trim();
if (usernameValue === '') {
setErrorFor(username, 'Username cannot be blank');
} else {
setSuccessFor(username);
}
if (emailValue === '') {
setErrorFor(email, 'Email cannot be blank');
} else if (!isEmail(emailValue)) {
setErrorFor(email, 'Email is not valid');
} else {
setSuccessFor(email);
}
if (passwordValue === '') {
setErrorFor(password, 'Password cannot be blank');
} else if (!isPassword(passwordValue)) {
setErrorFor(password, 'Password is not valid')
} else {
setSuccessFor(password);
}
if (password2Value === '') {
setErrorFor(password2, 'Password2 cannot be blank');
} else if (!isPassword(password2Value)) {
setErrorFor(password2, 'Password is not valid');
} else if (passwordValue !== password2Value) {
setErrorFor(password2, 'Passwords does not match');
} else {
setSuccessFor(password2);
}
}
function setErrorFor(input, message) {
const formControl = input.parentElement;
const small = formControl.querySelector('small');
small.innerText = message;
formControl.className = 'form-control error';
}
function setSuccessFor(input) {
const formControl = input.parentElement;
formControl.className = 'form-control success';
}
function isEmail(email) {
return /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(email);
}
function isPassword(password) {
return /^[A-Za-z]\w{7,14}$/.test(password);
}
#import url('https://fonts.googleapis.com/css?family=Muli&display=swap');
#import url('https://fonts.googleapis.com/css?family=Open+Sans:400,500&display=swap');
* {
box-sizing: border-box;
}
.main {
margin-top: 50px;
}
body {
background-color: plum;
font-family: 'Open Sans', sans-serif;
display: flex;
align-items: center;
justify-content: center;
margin-right: 25%;
/* margin: 0; */
}
.container {
background-color: white;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
overflow: hidden;
width: 420px;
max-width: 100%;
}
.header {
border-bottom: 1px solid white;
background-color: whitesmoke;
padding: 20px 40px;
}
.header h2 {
margin: 0;
}
.form {
padding: 30px 40px;
}
.form-control {
margin-bottom: 10px;
padding-bottom: 20px;
position: relative;
}
.form-control label {
display: inline-block;
margin-bottom: 5px;
}
.form-control input {
border: 2px solid whitesmoke;
border-radius: 4px;
display: block;
font-family: inherit;
font-size: 14px;
padding: 10px;
width: 100%;
}
.form-control.success input {
border-color: #2ecc71;
}
.form-control.error input {
border-color: #e74c3c;
}
.form-control i {
position: absolute;
top: 40px;
right: 10px;
visibility: hidden;
}
.form-control.success i.fa-check-circle {
color: #2ecc71;
visibility: visible;
}
.form-control.error i.fa-exclamation-circle {
color: #e74c3c;
visibility: visible;
}
.form-control small {
color: #e74c3c;
visibility: hidden;
position: absolute;
bottom: 0;
left: 0;
}
.form-control.error small {
visibility: visible;
}
.form button {
background-color: purple;
border: 2px solid purple;
border-radius: 4px;
color: white;
display: block;
font-family: inherit;
font-size: 16px;
padding: 10px;
width: 100%;
}
.footer p {
font-size: 14px;
}
.main a {
color: black;
}
.signUp,
.signIn {
/* position: absolute; */
}
<div class="main">
<div class="signIn">
<div class="container">
<div class="header">
<h2>Login</h2>
</div>
<form class="form" id="form">
<div class="form-control">
<label for="email">Email</label>
<input type="email" placeholder="" id="email" />
</div>
<div class="form-control">
<label for="password">Password</label>
<input type="password" id="password" />
</div>
<button>Submit</button>
</form>
</div>
<div class="footer">
<p>Not have an account? Sign Up Here</p>
</div>
</div>
<div id="signUpID" class="signUp">
<div class="container">
<div class="header">
<h2>Create Account</h2>
</div>
<form id="form" class="form">
<div class="form-control">
<label for="username">Username</label>
<input type="text" placeholder="Yeroma" id="username" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<div class="form-control">
<label for="username">Email</label>
<input type="email" placeholder="210103293#stu.sdu.edu.kz" id="email" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<div class="form-control">
<label for="username">Password</label>
<input type="password" placeholder="password" id="password" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<div class="form-control">
<label for="username">Password verification</label>
<input type="password" placeholder="password" id="password2" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<button>Submit</button>
<div class="footer">
<br>
<p>By clicking the Sign Up button, you agree to our </p>
<p>Terms and Condition and Policy Privacy</p>
</div>
</form>
</div>
<div class="footer">
<p>Already have an account? Login here</p>
</div>
</div>
</div>
try with this code.
use the javascript function to show hide signIn and signUp Form
const signIn = document.getElementsByClassName('signIn')[0];
const signUp = document.getElementsByClassName('signUp')[0];
signUp.style.display = 'none';
function showSignUpForm() {
signUp.style.display = 'block';
signIn.style.display = 'none';
}
function showSignInForm() {
signIn.style.display = 'block';
signUp.style.display = 'none';
}
const form = document.getElementById('form');
const username = document.getElementById('username');
const email = document.getElementById('email');
const password = document.getElementById('password');
const password2 = document.getElementById('password2');
form.addEventListener('submit', (e) => {
e.preventDefault();
checkInputs();
});
function checkInputs() {
const usernameValue = username.value.trim();
const emailValue = email.value.trim();
const passwordValue = password.value.trim();
const password2Value = password2.value.trim();
if (usernameValue === '') {
setErrorFor(username, 'Username cannot be blank');
} else {
setSuccessFor(username);
}
if (emailValue === '') {
setErrorFor(email, 'Email cannot be blank');
} else if (!isEmail(emailValue)) {
setErrorFor(email, 'Email is not valid');
} else {
setSuccessFor(email);
}
if (passwordValue === '') {
setErrorFor(password, 'Password cannot be blank');
} else if (!isPassword(passwordValue)) {
setErrorFor(password, 'Password is not valid')
} else {
setSuccessFor(password);
}
if (password2Value === '') {
setErrorFor(password2, 'Password2 cannot be blank');
} else if (!isPassword(password2Value)) {
setErrorFor(password2, 'Password is not valid');
} else if (passwordValue !== password2Value) {
setErrorFor(password2, 'Passwords does not match');
} else {
setSuccessFor(password2);
}
}
function setErrorFor(input, message) {
const formControl = input.parentElement;
const small = formControl.querySelector('small');
small.innerText = message;
formControl.className = 'form-control error';
}
function setSuccessFor(input) {
const formControl = input.parentElement;
formControl.className = 'form-control success';
}
function isEmail(email) {
return /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(email);
}
function isPassword(password) {
return /^[A-Za-z]\w{7,14}$/.test(password);
}
const signIn = document.getElementsByClassName('signIn')[0];
const signUp = document.getElementsByClassName('signUp')[0];
signUp.style.display = 'none';
function showSignUpForm() {
signUp.style.display = 'block';
signIn.style.display = 'none';
}
function showSignInForm() {
signIn.style.display = 'block';
signUp.style.display = 'none';
}
#import url('https://fonts.googleapis.com/css?family=Muli&display=swap');
#import url('https://fonts.googleapis.com/css?family=Open+Sans:400,500&display=swap');
* {
box-sizing: border-box;
}
.main {
margin-top: 50px;
}
body {
background-color: plum;
font-family: 'Open Sans', sans-serif;
display: flex;
align-items: center;
justify-content: center;
margin-right: 25%;
/* margin: 0; */
}
.container {
background-color: white;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
overflow: hidden;
width: 420px;
max-width: 100%;
}
.header {
border-bottom: 1px solid white;
background-color: whitesmoke;
padding: 20px 40px;
}
.header h2 {
margin: 0;
}
.form {
padding: 30px 40px;
}
.form-control {
margin-bottom: 10px;
padding-bottom: 20px;
position: relative;
}
.form-control label {
display: inline-block;
margin-bottom: 5px;
}
.form-control input {
border: 2px solid whitesmoke;
border-radius: 4px;
display: block;
font-family: inherit;
font-size: 14px;
padding: 10px;
width: 100%;
}
.form-control.success input {
border-color: #2ecc71;
}
.form-control.error input {
border-color: #e74c3c;
}
.form-control i {
position: absolute;
top: 40px;
right: 10px;
visibility: hidden;
}
.form-control.success i.fa-check-circle {
color: #2ecc71;
visibility: visible;
}
.form-control.error i.fa-exclamation-circle {
color: #e74c3c;
visibility: visible;
}
.form-control small {
color: #e74c3c;
visibility: hidden;
position: absolute;
bottom: 0;
left: 0;
}
.form-control.error small {
visibility: visible;
}
.form button {
background-color: purple;
border: 2px solid purple;
border-radius: 4px;
color: white;
display: block;
font-family: inherit;
font-size: 16px;
padding: 10px;
width: 100%;
}
.footer p {
font-size: 14px;
}
.main a {
color: black;
}
.signUp,
.signIn {
/* position: absolute; */
}
<div class="main">
<div class="signIn">
<div class="container">
<div class="header">
<h2>Login</h2>
</div>
<form class="form" id="form">
<div class="form-control">
<label for="email">Email</label>
<input type="email" placeholder="" id="email" />
</div>
<div class="form-control">
<label for="password">Password</label>
<input type="password" id="password" />
</div>
<button>Submit</button>
</form>
</div>
<div class="footer">
<p>Not have an account? Sign Up Here</p>
</div>
</div>
<div id="signUpID" class="signUp">
<div class="container">
<div class="header">
<h2>Create Account</h2>
</div>
<form id="form" class="form">
<div class="form-control">
<label for="username">Username</label>
<input type="text" placeholder="Yeroma" id="username" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<div class="form-control">
<label for="username">Email</label>
<input type="email" placeholder="210103293#stu.sdu.edu.kz" id="email" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<div class="form-control">
<label for="username">Password</label>
<input type="password" placeholder="password" id="password" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<div class="form-control">
<label for="username">Password verification</label>
<input type="password" placeholder="password" id="password2" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<button>Submit</button>
<div class="footer">
<br>
<p>By clicking the Sign Up button, you agree to our </p>
<p>Terms and Condition and Policy Privacy</p>
</div>
</form>
</div>
<div class="footer">
<p>Already have an account? Login here</p>
</div>
</div>
</div>
I'm trying to make a login form that check if my data are correct.
For example, if I insert a different value than "new_user" in the username field, then it should display a red error message under the submit button saying "please insert a valid user", and the border of the input field should be red as well.
If the username field is empty it has to do the same thing, just that the error message now has to be "please insert a username" and the same thing has to apply for the password field.
If the values for both username and password are matching has to display the message "Successfully Login"
I will attach an image just as an example, and I have added my code below. Please feel free to tell me what am I doing wrong.
var form = document.getElementById("form");
var user = document.getElementById("username");
var pass = document.getElementById("password");
var botton = document.getElementById("btn")
var validUser = "new_user";
var validPassword = 123456789;
form.addEventListener("submit", function(e) {
e.preventDefault();
checkInputs();
})
user.addEventListener("input", function() {
var username = user.value;
if (username) {
if (username === " " || username == null) {
setErrorFor(user, "Please insert a username");
} else if (username !== validUser) {
setErrorFor(user, "Please insert a valid username");
}
} else {
setSuccessFor(user, "Successfully Login")
}
})
function setErrorFor(input, message) {
var formControl = input.parentElement;
var showError = document.querySelector(".text-message");
var displayMessage = document.getElementById("msg");
//add error message & add the class name inside the message element
displayMessage.innerHTML = message
showError.className = "text-message invalid"
//add the error class
formControl.classList = "form-control fail"
}
function setSuccessFor(input, message) {
var formControl = input.parentElement;
var showError = document.querySelector(".text-message");
var displayMessage = document.getElementById("msg");
//add error message & add the class name inside the message element
displayMessage.innerHTML = message
showError.className = "text-message valid"
//add the error class
formControl.classList = "form-control success"
}
* {
box-sizing: border-box;
font-family: sans-serif;
}
body {
height: 100vh;
width: 100vw;
display: flex;
justify-content: center;
align-items: center;
}
#login-container {
width: 45%;
margin: 0 auto;
border-radius: .5em;
position: relative;
background: linear-gradient(to right, rgb(88, 167, 236), rgb(180, 198, 214), rgb(180, 198, 214));
padding: 3em 2.5em;
box-shadow: 0px 5px 4px #424241;
text-align: justify;
}
.input-field {
margin-bottom: .5em;
}
input[type="text"],
input[type="password"] {
width: 100%;
display: inline-block;
outline: none;
font-size: 18px;
padding: .5em 1.5em .5em .5em;
border-radius: .5em;
}
.form-control {
position: relative;
}
.input-field i {
position: absolute;
top: 2.2em;
right: .5em;
opacity: 0;
}
.fa-check {
color: green;
}
.fa-times {
color: red;
}
form label {
font-weight: bold;
display: inline-block;
font-size: 18px;
margin-bottom: .2em;
}
form input[type="submit"] {
background: rgb(112, 112, 112);
border-radius: .5em;
margin: 1em 0 .2em 0;
padding: .5em 0;
display: block;
font-size: 18px;
font-weight: 700;
width: 100%;
position: relative;
text-transform: uppercase;
border: none;
}
form input[type="submit"]:hover {
background-color: #70db70;
color: white;
}
.text-message .msg {
margin: 0;
padding: 0;
font-size: 16px;
}
/*Message classes*/
.form-control.success input {
border: 3px solid green;
}
.form-control.fail input {
border: 3px solid red;
}
.form-control.success i.fa-check {
opacity: 1;
}
.form-control.fail i.fa-times {
opacity: 1;
}
.text-message.valid p {
display: block;
color: green;
}
.text-message.invalid p {
display: block;
color: red;
}
<form id="form">
<div class="input-field">
<div class="form-control">
<label for="username">Username:</label>
<input id="username" class="input" type="text">
<i class="fas fa-check u_check"></i>
<i class="fas fa-times u_decline"></i>
</div>
</div>
<div class="input-field">
<div class="form-control">
<label for="password">Password:</label>
<input id="password" class="input" type="password">
<i class="fas fa-check p_check"></i>
<i class="fas fa-times p_decline"></i>
</div>
</div>
<input type="submit" value="submit" id="btn">
<div class="text-message">
<p id="msg" class="msg"></p>
</div>
I am trying to make a counter for submitting a form in php, if the data from the forms is sent to the server, +1 is written to the counter.txt file, this data is used to form the header in the letter. Everything works, but 5 identical letters come to the mail, the next time it sends 10 and so on. What is the problem? Why is this happening?
When I remove the counter code everything works fine and one letter arrives.
<?php
$email = ($_POST['sel']);
$change = ($_POST['button-set']);
$name = ($_POST['name']);
$question = ($_POST['message']);
$submit = ($_POST['submit']);
if (isset ($submit)) {
$count = file_get_contents ('counter.txt');
$count ++;
file_put_contents ('counter.txt', $count);
}
else {
$count = file_get_contents ('counter.txt');
};
$to = 'support#archsupport.ru';
$subject = 'Application number: ' . $count . 'from the site archsupport.ru';
$message = 'Name: ' . $name . "\r\n" . 'Contacts: ' . $email . "\r\n" . 'Write ' . $change . "\r\n" . 'Question: ' . $question ;
$headers = 'From: zergg52#gmail.com ' . "\r\n";
$subject = preg_replace("/(\r\n)|(\r)|(\n)/", "", $subject);
$subject = preg_replace("/(\t)/", " ", $subject);
$subject = '=?UTF-8?B?' . base64_encode($subject) . '?=';
#mail($to, $subject, $message, $headers);
echo 'message sent!';
var_dump($email,$change,$name,$question,$submit,$count)
?>
Page code:
var form = document.getElementsByTagName('form')[0];
var names = document.getElementById('name');
var validn = document.getElementById('vn');
var iconrequired = document.querySelector('#namereq');
var email = document.getElementById('sellection');
var valids = document.getElementById('vs');
var iconrequireds = document.querySelector('#sellectionreq');
var text = document.getElementById('qestions');
var validt = document.getElementById('vt');
var iconrequiredt = document.querySelector('#textreq');
document.addEventListener('input', function validation() {
var x = document.forms["support"]["sellection"].value;
if (names.validity.valid) {
validn.className = "valid";
iconrequired.className = "iconrequired hide";
};
if (email.validity.valid && x != "") {
valids.className = "valid";
iconrequireds.className = "iconrequired hide";
};
if (text.validity.valid) {
validt.className = "valid";
iconrequiredt.className = "iconrequired hide";
};
if (!names.validity.valid) {
validn.className = "invalid";
iconrequired.className = "iconrequired hide";
};
if (!email.validity.valid) {
valids.className = "invalid";
iconrequireds.className = "iconrequired hide";
};
if (!text.validity.valid) {
validt.className = "invalid";
iconrequiredt.className = "iconrequired hide";
};
if (names.validity.valid && email.validity.valid && text.validity.valid) {
$('#support').submit(function() {
$.post(
'https://www.archsupport.ru/post-email.php',
$("#support").serialize(),
function(msg) {
$('#support').hide('slow');
$('#message').html(msg);
}
);
});
} else {
return false;
}
});
function validateSellection() {
var x = document.forms["support"]["sellection"].value;
if (x === "") {
document.getElementById('sellectionreq').classList.remove("hide");
return false;
} else {
document.getElementById('sellectionreq').classList.add("hide");
return false;
}
};
function validateName() {
var x = document.forms["support"]["name"].value;
if (x === "") {
document.getElementById('namereq').classList.remove("hide");
return false;
} else {
document.getElementById('namereq').classList.add("hide");
return false;
}
};
function validateText() {
var x = document.forms["support"]["qestions"].value;
if (x === "") {
document.getElementById('textreq').classList.remove("hide");
return false;
} else {
document.getElementById('textreq').classList.add("hide");
return false;
}
};
$('#support').submit(function validate() {
if (validateName() && validateSellection() && validateText() === true) {
return false;
} else {
validateSellection();
validateName();
validateText()
return false
}
});
$(".radio").on('click.two', function() {
let input = $("#sellection");
if ($("#radio").prop("checked")) {
input.prop("disabled", false);
input.prop({
"type": "email",
"placeholder": "example#yourmail.ru",
"autocomplete": "email",
"maxlength": "35",
"minlength": "12",
"value": "",
});
document.getElementById("sellection").pattern = "^[a-z0-9._%+-]+#[a-z0-9.-]+\\.[a-z]{2,4}$";
} else {
input.prop("disabled", false);
$("#sellection").prop({
"type": "tel",
"placeholder": "+7-910-205-46-15",
"autocomplete": "tel",
"maxlength": "16",
"minlength": "11",
"value": "",
});
document.getElementById("sellection").pattern = "\\+7\\s?[\\(]{0,1}9[0-9]{2}[\\)]{0,1}\\s?\\d{3}[-]{0,1}\\d{2}[-]{0,1}\\d{2}";
}
input.focus();
input.val("");
});
var fab = $('.icons');
fab.on('click.ten', function iconback() {
fab.removeClass('checked');
$(this).addClass('checked');
});
#keyframes req {
0% {
transform: translatex(0px);
}
100% {
transform: translatex(5px);
}
}
#keyframes inv {
0% {
opacity: .5;
}
100% {
opacity: 1;
}
}
* {
padding: 0;
margin: 0;
}
:root {
font-family: "HelveticaNeueCyr";
font-weight: 100;
}
form {
font-size: 24px;
position: relative;
width: 100%;
display: inline-flex;
flex-direction: column;
}
textarea {
height: 30vh;
border-radius: 18px;
padding-left: 15px;
padding-top: 10px;
border: 2px solid #d7d7d7;
overflow: hidden;
overflow-y: scroll;
outline: none;
resize: none
}
input,
textarea {
font-family: "HelveticaNeueCyr";
font-weight: 100;
font-size: 18px;
}
::-webkit-input-placeholder {
color: gray;
font-size: 18px;
}
::-moz-placeholder {
color: gray;
font-size: 18px;
}
/* Firefox 19+ */
:-moz-placeholder {
color: gray;
font-size: 18px;
}
/* Firefox 18- */
:-ms-input-placeholder {
color: gray;
font-size: 18px;
}
input:not([type="submit"]) {
border-radius: 100px;
padding-left: 15px;
height: 36px;
border: none;
background: #f3f3f3;
}
input:focus {
outline: none;
border: 2px solid #f3f3f3;
box-sizing: border-box;
background: white;
padding-left: 13px;
}
.required {
display: inline-flex;
width: 100%;
flex-direction: column;
margin-bottom: 15px;
position: relative;
}
.iconrequired {
margin: auto;
display: flex;
align-items: center;
justify-content: center;
width: 90px;
height: 14px;
color: white;
border-radius: 100px;
font-size: 10px;
font-weight: 100;
font-family: "HelveticaNeueCyr";
background: #343434;
position: absolute;
right: 15px;
top: 10px;
opacity: 1;
transition: opacity ease-out 1s;
animation: .05s ease-in-out 0s 4 alternate req;
}
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
input:-webkit-autofill:active {
transition: background-color 5000s ease-in-out 0s;
border: 2px solid #f3f3f3;
box-sizing: border-box;
padding-left: 13px;
}
div.button-set {
display: inline-flex;
}
div.button-set>label {
position: relative;
flex: 0 0 auto;
height: 50px;
width: 50px;
margin-left: 15px;
border-radius: 100px;
outline: none;
border: none;
margin-bottom: 20px;
}
.checked {
background: #f3f3f3;
border-radius: 100px;
}
input[type="submit"] {
font-family: "HelveticaNeueCyr";
height: 36px;
width: 160px;
font-weight: 100;
font-size: 24px;
margin-top: 20px;
margin-left: 10px;
border: none;
border-radius: 100px;
background: #f3f3f3;
padding: 0;
}
::-webkit-scrollbar {
position: absolute;
z-index: 9999;
width: 5px;
}
::-webkit-scrollbar-button {
display: none;
}
::-webkit-scrollbar-track {
z-index: 9999;
background-color: transparent;
}
::-webkit-scrollbar-track-piece {
z-index: 9999;
z-index: 9999;
background-color: transparent;
}
::-webkit-scrollbar-thumb {
z-index: 9999;
background-color: #d7d7d7;
border-radius: 3px;
}
::-webkit-scrollbar-corner {
z-index: 9999;
background-color: #d7d7d7;
}
.invalid {
width: 12px;
height: 12px;
color: white;
position: absolute;
right: 15px;
top: 12px;
background: tomato;
border-radius: 6px;
animation: 2s ease-in-out 0s infinite alternate inv;
}
.valid {
width: 12px;
height: 12px;
color: white;
position: absolute;
right: 15px;
top: 12px;
background: #9dc46b;
border-radius: 6px;
animation: 2s ease-in-out 0s infinite alternate inv;
}
.error {
text-align: right;
font-size: 12px;
padding-right: 20px;
padding-top: 10px;
color: gray;
letter-spacing: .05em;
}
.hide {
display: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="/css/form.css">
</head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<form novalidate action="" method="post" name="support" id="support">
<label class="required"><span id="vs" class="invalid hide"></span><input id="sellection" class="mail sellection" name="sel" vlaue="" placeholder="choose a communication way...." required disabled><span id="error1"></span><div id="sellectionreq" class="iconrequired hide">REQUIRED</div></label>
<div class="button-set">
<label title="Email"><img class="icons" src='/img/icon/social_icon_mail_white.svg'><input class="radio" id="radio" type="radio" name="button-set" value="to mail" style="display:none;"></label>
<label for="radio1" title="WhatsApp"><img class="icons" src='/img/icon/social_icon_whatsapp_white.svg'><input class="radio" id="radio1" type="radio" name="button-set" value="to WhatsApp" style="display:none;"></label>
<label for="radio2" title="Telegram"><img class="icons" src='/img/icon/social_icon_telegram_white.svg'><input class="radio" id="radio2" type="radio" name="button-set" value="to Telegram" style="display:none;"></label>
<label for="radio3" title="Viber"><img class="icons" src='/img/icon/social_icon_viber_white.svg'><input class="radio" id="radio3" type="radio" name="button-set" value="to Viber" style="display:none;"></label>
</div>
<label class="required"><span id="vn" class="invalid hide"></span>
<input id="name" class="mail" type="name" name="name" autocomplete= none placeholder="what's your name...." value="" pattern="[A-Za-z]+(\s+[A-Za-z]+)?" maxlength="15" minlength="2" required><div id="namereq" class="iconrequired hide">REQUIRED</div></label>
<label class="required"><span id="vt" class="invalid hide"></span><textarea id="qestions" type="text" placeholder="your question...." name="message" value="" pattern="[A-Za-z]+(\s+[A-Za-z]+)?" maxlength="400" minlength="4" required></textarea><div id="textreq" class="iconrequired hide">REQUIRED</div></label>
<input name="submit" type="submit" id="submit" value="SUBMIT" />
</form>
<div id="message"></div>
</body>
<script src="/js/form.js"></script>
</html>
without counter:
var_dump($email,$change,$name,$question,$submit) - string(12)
"+79102054615" string(11) "to WhatsApp" string(4) "ZERG" string(8)
"ANYTHING" NULL
with counter:
var_dump($email,$change,$name,$question,$submit,$count) - string(12)
"+79102054615" string(11) "to WhatsApp" string(4) "ZERG" string(8)
"ANYTHING" NULL string(1) "9"
$count immediately takes on value "9"
site with form: https://www.archsupport.ru/
In regards to the HTML/JavaScript, consider the following code.
$(function() {
var form = $("#support");
function checkFieldValidity(fObj) {
var r = false;
var re = new RegExp(fObj.attr("pattern"));
var v = fObj.val();
if (fObj.is("[required]")) {
if (v.length) {
fObj.next(".iconrequired").hide();
} else {
fObj.next(".iconrequired").show();
}
if (re.test(v)) {
fObj.prev(".icon").removeClass("invalid").addClass("valid");
r = true;
} else {
fObj.prev(".icon").removeClass("valid").addClass("invalid");
}
} else {
r = true;
}
return r;
}
$("input", form).blur(function() {
checkFieldValidity($(this));
});
form.submit(function(e) {
e.preventDefault();
var valid = true;
$("[required]", form).each(function(i, el) {
valid = valid && checkFieldValidity($(el));
});
return valid;
});
$(".button-set label", form).on('click', function() {
$(this).parent().find(".checked").removeClass("checked");
$("img", this).addClass("checked");
var input = $("#sellection");
input.prop("disabled", false);
switch ($(this).data("value")) {
case "email":
input.prop({
type: "email",
placeholder: "example#yourmail.com",
autocomplete: "email",
maxlength: 35,
minlength: 12,
value: "",
}).attr("pattern", "^[a-z0-9._%+-]+#[a-z0-9.-]+\\.[a-z]{2,4}$");
break;
// Add Cases for each selection option if needed
default:
input.prop({
"type": "tel",
"placeholder": "+7-910-205-46-15",
"autocomplete": "tel",
"maxlength": "16",
"minlength": "11",
"value": "",
});
input.attr("pattern", "\\+7\\s?[\\(]{0,1}9[0-9]{2}[\\)]{0,1}\\s?\\d{3}[-]{0,1}\\d{2}[-]{0,1}\\d{2}");
break;
}
input.focus();
input.val("");
});
});
#keyframes req {
0% {
transform: translatex(0px);
}
100% {
transform: translatex(5px);
}
}
#keyframes inv {
0% {
opacity: .5;
}
100% {
opacity: 1;
}
}
* {
padding: 0;
margin: 0;
}
:root {
font-family: "HelveticaNeueCyr";
font-weight: 100;
}
form {
font-size: 24px;
position: relative;
width: 100%;
display: inline-flex;
flex-direction: column;
}
textarea {
height: 30vh;
border-radius: 18px;
padding-left: 15px;
padding-top: 10px;
border: 2px solid #d7d7d7;
overflow: hidden;
overflow-y: scroll;
outline: none;
resize: none
}
input,
textarea {
font-family: "HelveticaNeueCyr";
font-weight: 100;
font-size: 18px;
}
::-webkit-input-placeholder {
color: gray;
font-size: 18px;
}
::-moz-placeholder {
color: gray;
font-size: 18px;
}
/* Firefox 19+ */
:-moz-placeholder {
color: gray;
font-size: 18px;
}
/* Firefox 18- */
:-ms-input-placeholder {
color: gray;
font-size: 18px;
}
input:not([type="submit"]) {
border-radius: 100px;
padding-left: 15px;
height: 36px;
border: none;
background: #f3f3f3;
}
input:focus {
outline: none;
border: 2px solid #f3f3f3;
box-sizing: border-box;
background: white;
padding-left: 13px;
}
.required {
display: inline-flex;
width: 100%;
flex-direction: column;
margin-bottom: 15px;
position: relative;
}
.iconrequired {
margin: auto;
display: flex;
align-items: center;
justify-content: center;
width: 90px;
height: 14px;
color: white;
border-radius: 100px;
font-size: 10px;
font-weight: 100;
font-family: "HelveticaNeueCyr";
background: #343434;
position: absolute;
right: 15px;
top: 10px;
opacity: 1;
transition: opacity ease-out 1s;
animation: .05s ease-in-out 0s 4 alternate req;
}
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
input:-webkit-autofill:active {
transition: background-color 5000s ease-in-out 0s;
border: 2px solid #f3f3f3;
box-sizing: border-box;
padding-left: 13px;
}
div.button-set {
display: inline-flex;
}
div.button-set>label {
position: relative;
flex: 0 0 auto;
height: 50px;
width: 50px;
margin-left: 15px;
border-radius: 100px;
outline: none;
border: none;
margin-bottom: 20px;
}
.checked {
background: #f3f3f3;
border-radius: 100px;
}
input[type="submit"] {
font-family: "HelveticaNeueCyr";
height: 36px;
width: 160px;
font-weight: 100;
font-size: 24px;
margin-top: 20px;
margin-left: 10px;
border: none;
border-radius: 100px;
background: #f3f3f3;
padding: 0;
}
::-webkit-scrollbar {
position: absolute;
z-index: 9999;
width: 5px;
}
::-webkit-scrollbar-button {
display: none;
}
::-webkit-scrollbar-track {
z-index: 9999;
background-color: transparent;
}
::-webkit-scrollbar-track-piece {
z-index: 9999;
z-index: 9999;
background-color: transparent;
}
::-webkit-scrollbar-thumb {
z-index: 9999;
background-color: #d7d7d7;
border-radius: 3px;
}
::-webkit-scrollbar-corner {
z-index: 9999;
background-color: #d7d7d7;
}
.invalid {
width: 12px;
height: 12px;
color: white;
position: absolute;
right: 15px;
top: 12px;
background: tomato;
border-radius: 6px;
animation: 2s ease-in-out 0s infinite alternate inv;
}
.valid {
width: 12px;
height: 12px;
color: white;
position: absolute;
right: 15px;
top: 12px;
background: #9dc46b;
border-radius: 6px;
animation: 2s ease-in-out 0s infinite alternate inv;
}
.error {
text-align: right;
font-size: 12px;
padding-right: 20px;
padding-top: 10px;
color: gray;
letter-spacing: .05em;
}
.hide {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form novalidate action="" method="post" name="support" id="support">
<span class="icon"></span><input id="sellection" class="mail" name="f[sel]" value="" placeholder="Choose a communication method...." required disabled>
<div class="iconrequired hide">REQUIRED</div>
<div class="button-set">
<label title="Email" data-value="email"><img class="icon" src='/img/icon/social_icon_mail_white.svg'></label>
<label title="WhatsApp" data-value="whatsapp"><img class="icon" src='/img/icon/social_icon_whatsapp_white.svg'></label>
<label title="Telegram" data-value="telegram"><img class="icon" src='/img/icon/social_icon_telegram_white.svg'></label>
<label title="Viber" data-value="viber"><img class="icon" src='/img/icon/social_icon_viber_white.svg'></label>
</div>
<label class="required"><span class="icon"></span>
<input id="name" class="mail" type="name" name="f[name]" autocomplete="none" placeholder="what's your name...." value="" pattern="[A-Za-z]+(\s+[A-Za-z]+)?" maxlength="15" minlength="2" required><div id="namereq" class="iconrequired hide">REQUIRED</div></label>
<label class="required"><span id="vt" class="invalid hide"></span><textarea id="qestions" type="text" placeholder="your question...." name="f[message]" value="" pattern="[A-Za-z]+(\s+[A-Za-z]+)?" maxlength="400" minlength="45" required></textarea><div id="textreq" class="iconrequired hide">REQUIRED</div></label>
<input name="f[submit]" type="submit" id="submit" value="SUBMIT" />
</form>
<div id="message"></div>
You want to evaluate if each field that is required has content and matches a specific pattern. I think your approach was too complicated. Additionally, I would stick with all native JavaScript or all jQuery. Don't mix them.
For submit, you will want to test each field and keep a running tally. To do this, you can logically start with a true value and as you test, keep logically evaluating. Example:
var result = true;
result = result && true; // result is true
result = result && false; // result is false
result = result && true; // result is false
If some of the fields validate and if any do not, the result will be false and the form should not submit. If all validate, the result will be true and it's safe to submit the data to PHP. This should also prevent multiple submissions.
Remember that this is Client Side validation and can be bypassed by posting the data manually to the PHP. Most users will not even bother, yet all it takes is one curious or malicious User or Bot to see that they can bypass the form and create their own HTTP Post Payload. So you will want to ensure that your PHP is protected from such actions. Test any data submitted by the User before using it in your PHP Code. For example, you define $name like so:
$name = ($_POST['name']);
If I construct a payload like:
&name=;include "/etc/passwd";
This might get evaluated in the following code:
$message = 'Name: ' . $name . "\r\n" . 'Contacts: ' . $email . "\r\n" . 'Write ' . $change . "\r\n" . 'Question: ' . $question;
Just some things to consider.
I am a stuck on following issues:
How to add required error just once after first click on submit button? And not at any subsequent click after.
How can to start function (checkValid()) with RegExp validation only after first function (checkRequired()) implementation with required checking?
How to show every error after RegExp validation in its relative element? Now all errors are displayed in the last block with phone input.
Here is case on jsfiddle:
https://jsfiddle.net/SanchezMalina/hno7v4tf/35/
Or code here:
// regexp pattern functions
function validateEmail(email) {
let re = /^(([^<>()\[\]\\.,;:\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,}))$/;
return re.test(email.toLowerCase());
}
function validatePhone(phone) {
let re = /^[0-9]{7,20}$/;
return re.test(phone.toLowerCase());
}
function validateName(name) {
let re = /^([a-zA-Z0-9А]){3,50}$/;
return re.test(name.toLowerCase());
}
let flag = false;
// check required fields
function checkRequired() {
let notFilled = document.querySelectorAll('.is-required');
notFilled.forEach(function (el) {
if (el.value === '') {
el.parentElement.classList.add('is-empty');
addRequiredError();
} else {
el.parentElement.classList.remove('is-empty');
removeRequiredError();
}
});
}
let formFields = document.querySelectorAll('.form__field');
//add required error message
function addRequiredError() {
let errorRequiredMsg = document.createElement('div');
errorRequiredMsg.classList.add('input-required');
errorRequiredMsg.innerHTML = `<span> This field is required! </span>`;
formFields.forEach( function (elem) {
if (elem.classList.contains('is-empty')) {
elem.appendChild(errorRequiredMsg);
}
});
}
//remove required error message
function removeRequiredError() {
let requiredErrorMsg = document.querySelectorAll('.form__field .input-required');
requiredErrorMsg.forEach(function (elem) {
elem.parentElement.removeChild(elem);
});
flag = true;
}
//check validation inputs
function checkValid() {
let firstName = document.querySelector('#f-name');
let lastName = document.querySelector('#l-name');
let selectCountry = document.querySelector('.form__select');
let phone = document.querySelector('#cell');
let email = document.querySelector('#email');
formFields.forEach(function () {
if(!validateName(firstName.value) && !validateName(lastName.value) && !validatePhone(phone.value) && !validateEmail(email.value)) {
firstName.parentElement.classList.add('is-error');
lastName.parentElement.classList.add('is-error');
selectCountry.parentElement.classList.add('is-error');
phone.parentElement.classList.add('is-error');
email.parentElement.classList.add('is-error');
addValidError();
} else {
firstName.parentElement.classList.remove('is-error');
lastName.parentElement.classList.remove('is-error');
selectCountry.parentElement.classList.remove('is-error');
phone.parentElement.classList.remove('is-error');
email.parentElement.classList.remove('is-error');
removeValidError();
}
});
}
//add invalid error message
function addValidError() {
let errorValidMsg = document.createElement('div');
errorValidMsg.classList.add('input-error');
errorValidMsg.innerHTML = `<span> Input is invalid! </span>`;
formFields.forEach(function (elem) {
if (elem.classList.contains('is-error')) {
elem.appendChild(errorValidMsg);
}
});
// for (let i = 0; i < formFields.length; i++) {
//
// if (formFields[i].classList.contains('is-error')) {
//
// formFields[i].appendChild(errorValidMsg);
//
// }
// }
}
//remove invalid error message
function removeValidError() {
let requiredErrorMsg = document.querySelectorAll('.input-error');
requiredErrorMsg.forEach(function (elem) {
elem.parentNode.removeChild(elem);
})
}
//form submit handler
let formTrial = document.querySelector('.form__main');
formTrial.addEventListener('submit', function (event) {
event.preventDefault();
checkRequired();
console.log(flag);
if(flag !== false) {
checkValid();
}
});
.form__main {
display: block;
margin: 25px auto;
width: 450px;
}
.form__field {
position: relative;
margin: 10px 0;
padding: 5px 15px;
background-color: #fff;
height: 50px;
}
.form__field_select::after {
content: "";
width: 0;
height: 0;
border: 7px solid transparent;
border-color: #000 transparent transparent transparent;
position: absolute;
top: 55%;
right: 17px;
transform: translateY(-50%);
}
.form__input {
position: absolute;
left: 0;
top: 10px;
right: 0;
bottom: 10px;
padding-left: 45px;
background: none;
font-size: 14px;
font-weight: 400;
font-family: "Open Sans", sans-serif;
width: 100%;
color: #333;
line-height: 1.714;
box-sizing: border-box;
}
.form__input:focus ~ .form__label,
.form__input:valid ~ .form__label {
top: 0;
left: 45px;
transform: scale(0.6, 0.6);
color: #000;
}
.form__input:focus ~ .form__label[for=cell],
.form__input:valid ~ .form__label[for=cell] {
top: 0;
left: 125px;
}
.form__input[type=tel] {
padding-left: 125px;
}
.form__input:-webkit-autofill {
-webkit-box-shadow: 0 0 0 100px white inset;
}
.form__label {
position: absolute;
top: 50%;
left: 50px;
transform-origin: left top;
transition: all 0.3s ease;
transform: translateY(-50%);
font-size: 14px;
font-family: "Open Sans", sans-serif;
color: #999999;
line-height: 1.714;
}
.form__label[for=cell] {
left: 135px;
}
.form__select {
position: absolute;
width: 100%;
height: 100%;
top: 50%;
transform: translateY(-50%);
left: 0;
right: 0;
padding-left: 50px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
-webkit-appearance: none;
-moz-appearance: none;
background-color: transparent;
border-color: #fff;
font-size: 14px;
font-family: "Open Sans", sans-serif;
color: #000;
line-height: 1.714;
}
.form__country-code {
position: absolute;
color: #000;
left: 50px;
font-size: 14px;
font-family: "Open Sans", sans-serif;
line-height: 2;
height: 100%;
top: 0;
bottom: 0;
display: flex;
align-items: center;
border-right: 1px solid;
padding-right: 20px;
z-index: 2;
}
.form .btn {
width: 100%;
margin: 20px 0;
}
.form .btn:hover {
transform: translateY(-5px);
box-shadow: 1px 3px 20px #c5f833;
}
<form method="post" class="form__main" novalidate>
<div class="form__field">
<i class="icon icon-user"></i>
<input class="form__input is-required" id="f-name" type="text" required>
<label class="form__label" for="f-name">First Name</label>
</div>
<div class="form__field">
<i class="icon icon-user"></i>
<input class="form__input is-required" id="l-name" type="text" required>
<label class="form__label" for="l-name">Last Name</label>
</div>
<div class="form__field">
<i class="icon icon-envelop"></i>
<input class="form__input" id="email" type="text" required>
<label class="form__label" for="email">Email</label>
</div>
<div class="form__field form__field_select">
<i class="icon icon-pin"></i>
<select class="form__select" name="country">
<option value="ro" selected>USA</option>
<option value="ua">India</option>
<option value="il">Spain</option>
</select>
</div>
<div class="form__field">
<i class="icon icon-phone"></i>
<span class="form__country-code">+10000</span>
<input class="form__input" id="cell" type="tel" required>
<label class="form__label" for="cell">Phone</label>
</div>
<button class="btn btn_lime">Try for free</button>
</form>
1)
if( !el.parentElement.classList.contains('is-empty') ) {
addRequiredError();
}
2)
not sure to understand the question
3)
function addValidError() {
let errorValidMsg = document.createElement('div');
errorValidMsg.classList.add('input-error');
errorValidMsg.innerHTML = '<span> Input is invalid! </span>';
formFields.forEach(function (elem) { // <-- here formFields is not defined
}
In my form, when the user fills out the email portion, if the email has been previously used and auto fill puts in the information the email shows up as invalid. How can I change the javascript or JQuery so it does not do this? Any help would be much appreciated!
[![enter image description here][1]][1]
[enter link description here][2]
[1]: https://i.stack.imgur.com/nQD04.png
[2]: http://jsfiddle.net/M6N24/532/
<form class="container" action="https://webto.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8" method="POST">
<label>First Name
<input id="first_name" maxlength="40" name="first_name" size="20" type="text" onkeyup="test()" required><i class="fa fa-check-circle" aria-hidden="true"></i>
</label>
<label>Last Name
<input id="last_name" maxlength="80" name="last_name" size="20" type="text" onkeyup="test()"><i class="fa fa-check-circle" aria-hidden="true"></i>
</label>
<label>Email
<span class="error">Please enter a valid email address</span>
<input id="email" maxlength="80" name="email" size="20" type="text" onkeyup="test()"><i class="fa fa-times-circle-o" aria-hidden="true"></i>
</label>
<label>Phone
<span class="error">Please enter a valid phone number</span>
<input id="phone" maxlength="80" name="phone" size="20" type="tel" onkeyup="test()"><i class="fa fa-check-circle" aria-hidden="true"></i>
</label>
<label>City
<input id="city" name="city" maxlength="40" size="20" type="text" onkeyup="test()"><i class="fa fa-check-circle" aria-hidden="true"></i>
</label>
<label>State/Province
<input id="state" maxlength="20" name="state" size="20" type="text" onkeyup="test()"><i class="fa fa-check-circle" aria-hidden="true"></i>
</label>
<label id="co">Company
<input id="company" name="company" type="text" onkeyup="test()"><i class="fa fa-check-circle" aria-hidden="true"></i>
</label>
<label>Comments
<textarea id="comments" name="" id="" cols="30" rows="10" onkeyup="test()"></textarea>
<input id="sub" type="submit" disabled="disabled" />
</label>
<div>
<select hidden="true" id="00N6A000008yXMN" name="00N6A000008yXMN" title="Product Interest">
<option value="">--None--</option>
<option selected="selected" value="Visiant">Visiant</option>
<option value="Tessellate">Tessellate</option>
</select><br>
<select hidden="true" id="lead_source" name="lead_source">
<option value="">--None--</option>
<option value="Internal">Internal</option>
<option value="Trade Show">Trade Show</option>
<option selected="selected" value="Website">Website</option>
<option value="Direct Marketing">Direct Marketing</option>
<option value="Social Media">Social Media</option>
<option value="Other">Other</option>
</select><br>
</div>
</form>
body {
color: #fff;
background-color: #30bda6;
text-align: center;
}
form {
color: #fff;
background-color: #30bda6;
text-align: center;
font-family: Lato;
}
* {
box-sizing: border-box;
}
.form-title {
font-size: 38px;
color: #fff;
font-family: "Lato";
letter-spacing: 70px;
}
input {
font-size: 15px;
height: 48px;
margin-top: 8px;
}
input[type="tel"] {
width: 100%;
padding: 10px;
background-color: #30bda6;
border: 1px solid #fff;
font-size: 15px;
height: 48px;
}
input[type="text"] {
width: 100%;
padding: 10px;
background-color: #30bda6;
border: 1px solid #fff;
font-size: 15px;
}
input:focus {
background-color: #fff;
}
input[type="text"]:focus {
background-color: #fff;
}
input[type="text"]:visited {
background-color: #fff;
}
input[type="tel"]:focus {
background-color: #fff;
}
input[type="tel"]:visited {
background-color: #fff;
}
.container {
display: flex;
flex-direction: column;
padding: 5px 0;
}
textarea {
width: 100%;
background-color: #30bda6;
border: 1px solid #fff;
}
textarea:focus {
background-color: #fff;
}
#co {
flex-basis: 100%;
max-width: 100%;
}
label:nth-last-child(-n+2) {
flex-basis: 100%;
max-width: 100%;
}
select,
label {
height: 50px;
width: 48%;
margin: 2% 1%;
text-align: left;
font-family: "Lato";
font-size: 15px;
}
#sub {
border-radius: 6px;
width: 120px;
height: 35px;
text-transform: uppercase;
display: block;
margin-top: 48px;
font-size: 16px;
border: none;
}
#sub2 {
border-radius: 6px;
width: 120px;
height: 35px;
text-transform: uppercase;
display: block;
margin-top: 48px;
font-size: 16px;
border: none;
}
label {
position: relative;
}
.fa {
position: absolute;
bottom: 0;
right: 0;
transform: translate(-50%, 65%);
opacity: 0;
transition: opacity .5s, color .5s;
}
[data-valid] .fa {
opacity: 1;
color: #00594C;
}
[data-valid="valid"] .fa {
color: #00594C;
}
[data-valid="error"] .fa {
color: #AB0000;
}
.error {
display: none;
color: #AB0000;
font-size: .7em;
position: absolute;
left: 10px;
top: 0;
transform: translateY(150%);
font-size: 12px;
margin-top: 2px;
}
[data-valid="error"] .error {
display: block;
}
input#sub2:not([disabled]){
background-color: #fff;
color: #00AB8E;
}
input#sub:not([disabled]){
background-color: #fff;
color: #F68D2E;;
}
#thankyou { display:none;}
#thankyou.success {
display: block;
text-align: center;
}
#tessellate-page input:focus {
background-color: #fff !important;;
}
#tessellate-page textarea:focus {
background-color: #fff !important;;
}
#tessellate-page input[type="text"] {
width: 100%;
padding: 10px;
background-color: #30bda6;
border: 1px solid #fff;
}
#comments_label {
margin-top: 8px;
}
#media (max-width: 656px) {
label {
width: 98%;
height: 70px;
}
.fa {
transform: translate(-50%, -45%);
}
}
#media (min-width: 656px) {
.container {
flex-direction: row;
flex-wrap: wrap;
align-self: flex-start;
}
label {
margin-bottom: 20px;
}
}
function phoneNumber(phone) {
var phoneno = /^\d{9}|\d{10}|\d{11}$/;
return phoneno.test(phone);
}
$('input[type="tel"]').on('keyup', function() {
var $label = $(this).closest('label');
if ($(this).val().trim() != '') {
if ($(this).is('#phone')) {
if (phoneNumber($(this).val())) {
$label.attr('data-valid', 'valid');
} else {
$label.attr('data-valid', 'error');
console.log("this works")
}
} else {
$label.attr('data-valid', 'valid');
console.log("this works")
}
} else {
$label.removeAttr('data-valid');
console.log("this works")
}
});
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\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,}))$/;
return re.test(email);
}
$('input[type="text"]').on('keyup', function() {
var $label = $(this).closest('label');
if ($(this).val().trim() != '') {
if ($(this).is('#email')) {
if (validateEmail($(this).val())) {
$label.attr('data-valid', 'valid');
} else {
$label.attr('data-valid', 'error');
console.log("this works")
}
} else {
$label.attr('data-valid', 'valid');
console.log("this works")
}
} else {
$label.removeAttr('data-valid');
console.log("this works")
}
});
test = function() {
if ($("#first_name").val() && $("#last_name").val() && $("#email").val() && $("#phone").val() && $("#city").val() && $("#state").val() && $("#company").val()) {
$("#sub").removeAttr("disabled");
}
}
You are checking email validation on textbox keyup event, but jquery does not consider autofill as a keyup event. It can not even read the filled value using autofill.
Instead of keyup event, you can use focusout event to solve your issue.
Here is the updated jsfiddle
function phoneNumber(phone) {
var phoneno = /^\d{9}|\d{10}|\d{11}$/;
return phoneno.test(phone);
}
$('input[type="tel"]').on('keyup', function() {
var $label = $(this).closest('label');
if ($(this).val().trim() != '') {
if ($(this).is('#phone')) {
if (phoneNumber($(this).val())) {
$label.attr('data-valid', 'valid');
} else {
$label.attr('data-valid', 'error');
console.log("this works")
}
} else {
$label.attr('data-valid', 'valid');
console.log("this works")
}
} else {
$label.removeAttr('data-valid');
console.log("this works")
}
});
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\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,}))$/;
return re.test(email);
}
$('input[type="text"]').on('focusout', function() {
var $label = $(this).closest('label');
if ($(this).val().trim() != '') {
if ($(this).is('#email')) {
if (validateEmail($(this).val())) {
$label.attr('data-valid', 'valid');
} else {
$label.attr('data-valid', 'error');
console.log("this works")
}
} else {
$label.attr('data-valid', 'valid');
console.log("this works")
}
} else {
$label.removeAttr('data-valid');
console.log("this works")
}
});
test = function() {
if ($("#first_name").val() && $("#last_name").val() && $("#email").val() && $("#phone").val() && $("#city").val() && $("#state").val() && $("#company").val()) {
$("#sub").removeAttr("disabled");
}
}
body {
color: #fff;
background-color: #30bda6;
text-align: center;
}
form {
color: #fff;
background-color: #30bda6;
text-align: center;
font-family: Lato;
}
* {
box-sizing: border-box;
}
.form-title {
font-size: 38px;
color: #fff;
font-family: "Lato";
letter-spacing: 70px;
}
input {
font-size: 15px;
height: 48px;
margin-top: 8px;
}
input[type="tel"] {
width: 100%;
padding: 10px;
background-color: #30bda6;
border: 1px solid #fff;
font-size: 15px;
height: 48px;
}
input[type="text"] {
width: 100%;
padding: 10px;
background-color: #30bda6;
border: 1px solid #fff;
font-size: 15px;
}
input:focus {
background-color: #fff;
}
input[type="text"]:focus {
background-color: #fff;
}
input[type="text"]:visited {
background-color: #fff;
}
input[type="tel"]:focus {
background-color: #fff;
}
input[type="tel"]:visited {
background-color: #fff;
}
.container {
display: flex;
flex-direction: column;
padding: 5px 0;
}
textarea {
width: 100%;
background-color: #30bda6;
border: 1px solid #fff;
}
textarea:focus {
background-color: #fff;
}
#co {
flex-basis: 100%;
max-width: 100%;
}
label:nth-last-child(-n+2) {
flex-basis: 100%;
max-width: 100%;
}
select,
label {
height: 50px;
width: 48%;
margin: 2% 1%;
text-align: left;
font-family: "Lato";
font-size: 15px;
}
#sub {
border-radius: 6px;
width: 120px;
height: 35px;
text-transform: uppercase;
display: block;
margin-top: 48px;
font-size: 16px;
border: none;
}
#sub2 {
border-radius: 6px;
width: 120px;
height: 35px;
text-transform: uppercase;
display: block;
margin-top: 48px;
font-size: 16px;
border: none;
}
label {
position: relative;
}
.fa {
position: absolute;
bottom: 0;
right: 0;
transform: translate(-50%, 65%);
opacity: 0;
transition: opacity .5s, color .5s;
}
[data-valid] .fa {
opacity: 1;
color: #00594C;
}
[data-valid="valid"] .fa {
color: #00594C;
}
[data-valid="error"] .fa {
color: #AB0000;
}
.error {
display: none;
color: #AB0000;
font-size: .7em;
position: absolute;
left: 10px;
top: 0;
transform: translateY(150%);
font-size: 12px;
margin-top: 2px;
}
[data-valid="error"] .error {
display: block;
}
input#sub2:not([disabled]) {
background-color: #fff;
color: #00AB8E;
}
input#sub:not([disabled]) {
background-color: #fff;
color: #F68D2E;
;
}
#thankyou {
display: none;
}
#thankyou.success {
display: block;
text-align: center;
}
#tessellate-page input:focus {
background-color: #fff !important;
;
}
#tessellate-page textarea:focus {
background-color: #fff !important;
;
}
#tessellate-page input[type="text"] {
width: 100%;
padding: 10px;
background-color: #30bda6;
border: 1px solid #fff;
}
#comments_label {
margin-top: 8px;
}
#media (max-width: 656px) {
label {
width: 98%;
height: 70px;
}
.fa {
transform: translate(-50%, -45%);
}
}
#media (min-width: 656px) {
.container {
flex-direction: row;
flex-wrap: wrap;
align-self: flex-start;
}
label {
margin-bottom: 20px;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet" />
<form class="container" action="https://webto.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8" method="POST">
<label>First Name
<input id="first_name" maxlength="40" name="first_name" size="20" type="text" onkeyup="test()" required><i class="fa fa-check-circle" aria-hidden="true"></i>
</label>
<label>Last Name
<input id="last_name" maxlength="80" name="last_name" size="20" type="text" onkeyup="test()"><i class="fa fa-check-circle" aria-hidden="true"></i>
</label>
<label>Email
<span class="error">Please enter a valid email address</span>
<input id="email" maxlength="80" name="email" size="20" type="text" onkeyup="test()"><i class="fa fa-times-circle-o" aria-hidden="true"></i>
</label>
<label>Phone
<span class="error">Please enter a valid phone number</span>
<input id="phone" maxlength="80" name="phone" size="20" type="tel" onkeyup="test()"><i class="fa fa-check-circle" aria-hidden="true"></i>
</label>
<label>City
<input id="city" name="city" maxlength="40" size="20" type="text" onkeyup="test()"><i class="fa fa-check-circle" aria-hidden="true"></i>
</label>
<label>State/Province
<input id="state" maxlength="20" name="state" size="20" type="text" onkeyup="test()"><i class="fa fa-check-circle" aria-hidden="true"></i>
</label>
<label id="co">Company
<input id="company" name="company" type="text" onkeyup="test()"><i class="fa fa-check-circle" aria-hidden="true"></i>
</label>
<label>Comments
<textarea id="comments" name="" id="" cols="30" rows="10" onkeyup="test()"></textarea>
<input id="sub" type="submit" disabled="disabled" />
</label>
<div>
<select hidden="true" id="00N6A000008yXMN" name="00N6A000008yXMN" title="Product Interest">
<option value="">--None--</option>
<option selected="selected" value="Visiant">Visiant</option>
<option value="Tessellate">Tessellate</option>
</select><br>
<select hidden="true" id="lead_source" name="lead_source">
<option value="">--None--</option>
<option value="Internal">Internal</option>
<option value="Trade Show">Trade Show</option>
<option selected="selected" value="Website">Website</option>
<option value="Direct Marketing">Direct Marketing</option>
<option value="Social Media">Social Media</option>
<option value="Other">Other</option>
</select><br>
</div>
</form>
I would suggest disabling auto fill functionality with some tricks if this is bothering you. Handling a browser functionality with DOM is not always a good way.
Chrome is ignoring read-only fields for auto fill. You can load your input fields as read-only and on hover make them editable
<input type="email" name="email" readonly>