Validating contact form with javascript - javascript

The code below obviously has a lot of errors or some other things missing but I am beginner to JavaScript trying to make my own projects.
I tried to make this contact form with JavaScript validation from my own and a bit with a search but I'm stuck because validation form doesn't work at all. I would appreciate if you help me fixing this, thank you.
let name = document.querySelector('.name');
let email = document.querySelector('.email');
let submit = document.querySelector('.submit');
function validateName() {
if (name === null) {
error.innerHTML = 'Name cannot be blank';
return false;
} else if (name < characters.length < 3) {
error.innerHTML = 'Use more than 3 characters';
return false;
}
}
function validateEmail() {
if (email === null) {
error.innerHTML = 'Email cannot be blank';
return false;
} else if (email < characters.length < 5) {
error.innerHTML = 'Use more than 3 characters on email';
return false;
}
}
function submitForm() {
document.querySelector('.submit').submit();
}
.info {
display: flex;
justify-content: center;
padding-top: 20px;
text-align: center;
background-color: mediumslateblue;
font-size: 22px;
}
.name {
margin-top: 10px;
}
.email {
margin-top: 10px;
}
.mesage {
margin-top: 10px;
}
.submit {
margin-bottom: 10px;
}
<div class="info">
<div class="info-form">
<input class="name" type="text" placeholder="Your Name">
<br>
<input class="email" type="email" placeholder="Your Email">
<br>
<textarea name="message" class="mesage" cols="36" rows="3" placeholder="Your message"></textarea>
<br>
<button class="submit" action="/submit.php" onclick="submitForm()">Submit</button>
</div>
</div>

Well, you only defined validation methods but don't use them, that's why they have no effect.
You should add event listeners like onchange (or oninput, depending on when you'd like to show error messages) to your fields.
For instance:
<input class="name" type="text" placeholder="Your Name" onchange="validateName()">
Actually, you have multiple more problems:
error is undefined: you should create another element and find it in JS
you have to use element.value, not element to access a value of input
you have undefined characters used in a weird way in your checks; to check the length of content, use element.value.length
Here's a snippet with these fixes:
let name = document.querySelector('.name');
let email = document.querySelector('.email');
let submit = document.querySelector('.submit');
let error = document.querySelector('.error');
function validateName() {
if (!name.value) {
error.innerHTML = 'Name cannot be blank';
return false;
} else if (name.value.length < 3) {
error.innerHTML = 'Use more than 3 characters';
return false;
}
}
function validateEmail() {
if (!email.value) {
error.innerHTML = 'Email cannot be blank';
return false;
} else if (email.value.length < 5) {
error.innerHTML = 'Use more than 3 characters on email';
return false;
}
}
function submitForm() {
document.querySelector('.submit').submit();
}
.info {
display: flex;
justify-content: center;
padding-top: 20px;
text-align: center;
background-color: mediumslateblue;
font-size: 22px;
}
.name {
margin-top: 10px;
}
.email {
margin-top: 10px;
}
.mesage {
margin-top: 10px;
}
.submit {
margin-bottom: 10px;
}
<div class="info">
<div class="info-form">
<input class="name" type="text" placeholder="Your Name" onchange="validateName()">
<br>
<input class="email" type="email" placeholder="Your Email" onchange="validateEmail()">
<br>
<textarea name="message" class="mesage" cols="36" rows="3" placeholder="Your message"></textarea>
<div class="error"></div>
<br>
<button class="submit" action="/submit.php" onclick="submitForm()">Submit</button>
</div>
</div>
Moreover, I'd make some more improvements to the code, namely
use event.target inside event handlers instead of calcing the elements globally (note the difference in usage inside html too);
clear the error div when the content is ok!
why multiple return false instead of one in the end of the handler?
you don't use the submit variable, get rid of it; does submitForm do anything useful? (submits on submit??) Not sure, but it seems it should be removed, too
let error = document.querySelector('.error');
function validateName(event) {
let name = event.target;
if (!name.value) {
error.innerHTML = 'Name cannot be blank';
} else if (name.value.length < 3) {
error.innerHTML = 'Use more than 3 characters';
} else {
error.innerHTML = '';
}
return false;
}
function validateEmail(event) {
let email = event.target;
if (!email.value) {
error.innerHTML = 'Email cannot be blank';
} else if (email.value.length < 5) {
error.innerHTML = 'Use more than 3 characters on email';
} else {
error.innerHTML = '';
}
return false;
}
function submitForm() {
document.querySelector('.submit').submit();
}
.info {
display: flex;
justify-content: center;
padding-top: 20px;
text-align: center;
background-color: mediumslateblue;
font-size: 22px;
}
.name {
margin-top: 10px;
}
.email {
margin-top: 10px;
}
.mesage {
margin-top: 10px;
}
.submit {
margin-bottom: 10px;
}
<div class="info">
<div class="info-form">
<input class="name" type="text" placeholder="Your Name" onchange="validateName(event)">
<br>
<input class="email" type="email" placeholder="Your Email" onchange="validateEmail(event)">
<br>
<textarea name="message" class="mesage" cols="36" rows="3" placeholder="Your message"></textarea>
<div class="error"></div>
<br>
<button class="submit" action="/submit.php" onclick="submitForm()">Submit</button>
</div>
</div>

Alot of your syntax and validation methods are off. Few tips: you need to use name.value and email.value to get the values of the elements, you also need to use name.value.length instead of email < characters.length < 5 and change the button type to submit and you can negate having to call it in JS.
Below is a working snippet based on the code you posted. I believe it does what you want.
let error = document.getElementById('error');
function validateName() {
let name = document.getElementById('name');
if (!name.value) {
error.innerHTML = 'Name cannot be blank';
return false;
} else if (name.value.length < 3) {
error.innerHTML = 'Use more than 3 characters on name';
return false;
}
}
function validateEmail() {
let email = document.getElementById('email');
if (!email.value) {
error.innerHTML = 'Email cannot be blank';
return false;
} else if (email.value.length < 5) {
error.innerHTML = 'Use more than 5 characters on email';
return false;
}
}
function submitForm() {
error.innerHTML = ""
validateEmail()
validateName()
}
.info {
display: flex;
justify-content: center;
padding-top: 20px;
text-align: center;
background-color: mediumslateblue;
font-size: 22px;
}
.name {
margin-top: 10px;
}
.email {
margin-top: 10px;
}
.mesage {
margin-top: 10px;
}
.submit {
margin-bottom: 10px;
}
<div class="info">
<div class="info-form">
<input id="name" type="text" placeholder="Your Name">
<br>
<input id="email" type="email" placeholder="Your Email">
<br>
<textarea name="message" class="mesage" cols="36" rows="3" placeholder="Your message"></textarea>
<br>
<button class="submit" type = "submit" action="/submit.php" onclick="submitForm()">Submit</button>
<div id="error">
</div>
</div>
</div>

You've written your JS function validateName and validateEmails but you aren't calling those functions anywhere. Instead of selecting the .submit button inside of submitForm(), call those functions. The line you have inside of submitForm is doing nothing. onclick() within your HTML handles the calling of the function submitForm(), and submitForm() should then validate your form.
Edit: you can also call validateName and validateEmails when the email or name fields are edited.

Yeah, like what the other contributors said, the validate functions are written well, they just aren't being called.
You can either add them to the onchange property of your input elements, or call it in your submitform function like so:
function validateName() {
if (name === null) {
error.innerHTML = 'Name cannot be blank';
return false;
} else if (name < characters.length < 3) {
error.innerHTML = 'Use more than 3 characters';
return false;
}
return true;
}
function validateEmail() {
if (email === null) {
error.innerHTML = 'Email cannot be blank';
return false;
} else if (email < characters.length < 5) {
error.innerHTML = 'Use more than 3 characters on email';
return false;
}
return true;
}
function submitForm(){
if(validateName() && validateEmail()){
//Do whatever submitting entails
}
}
Also remember to add an error div to your html to display the errors, and to create an error querySelector variable like you did with name, email and submit.
You're doing great! Keep up the good work!

Here's something that works to a minimum using your current code. I added comments to explain what is going on. Don't hesitate to ask me for any clarifications. Like you said, code can be improved further but I didn't want to change too much and confuse you.
let name = document.querySelector('.name');
let email = document.querySelector('.email');
let submit = document.querySelector('.submit');
let error = document.querySelector('#error'); //Get's the span in the html where the errors will be shown.
function validateName() {
//Get the text value of name with name.value and care with an empty string.
if (name.value === "") {
error.innerHTML = 'Name cannot be blank';
return false;
//Get the number of character in the value of the name and see if you have less than 3.
} else if (name.value.length < 3) {
error.innerHTML = 'Use more than 3 characters';
return false;
}
}
function validateEmail() {
//Get the text value of name with name.value and compare with an empty string.
if (email.value === "") {
error.innerHTML = 'Email cannot be blank';
return false;
//Get the number of characters in the value of the email and see if you have less than 5.
} else if (email.value.length < 5) {
error.innerHTML = 'Use more than 3 characters on email';
return false;
}
}
function submitForm() {
//Instead of calling the function .submit (that doesn't exist). Call the verification functions that you made.
validateName();
validateEmail();
}
.info {
display: flex;
justify-content: center;
padding-top: 20px;
text-align: center;
background-color: mediumslateblue;
font-size: 22px;
}
.name {
margin-top: 10px;
}
.email {
margin-top: 10px;
}
.mesage {
margin-top: 10px;
}
.submit {
margin-bottom: 10px;
}
<div class="info">
<div class="info-form">
<span id="error"></span>
<input class="name" type="text" placeholder="Your Name">
<br>
<input class="email" type="email" placeholder="Your Email">
<br>
<textarea name="message" class="mesage" cols="36" rows="3" placeholder="Your message"></textarea>
<br>
<button class="submit" action="/submit.php" onclick="submitForm()">Submit</button>
</div>
</div>

Related

how to sumbit form with addEventListener

I saw this code from the internet and I want to understand somethings - https://codepen.io/FlorinPop17/pen/OJJKQeK
And I try to POST form after all the parms are valid.
The valid is in the client browser (and also in server side).
I want after the all inputs are valid to POST the inputs to <form action="/postdata">
<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="florinpop17" 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="a#florin-pop.com" 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 check</label>
<input type="password" placeholder="Password two" id="password2"/>
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<button>Submit</button>
</form>
JS -
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() {
// trim to remove the whitespaces
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, 'Not a valid email');
} else {
setSuccessFor(email);
}
if(passwordValue === '') {
setErrorFor(password, 'Password cannot be blank');
} else {
setSuccessFor(password);
}
if(password2Value === '') {
setErrorFor(password2, 'Password2 cannot be blank');
} 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');
formControl.className = 'form-control error';
small.innerText = message;
}
function setSuccessFor(input) {
const formControl = input.parentElement;
formControl.className = 'form-control success';
}
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);
}
So, after checking the validity and make sure that all valid, then send a fetch request with POST method to /postdata with a body equal to object with inputs value.
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();
if (checkInputs()) {
fetch('/postdata', {
body: {
username: username.value,
email: email.value,
password: password.value,
password2: password2.value,
},
method: 'POST',
})
}
});
function checkInputs() {
// trim to remove the whitespaces
const usernameValue = username.value.trim();
const emailValue = email.value.trim();
const passwordValue = password.value.trim();
const password2Value = password2.value.trim();
let isValid = true
if(usernameValue === '') {
setErrorFor(username, 'Username cannot be blank');
isValid = false;
} else {
setSuccessFor(username);
}
if(emailValue === '') {
setErrorFor(email, 'Email cannot be blank');
isValid = false;
} else if (!isEmail(emailValue)) {
setErrorFor(email, 'Not a valid email');
} else {
setSuccessFor(email);
}
if(passwordValue === '') {
setErrorFor(password, 'Password cannot be blank');
isValid = false;
} else {
setSuccessFor(password);
}
if(password2Value === '') {
setErrorFor(password2, 'Password2 cannot be blank');
isValid = false;
} else if(passwordValue !== password2Value) {
setErrorFor(password2, 'Passwords does not match');
isValid = false;
} else{
setSuccessFor(password2);
}
return isValid;
}
function setErrorFor(input, message) {
const formControl = input.parentElement;
const small = formControl.querySelector('small');
formControl.className = 'form-control error';
small.innerText = message;
}
function setSuccessFor(input) {
const formControl = input.parentElement;
formControl.className = 'form-control success';
}
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);
}
Critical Details
There are a ton of changes to OP, but only a few changes are actually important. The <form> attributes should be as follows:
<form id="main" action="/postdata" method="POST">
The action value is a relative location, it's correct as long as the <form> is in the same domain as the server. Otherwise, it'll be something like: https://serverDomain.com/postData.
Next, the event handler triggered by the "submit" event needs to check each "div.form-control" to see if they all have the class: ".success" after the checkInputs() function runs. If they do, then the <form> needs to be submitted.
main.addEventListener('submit', function(e) {
e.preventDefault();
checkInputs();
if (Array.from(document.querySelectorAll(".form-control"))
.every(div => div.classList.contains("success"))) {
this.submit();
}
});
The example above should work with the OP unchanged. Note the anonymous event handler is not an arrow function. IMO arrow function event handlers are limiting because the keyword this is useless (see addEventListener, arrow functions, and `this`).
Other Changes
Although many things have changed from the OP in the example, fundamentally they are the same, it's just I wrote it a little better.
Some elements were changed into form controls which provided added features, made more easily accessible, and even better semantically.
<div class="form-control">
<!--from-
--to-->
<fieldset name="formControl">
<small>
<!--from-
--to-->
<output name="message">
HTMLFormElement and
HTMLFormControlsCollection interfaces are used to reference the <form> and it's form controls. The syntax is succinct and specialized so there's more control with less code.
Functions isUser() and isPass() are added to impose real criteria for username and password values.
The error() function (in OP it is setErrorFor()) has an third optional #param {string} criteria - which adds a <input type="button"> that opens a <dialog> that displays the given string criteria.
When the <form> is successfully submitted, the data is sent to a live test server. The response is captured and displayed in the <iframe> located at the bottom of the page.
const main = document.forms.main;
const fc = main.elements;
const user = fc.username;
const email = fc.email;
const pass = fc.password;
const check = fc.check;
const details = fc.details;
const modal = details.parentElement;
main.addEventListener('submit', function(e) {
e.preventDefault();
checkInputs();
if (Array.from(fc.formControl).every(fSet => fSet.classList.contains("valid"))) {
this.submit();
}
});
main.addEventListener("click", function(e) {
const clicked = e.target;
if (clicked !== this) {
if (clicked.name === "more") {
modal.showModal();
details.value = clicked.dataset.text;
}
if (clicked.id === "close") {
modal.close();
}
}
});
function checkInputs() {
const userData = user.value.trim();
const emailData = email.value.trim();
const passData = pass.value.trim();
const checkData = check.value.trim();
if (userData === "") {
error(user, "Username is blank, enter data");
} else if (!isUser(userData)) {
error(user, "Username must have at least 8 characters", "A minimum of 8 characters in any combination of lower case letters, upper case letters, and digits");
} else {
valid(user);
}
if (emailData === "") {
error(email, "Email is blank, enter data");
} else if (!isEmail(emailData)) {
error(email, "Email address is invalid", "Email address must have 1 or more characters, an ampersand: #, followed by 1 or more charaters, a dot: ., followed by 1 or more characters");
} else {
valid(email);
}
if (passData === "") {
error(pass, "Password is blank, enter data");
} else if (!isPass(passData)) {
error(pass, "Password must have at least 8 character", "Password must have a minimum of 8 characters with at least 1 lower case letter, 1 upper case letter, 1 digit, and 1 symbol (!, #, #, $, %, ^, &, *, _, =, +, -)");
} else {
valid(pass);
}
if (checkData === "") {
error(check, "Password check is blank, enter data");
} else if (passData !== checkData) {
error(check, "Passwords do not match");
} else {
valid(check);
}
}
function error(input, message, criteria) {
const set = input.parentElement;
const msg = set.elements.message;
set.classList.add('error');
set.classList.remove('valid');
msg.value = message;
if (criteria) {
msg.insertAdjacentHTML("beforeend", `<input name="more" class="more" type="button" value="..." data-text="${criteria}">`);
}
}
function valid(input) {
const set = input.parentElement;
const msg = set.elements.message;
set.classList.add('valid');
set.classList.remove('error');
msg.value = "";
}
function isUser(name) {
const rgx = /[a-zA-Z0-9]{8,}/g;
return rgx.test(name);
}
function isEmail(address) {
const rgx = /\S+#\S+\.\S+/g;
return rgx.test(address);
}
function isPass(secret) {
const rgx = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##$%^&*_=+-]).{8,}$/g;
return rgx.test(secret);
}
#import url('https://fonts.googleapis.com/css?family=Open+Sans:400,500&display=swap');
* {
box-sizing: border-box;
}
html {
font: 400 2ch/1.15 'Open Sans'
}
body {
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
margin: 0;
background: #9b59b6;
}
form {
padding: 30px 40px;
}
fieldset {
position: relative;
margin-bottom: 15px;
border: 0;
}
label {
display: inline-block;
margin-bottom: 5px;
color: #fff;
}
.data {
display: block;
width: 100%;
padding: 10px;
border: 2px solid #f0f0f0;
border-radius: 4px;
font: inherit;
}
.data:focus {
border-color: #777;
outline: 0;
}
.success .data {
border-color: #2ecc71;
}
.error .data {
border-color: #e74c3c;
}
i {
position: absolute;
top: 42px;
right: 15px;
visibility: hidden;
}
.valid i.fa-check-circle {
color: #2ecc71;
visibility: visible;
}
.error i.fa-exclamation-circle {
color: #e74c3c;
visibility: visible;
}
output {
display: inline-block;
position: absolute;
bottom: -15px;
left: 15px;
padding: 4px;
border-radius: 4px;
font-size: 0.75rem;
color: #e74c3c;
background: #fff;
visibility: hidden;
}
button {
display: block;
width: 100%;
margin: 20px auto;
padding: 10px;
border: 2px solid #8e44ad;
border-radius: 4px;
color: #fff;
font: inherit;
background: #8e44ad;
cursor: pointer;
}
.more {
position: absolute;
top: -1px;
right: -1.75rem;
padding-bottom: 3px;
cursor: pointer;
visibility: hidden;
}
.error output,
.error .more {
visibility: visible;
}
#details {
position: static;
margin-bottom: 10px;
visibility: visible;
}
#close {
float: right;
cursor: pointer;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" rel="stylesheet">
<form id="main" action="https://httpbin.org/post" method="POST" target="response">
<fieldset name="formControl">
<label for="username">Username</label>
<input id="username" name="username" class="data" type="text" placeholder="user01" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<output name="message"></output>
</fieldset>
<fieldset name="formControl">
<label for="email">Email</label>
<input id="email" name="email" class="data" type="text" placeholder="user01#email.com" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<output name="message"></output>
</fieldset>
<fieldset name="formControl">
<label for="password">Password</label>
<input id="password" name="password" class="data" type="password" placeholder="Password" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<output name="message"></output>
</fieldset>
<fieldset name="formControl">
<label for="check">Password Check</label>
<input id="check" name="check" class="data" type="password" placeholder="Password as entered previously" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<output name="message"></output>
</fieldset>
<button>Submit</button>
<iframe name="response"></iframe>
<dialog>
<output id="details"></output>
<input id="close" type="button" value="OK">
</dialog>
</form>

HTML Form Using JavaScript Valildation

I working on Javascript validation task as i am beginner in Javascript i was stuck in Js validation code codepen.Can, Anyone Please help out of this and point me in right direction.
Thanks in advance.
jQuery(document).ready(function($) {
function formValidation() {
var firstname = document.getElementById('product');
if (firstname.value.length == 0) {
document.getElementById('head').innerText = "* All fields are mandatory *";
firstname.focus();
return false;
}
if (inputAlphabet(firstname, "* For your name please use alphabets only *")) {
return true;
}
return false;
}
function textNumeric(inputtext, alertMsg) {
var numericExpression = /^[0-9]+$/;
if (inputtext.value.match(numericExpression)) {
return true;
}
else {
document.getElementByClass('price').innerText = alertMsg;
inputtext.focus();
return false;
}
}
function inputAlphabet(inputtext, alertMsg) {
var alphaExp = /^[a-zA-Z]+$/;
if (inputtext.value.match(alphaExp)) {
return true;
}
else {
document.getElementById('product').innerText = alertMsg;
inputtext.focus();
return false;
}
}
});
body {
background: #f5f5f5;
}
.product-container {
display: flex;
justify-content: center;
align-items: center;
padding: 100px;
}
input#product {
max-width: 200px;
padding: 5px 20px;
}
input.price {
max-width: 227px;
padding: 5px 4px;
width: 100%;
}
input.qnty {
max-width: 235px;
width: 100%;
padding: 5px 4px;
}
input[type="submit"] {
font-size: 14px;
font-family: 'Roboto', sans-serif;
font-weight: 500;
color: #000000;
padding: 5px 10px;
letter-spacing: 0.6px;
}
<!DOCTYPE html>
<html>
<head>
<title>Product Order</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
<script src="custom.js"></script>
</head>
<body>
<div class="product-container">
<form action="submit" method="POST">
Product Name: <input type="text" name="name" value="" required id="product" ><br><br>
Unit Price: <input type="number" name="Price" value= "" required class="price" pattern="\d+(\.\d{2})?"><br><br>
Quantity: <input type="number" name="Quantity" value="" min="1" max="10" required class="qnty price"><br><br>
<input type = "submit" name = "submit" value = "Get Total Amount">
</form>
</div>
</body>
</html>
You're doing the same thing I was doing when I started using jQuery... mixing JavaScript with jQuery.
You don't need to create a function to validate the form. I'd first change your submit button to this:
<button type="button" id="submitButton">Submit</button>
Then use jQuery to listen for the button click:
$('#submitButton').on('click', function() {
var product = $('#product').val();
var price = $('.price').val();
var name = $('#name').val();
// check if name input has a value, if blank, then display error message
if(name == "") {
alert('You must enter a name');
return false;
}
if(product == '//whatever you want to check here') {
// display message
}
if(price == '// check if the input is blank') {
// return error message
}
else {
// do something
}
});
The if/else inside your button click is your validation.
I see a ton of errors in your very small code. Your Jquery code looks very bad. You are creating functions but never using them, You don't have to create functions for form validation. You can use Jquery event listeners to check if the user has performed some action like (submit, Focus, Blur etc.,) and when you receive the event you have to perform an action and clearly innerText does not work on input boxes. Go through this article on form validation using Jquery.
You should do basic google search before posting a question here.

Javascript form validation for phone numbers

Trying to create a form with pretty simple validation and I'm curious as to two things.
One; how do I check if a form is empty?
Two; on the phone number field how would I only accept numbers in this format:
xxx-xxxx (where X is a number)
Here is what I have done so far:
HTML:
<form onsubmit="return false" method="post" name="myForm">
<div class="form-block">
<label>Name: </label>
<input type="text" name="name" id="name" />
<span id="name-error" class="error"></span>
</div>
<div class="form-block">
<label>Phone Number: </label>
<input type="text" name="phone" id="phone" />
<span id="phone-error" class="error"></span>
</div>
<input type="submit" id="mysubmit" name="submit" onclick="validate()" />
</form>
CSS:
a, p, h1, h2, h3, h4, h5, h6, li, label, span {
font-family: sans-serif;
}
#mysubmit {
display: block;
margin-top: 10px;
}
span.error {
color: red;
font-weight: bold;
}
.form-block {
display: block;
width: 100%;
margin: 10px 0;
}
label {
display: inline-block;
width: 150px;
text-align: right;
}
JS:
validate = function() {
var name = document.getElementById("name").value;
var phone = document.getElementById("phone").value;
if(/^[a-zA-Z]*$/.test(name)) {
document.getElementById("name-error").innerHTML = "Good.";
} else {
document.getElementById("name-error").innerHTML = "Invalid. Only letters.";
}
if(isNaN(phone)) {
document.getElementById("phone-error").innerHTML = "Can only contain numbers";
} else {
document.getElementById("phone-error").innerHTML = "Good.";
}
};
You can test if the value of a form element is empty by simply checking for an empty string.
I've already posted something that will help you access and iterate through form fields.
// ES5: a very crude validation check
// your form field elements should share a class in order to collect them all
var formElements = document.querySelectorAll('.your-form-field-class');
// set a flag to keep track of whether you have an empty field
var containsEmptyField = false
i,
l = formElements.length;
for (; i < l; i++) {
if (formElements[i].value === '') {
containsEmptyField = true;
// do something in response to an empty field
// the break is to stop looping since you've found
// a match
break;
}
}
// ES6: a very crude validation check
const formElements = document.querySelector('#some-form').elements;
let containsEmptyField = false;
for (let element of formElements) {
if (element.value === '') {
containsEmptyField = true;
break;
}
}
I haven't tested it properly, but the regex for the phone number, might look something like this:
(/^(\d){3,3}\-(\d){4,4}$/).test(someNumber)
// returns true if value matches or false if it doesn't

Display a fading jQuery Alert Message without using traditional javascript alert-box

I have the following form, my question is implementing a fadding JQuery Alert message without using the normal js alertBox
the Html Form
<form name="userLogin" action="success.php" onsubmit="validateInputField()" method="post">
UserName: <input type="text" name="username" placeholder="Username">
password: <input type="password" name="pwd" placeholder="Password">
<input type="submit" value="Submit">
</form>
javaScript code
<script>
function validateInputField() {
var x = document.forms["userLogin"]["username"].value;
var y = document.forms["userLogin"]["pwd"].value;
if (x == null || x == "") {
alert("Name must be filled out");
return false;
}
if (y == null || y == "") {
alert("Password must be filled out");
return false;
}
}
</script>
You can simply add a div and display your error message within that div and use fadeIn and fadeOut to animate the same.
function validateInputField() {
var x = document.forms["userLogin"]["username"].value;
var y = document.forms["userLogin"]["pwd"].value;
if (x == null || x == "") {
$(".alert").find('.message').text("Name must be filled out");
$(".alert").fadeIn("slow",function(){
setTimeout(function(){
$(".alert").fadeOut("slow");
},4000);
});
return false;
}
if (y == null || y == "") {
$(".alert").find('.message').text("Name must be filled out");
$(".alert").fadeIn("slow",function(){
setTimeout(function(){
$(".alert").fadeOut("slow");
},4000);
});
return false;
}
}
.hide {
display: none;
}
.alert {
background: red;
position: absolute;
top: 50%;
left: 40%;
padding:20px;
}
.message {
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="userLogin" action="success.php" onsubmit="validateInputField()" method="post">
UserName:
<input type="text" name="username" placeholder="Username">password:
<input type="password" name="pwd" placeholder="Password">
<input type="submit" value="Submit">
</form>
<div class="alert hide">
<div class="message">
</div>
</div>
To be more optimized
function validateInputField() {
var x = document.forms["userLogin"]["username"].value;
var y = document.forms["userLogin"]["pwd"].value;
if (x == null || x == "") {
showAlert("Name must be filled out");
return false;
}
if (y == null || y == "") {
showAlert("Password must be filled out");
return false;
}
}
function showAlert(message) {
$(".alert").find('.message').text(message);
$(".alert").fadeIn("slow", function() {
setTimeout(function() {
$(".alert").fadeOut("slow");
}, 4000);
});
}
.hide {
display: none;
}
.alert {
background: red;
position: absolute;
top: 50%;
left: 40%;
padding:20px;
}
.message {
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="userLogin" action="success.php" onsubmit="validateInputField()" method="post">
UserName:
<input type="text" name="username" placeholder="Username">password:
<input type="password" name="pwd" placeholder="Password">
<input type="submit" value="Submit">
</form>
<div class="alert hide">
<div class="message">
</div>
</div>
Why not make your own?
A simple fadeIn() and fadeOut() can create a really cool "alert-box" and is super easy to use :)
Login Page:-
First You have to Create Your Login Code & at Last use header() with URL get Variable.
<?php
header('Location:view.php?status=login');
?>
Dashboard Page:-
<?php
if(isset($_GET['status']) == 'login'){
echo '<div class="alert alert-success">
Login Successfully !!!
</div>';
}
?>
jQuery Part:-
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" rel="stylesheet">
$('document').ready(function(){
$(".alert").fadeIn(1000).fadeOut(5000);
});
</script>

Form validation not showing

I am trying to use some code from a form validation example and tailor it to my own form but it doesn't seem to be working. There is a message that is supposed to appear when a user enters a name,phone number or email incorrectly e.g 'please enter a valid name'.I don't understand javascript that well so am struggling to try and find the problem. There aren't any console problems if that helps it is probably a naming issue?
jsFiddle
HTML
<form>
<div class="formColumn2">
<label for="name">
<span class="textStyle">Full Name*</span><input type="text" id="name"><br>
<span id="nameMessage" class="message">You must have a valid name</span>
</label>
<label for="email"><span class="textStyle">Email*</span>
<input type="text" id="email"><br>
<span id="emailMessage" class="message">You must have a valid email</span>
</label>
<label for="phoneNumber">
<span class="textStyle">Phone Number*</span>
<input type="text" id="phoneNumber"><br>
<span id="phoneMessage" class="message">You must have a valid phone number</span>
</label>
<input type="submit" id="submit" value="Submit">
</div>
</form>
CSS
.textStyle {
width: 150px;
display: inline-block;
}
.formColumn2 {
margin-top:-80px;
margin-left: 50px;
}
select{
width:200px;
margin:10px 0;
}
input[type=text],
input[type=password]{
width:200px;
margin:10px 0;
}
.message{
display: none;
}
input[type=submit]{
background: #fff;
border: 1px solid black;
cursor: pointer;
}
input[type=text].error,
input[type=password].error{
border: 3px solid red;
color: red;
}
Javascript
var nameInput = document.querySelector('#name');
var emailInput = document.querySelector('#email');
var phoneInput = document.querySelector ('#phoneNumber');
function displayError(fieldname, message) {
var input_field = document.querySelector('#' + fieldname);
var error_box = document.querySelector('#' + fieldname + 'Message');
addClass (input_field, 'error');
error_box.style.display = 'block';
error_box.innerHTML = message;
}
function hideError(fieldname){
var input_field = document.querySelector('#'+fieldname);
var error_box = document.querySelector('#'+fieldname+'Message');
removeClass (input_field, 'error');
error_box.style.display = 'none';
}
function addClass(html_element,class_str) {
if(html_element.className.indexOf(class_str) == -1){
html_element.className += ' '+class_str;
}
}
function removeClass(html_element, class_str){
if(html_element.className.indexOf(class_str) != -1){
html_element.className = html_element.className.replace(class_str, '');
}
}
nameInput.onblur = function(){
if(!nameInput.value){
valid = false;
displayError('name', 'Please enter your name');
}else if(!isValidName(nameInput.value)){
valid = false;
displayError('name', 'That name has invalid characters');
}else{
hideError('name');
}
emailInput.onblur = function(){
if(!emailInput.value){
valid = false;
displayError('email', 'Please enter your email');
}else if(!isValidEmail(emailInput.value)){
valid = false;
displayError('email', 'The email field is invalid');
}else{
hideError('email');
}
}
phoneInput.onblur = function(){
if(!emailInput.value){
valid = false;
displayError('phone', 'Please enter your number');
}else if(!isValidEmail(emailInput.value)){
valid = false;
displayError('email', 'The phone number field is invalid');
}else{
hideError('phone');
}
}
submitButton.onclick = function(){
var valid = true;
return valid;
}
function isValidName(str){
var namePattern = new RegExp('^[a-zA-Z \s\'-]{1,}$');
return namePattern.test(str);
}
function isValidEmail(str) {
var emailPattern = /^(([^<>()[\]\\.,;:\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 emailPattern.test(str);
}
if you will use jQuery, it will be less complicated.
if that you need to use
$('.formClass').validate();
and in html
just put required in text fields, whom you want they not to be empty.
<form class="formCLass">
<input type="text" name="username" required/>
<input type="email" name="email" required/>
</form>

Categories

Resources