Javascript cannot submit form with empty field validation - javascript

I have a small issue with my code not submitting my form. Once I fill out the form and press the submit button, nothing simply happens, it seems like the form is not being submitted. In practice, this code should check whether there are any empty fields and if so, it prompts a message instructing to fill out the fields. If every field filled out, submit the form.
function storeUser() {
var userObject = {};
userObject.username = document.getElementById("username").value;
userObject.email = document.getElementById("inputEmail").value;
userObject.password = document.getElementById("inputPassword").value;
userObject.passwordConfirm = document.getElementById("inputPasswordConfirm").value;
userObject.mobileNumber = document.getElementById("inputNumber").value;
userObject.score = 0;
if (userObject.password !== userObject.passwordConfirm) {
document.getElementById("Warning").innerHTML = "Your password doesn't match.";
return false;
}
if (userObject.username === "") {
document.getElementById("Warning").innerHTML = "";
document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
}
if (userObject.email === " " ) {
document.getElementById("Warning").innerHTML = "";
document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
}
if (userObject.password === " ") {
document.getElementById("Warning").innerHTML = "";
document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
}
if (userObject.passwordConfirm === " ") {
document.getElementById("Warning").innerHTML = "";
document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
}
if (userObject.mobileNumber === " ") {
document.getElementById("Warning").innerHTML = "";
document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
return false;
}
else {
return true;
}
localStorage[userObject.email] = JSON.stringify(userObject);
document.getElementById("Result").innerHTML = "Success! You have registered your account.";
As you most probably noticed, I'm a complete novice to this. Aynone could lead me the right way?
EDIT:
<form class="form-container" name="registerForm" onsubmit="return false">
<p><b>Please fill out all fields to register your account</b></p>
<div class="form-group">
<input type="text" class="form-control" id="username" aria-describedby="username" placeholder="Username" minlength=3 required>
</div>
<div class="form-group">
<input type="email" class="form-control" id="inputEmail" aria-describedby="emailHelp" placeholder="Enter email" required>
</div>
<div class="form-group">
<input type="password" class="form-control" id="inputPassword" placeholder="Password" required>
</div>
<div class="form-group">
<input type="password" class="form-control" id="inputPasswordConfirm" placeholder="Confirm password" required>
</div>
<div class="form-group">
<input type="tel" class="form-control" id="inputNumber" placeholder="Mobile number" pattern="^\s*\(?(020[7,8]{1}\)?[ ]?[1-9]{1}[0-9{2}[ ]?[0-9]{4})|(0[1-8]{1}[0-9]{3}\)?[ ]?[1-9]{1}[0-9]{2}[ ]?[0-9]{3})\s*$" required>
</div>
<button type="submit" onclick="storeUser()" class="btn btn-primary regstrbtn">Register</button>
<p id="Result"></p>
<p id="Warning" style="color: red;"></p>
</form>

Looking at your code I found a number of problems:
Invalid telephone number regexp: you are using the following regexp to validate the telephone number field, but it has a missing character:
^\s*\(?(020[7,8]{1}\)?[ ]?[1-9]{1}[0-9{2}[ ]?[0-9]{4})|(0[1-8]{1}[0-9]{3}\)?[ ]?[1-9]{1}[0-9]{2}[ ]?[0-9]{3})\s*$
// missing ] after 0-9 ^^
(I am going to ignore the fact that the regular expression has placeholder 'Mobile number' yet only accepts landline phone numbers for inner and outer London in the UK.)
You are showing validation error messages if the email, password, confirm-password and telephone number fields contain a single space:
if (userObject.email === " " ) {
You probably want to be comparing the values against an empty string instead:
if (userObject.email === "" ) {
The end of your storeUser() function is as follows:
if (userObject.mobileNumber === " ") {
document.getElementById("Warning").innerHTML = "";
document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
return false;
}
else {
return true;
}
localStorage[userObject.email] = JSON.stringify(userObject);
document.getElementById("Result").innerHTML = "Success! You have registered your account.";
When do we reach the last two lines, the one that writes to local storage and the one that shows the success message?
If the telephone number field contains a single space, then a warning message appears and the function returns false.
If the telephone number field contains anything other than a single space, the function returns true.
The last two lines are unreachable. They are never executed because the function returns before it gets to them.
What you probably want to do is to get rid of the else clause and add return true; at the bottom, i.e.:
if (userObject.mobileNumber === " ") {
document.getElementById("Warning").innerHTML = "";
document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
return false;
}
localStorage[userObject.email] = JSON.stringify(userObject);
document.getElementById("Result").innerHTML = "Success! You have registered your account.";
return true;
Inconsistent use of return false;. If the passwords don't match, or the telephone number field isn't filled out, the function returns false. There is no corresponding return false; line for the username, email, password and confirm-password fields. Add this line for each of these fields.
You aren't clearing the warning message if the form is successfully completed. Add the line
document.getElementById("Warning").innerHTML = "";
to the end of your function.
Incidentally you have various pairs of lines
document.getElementById("Warning").innerHTML = "";
document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
but the first line in each pair is unnecessary because the empty-string value you assign to the inner HTML of the warning element is immediately replaced by the warning message assigned in the second line. You can delete the first line of each such pair.

You can simply manage this using HTML5 form field validators, please find below code snippet:
body {
font-family: Helvetica, Arial;
font-size:12px;
}
h1 {
font-size:200%;
}
legend {
padding:0 5px;
text-align:right;
}
fieldset > div {
margin:10px 0;
}
fieldset > legend + div {
margin-top:0;
}
fieldset > div:last-child {
margin-bottom:0;
}
label {
display:inline-block;
width:100px;
}
input {
width:200px;
}
input[type="number"] {
width:30px;
}
div > input[type="submit"] {
background: #ccc;
border:1px solid #999;
width:auto;
}
input:required {
background:hsl(180, 50%, 90%);
border:1px solid #999;
}
input:optional {
background:hsl(300, 50%, 90%);
border:1px dotted hsl(180, 50%, 90%);
}
input:valid,
input:in-range {
background:hsl(120, 50%, 90%);
border-color:hsl(120, 50%, 50%);
}
input:invalid,
input:out-of-range {
border-color:hsl(0, 50%, 50%);
background:hsl(0, 50%, 90%);
}
.help {
display:none;
font-size:90%;
}
input:focus + .help {
display:inline-block;
}
div.submit {
margin-left:100px;
}
<form action="" method="post">
<fieldset>
<legend>Booking Details</legend>
<div>
<label for="name">Name:</label>
<input id="name" name="name" value="" required pattern="[A-Za-z-0-9]+\s[A-Za-z-'0-9]+" title="firstname lastname" aria-required="true" aria-describedby="name-format">
<span id="name-format" class="help">Format: firstname lastname</span>
</div>
<div>
<label for="email">Email:</label>
<input type="email" id="email" name="email" value="" required aria-required="true">
</div>
<div>
<label for="website">Website:</label>
<input type="url" id="website" name="website" value="">
</div>
<div>
<label for="numTickets"><abbr title="Number">No.</abbr> of Tickets:</label>
<input type="number" id="numTickets" name="numTickets" value="" required aria-required="true" min="1" max="4">
</div>
<div class="submit">
<input type="submit" value="Submit">
</div>
</fieldset>
</form>

Related

How Do I Add An Error Message To An Incorrect Input With JS? [duplicate]

This question already has answers here:
how to check confirm password field in form without reloading page
(15 answers)
Closed 10 months ago.
I am trying to add some error messages to my inputs through JS, but I am not exactly sure how I should go about this, and everything I've tried does not function well.
I am trying to display an error, and prevent the form from submitting, if there is an error.
<form novalidate>
<label for="password">
<input type="password" name="password" id="password" placeholder="Password*" required minlength="8" />
<span id='pwmessage'></span>
</label>
<label for="confirmpassword">
<input type="password" name="confirm_password" id="confirm_password" placeholder=" Confirm password*" required minlength="8" />
<span id='cpwmessage'></span>
</label>
<button>Submit</button>
</form>
Just try this one! In here, the form won't be submitted if the password or confirm password is missing or the confirm password is not same as the first password.
function empty() {
if (document.getElementById("password").value == "") {
document.getElementById("pwmessage").innerHTML = "Enter at least one character to the password field";
return false;
}
if (document.getElementById("confirm_password").value != document.getElementById("password").value) {
document.getElementById("cpwmessage").innerHTML = "Please check your password and try again";
return false;
};
}
<form novalidate action='process.php' method='get'>
<label for="password">
<input type="password" name="password" id="password" placeholder="Password*" required minlength="8" /><br>
<span id='pwmessage'></span><br>
</label>
<label for="confirmpassword">
<input type="password" name="confirm_password" id="confirm_password" placeholder=" Confirm password*" required minlength="8" /><br>
<span id='cpwmessage'></span><br>
</label>
<input type="submit" value="submit" onClick="return empty()" />
</form>
Thanks and best regards!
There are plenty of form validation tutorials out there to give you further inspiration.
This version makes use of data attributes and is very scalable without the need for more javascript. More work will be needed for additional input types but should be enough to get you started.
//Set valudation on blur for each of the elements
document.querySelectorAll("[data-customvalidate] input").forEach(function(element) {
element.addEventListener("blur", function() {
validateField(this)
});
});
//Set form validation
document.querySelectorAll("[data-customvalidate").forEach(function(element) {
element.addEventListener("submit", function(event) {
let isNotValid = false;
//Go through each of the input element
this.querySelectorAll("input").forEach(function(input) {
//Validate the input and set the isNotValid flg
if (validateField(input) && !isNotValid) {
isNotValid = true;
}
});
//Stop the form submit if not valid
if (isNotValid) {
event.preventDefault();
}
});
});
//Main Validation Funtion
function validateField(field) {
let attributes = field.getAttributeNames();
let parent = field.parentNode
let errorField = parent.querySelector(".formError");
let isError = false;
//Required Vlidation
if (attributes.includes("required") && field.value === "") {
errorField.textContent = `The ${field.dataset.errorfieldname} field is required`;
isError = true;
//Min Length Validation
} else if (attributes.includes("minlength") && (field.value.length < field.getAttribute("minlength"))) {
errorField.textContent = `The mininmum length for ${field.dataset.errorfieldname} field is ${field.getAttribute("minlength")} characters`;
isError = true;
//Match Validation
} else if (attributes.includes("data-mustmatch")) {
let elementToMatch = document.getElementById(field.dataset.mustmatch);
if (elementToMatch.value !== field.value) {
errorField.textContent = `The ${elementToMatch.dataset.errorfieldname} and ${field.dataset.errorfieldname} do not match`;
isError = true;
}
}
parent.classList.toggle("error", isError);
return isError;
}
label {
display: block;
}
label:not(.error)>.formError {
display: none;
}
label>.formError {
color: red;
font-weight: bold;
padding-left: 1em;
}
<form novalidate data-customvalidate>
<label for="password">
<input type="password" name="password" id="password" placeholder="Password*" required minlength="8" data-errorfieldname="Password" />
<span class="formError"></span>
</label>
<label for="confirmpassword">
<input type="password" name="confirm_password" id="confirm_password" placeholder=" Confirm password*" required minlength="8" data-errorfieldname="Confirm Password" data-mustmatch="password" data-mustmatcherror= "Password and Confirm Password do not match" />
<span class="formError"></span>
</label>
<button>Submit</button>
</form>

eventListener works on click 1. But fails on click 2

So i am making a signup form with action="signup.inc.php" But im handling the validation in javascript.
If the fields are empty or the password don't match the input gets a red border and the placeholder is replaced.
This works perfectly on the first click. But as soon as i click again he just shoots to signup.inc.php.
I need those validations to be done before we go to the signup.inc.php file.
let signupForm = document.getElementById('signupForm');
let firstname = document.getElementById('firstname');
let lastname = document.getElementById('lastname');
let email = document.getElementById('email');
let username = document.getElementById('username');
let password = document.getElementById('password');
let passwordRepeat = document.getElementById('passwordRepeat');
let result = false;
function showError(input, message) {
let formControl = input.parentElement;
formControl.className = 'formControl error';
let error = input;
error.placeholder = message;
}
function showSucces(input) {
let formControl = input.parentElement;
formControl.className = 'formControl succes';
}
function requiredFields(inputArr) {
inputArr.forEach(function (input){
if (input.value.trim() === ''){
showError(input, 'this field is required');
} else {
showSucces(input);
result = true;
}
});
}
function matchPasswords(input1, input2) {
if (input1.value !== input2.value) {
showError(input2, "These passwords don't match");
} else {
result = true;
}
}
/* Eventlistener */
signupForm.addEventListener('submit', function(e){
if (result !== true) {
requiredFields ([firstname, lastname, email, username, password, passwordRepeat]);
matchPasswords (password, passwordRepeat);
e.preventDefault();
} else {
result = true;
}
});
.signupFormWrap {
margin-bottom: 15px;
}
.signupFormWrap,
.formControl {
width: 400px;
display: flex;
flex-direction: column;
}
.formControl label {
font-size: 1.2rem;
}
.formControl>input[type=text],
input[type=email],
input[type=password] {
padding-left: 10px;
font-size: 1rem;
line-height: 1.8;
}
.button {
margin-top: 15px;
margin-bottom: 15px;
}
.formControl.error>input {
border: 1px solid red;
}
.formControl.succes>input {
border: 1px solid green;
}
<form name="signupForm" id="signupForm" action="assets/php/signup.inc.php" method="POST">
<div class="signupFormWrap">
<div class="formControl">
<label for="firstname">Firstname</label>
<input type="text" name="firstname" id="firstname" placeholder="Fill in your firstname here..">
</div>
<div class="formControl">
<label for="lastname">lastname</label>
<input type="text" name="lastname" id="lastname" placeholder="Fill in your lastname here..">
</div>
<div class="formControl">
<label for="email">Email</label>
<input type="email" name="email" id="email" placeholder="Fill in your email here..">
</div>
<div class="formControl">
<label for="username">Username</label>
<input type="text" name="username" id="username" placeholder="Fill in your username here..">
</div>
<div class="formControl">
<label for="password">Password</label>
<input type="password" name="password" id="password" placeholder="fill in your password here..">
</div>
<div class="formControl">
<label for="passwordRepeat">Verify your password</label>
<input type="password" name="passwordRepeat" id="passwordRepeat" placeholder="Verify your password">
</div>
<button type="submit" name="submit" class="button">Sign up</button>
</div>
</form>
Your problem is that if any of the inputs are valid, result is set to true and so on the next submit the inputs are not checked and the form submits. You can work around that by always testing all the inputs, returning the error status from each input checking function and checking that they all return true:
let signupForm = document.getElementById('signupForm');
let firstname = document.getElementById('firstname');
let lastname = document.getElementById('lastname');
let email = document.getElementById('email');
let username = document.getElementById('username');
let password = document.getElementById('password');
let passwordRepeat = document.getElementById('passwordRepeat');
function showError(input, message) {
let formControl = input.parentElement;
formControl.className = 'formControl error';
let error = input;
error.placeholder = message;
}
function showSucces(input) {
let formControl = input.parentElement;
formControl.className = 'formControl succes';
}
function requiredFields(inputArr) {
result = true;
inputArr.forEach(function(input) {
if (input.value.trim() === '') {
showError(input, 'this field is required');
result = false;
} else {
showSucces(input);
}
});
return result;
}
function matchPasswords(input1, input2) {
result = true;
if (input1.value !== input2.value) {
showError(input2, "These passwords don't match");
result = false;
}
return result;
}
/* Eventlistener */
signupForm.addEventListener('submit', function(e) {
let result = true;
result = result && requiredFields([firstname, lastname, email, username, password, passwordRepeat]);
result = result && matchPasswords(password, passwordRepeat);
if (!result) {
e.preventDefault();
}
});
.signupFormWrap {
margin-bottom: 15px;
}
.signupFormWrap,
.formControl {
width: 400px;
display: flex;
flex-direction: column;
}
.formControl label {
font-size: 1.2rem;
}
.formControl>input[type=text],
input[type=email],
input[type=password] {
padding-left: 10px;
font-size: 1rem;
line-height: 1.8;
}
.button {
margin-top: 15px;
margin-bottom: 15px;
}
.formControl.error>input {
border: 1px solid red;
}
.formControl.succes>input {
border: 1px solid green;
}
<form name="signupForm" id="signupForm" action="assets/php/signup.inc.php" method="POST">
<div class="signupFormWrap">
<div class="formControl">
<label for="firstname">Firstname</label>
<input type="text" name="firstname" id="firstname" placeholder="Fill in your firstname here..">
</div>
<div class="formControl">
<label for="lastname">lastname</label>
<input type="text" name="lastname" id="lastname" placeholder="Fill in your lastname here..">
</div>
<div class="formControl">
<label for="email">Email</label>
<input type="email" name="email" id="email" placeholder="Fill in your email here..">
</div>
<div class="formControl">
<label for="username">Username</label>
<input type="text" name="username" id="username" placeholder="Fill in your username here..">
</div>
<div class="formControl">
<label for="password">Password</label>
<input type="password" name="password" id="password" placeholder="fill in your password here..">
</div>
<div class="formControl">
<label for="passwordRepeat">Verify your password</label>
<input type="password" name="passwordRepeat" id="passwordRepeat" placeholder="Verify your password">
</div>
<button type="submit" name="submit" class="button">Sign up</button>
</div>
</form>
change all validation functions like
function matchPasswords(input1, input2) {
if (input1.value !== input2.value) {
showError(input2, "These passwords don't match");
return false;
}
return true;
}
signupForm.addEventListener('submit', function(e){
if(!requiredFields ([firstname, lastname, email, username, password, passwordRepeat]) &&
!matchPasswords (password, passwordRepeat)){
e.preventDefault();
}
});

Validate login form through JavaScript (Suggestion)

I have used pure JavaScript to validate this login form consider the below example and also check out the live demo here https://codepen.io/uicreation/pen/xpdbKe
hope it will be help you to understand how JavaScript validation is works.
Live Demo
if(document.getElementsByClassName('firstForm')[0]){
document.getElementsByClassName('firstForm')[0].onsubmit = function(e){
e.preventDefault();
var field = this;
var email = field.querySelector('input[type=email]');
var pass = field.querySelector('input[type=password]');
var regex = /^(([^<>()[\]\\.,;:\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,}))$/;
if(!regex.test(email.value)){
console.log("enter a valid email address")
} else if(pass.value.length < 8){
console.log("password should be greater than 8 characters")
} else {
console.log("success!")
}
}
}
form {
margin: 30px 0 0 30px;
}
fieldset {
padding:5px;
}
label {
min-width:60px;
display: inline-block;
}
input[type=submit]{
margin-top:5px;
margin-left:5px;
}
<form class="firstForm" novalidate>
<fieldset>
<label>Email</label>
<input type="email" name="email" placeholder="Enter Email" />
</fieldset>
<fieldset>
<label>Password</label>
<input type="password" name="password" placeholder="Enter Password" />
</fieldset>
<input type="submit" value="Login" />
</form>

JQuery addClass working in a very odd manner

I have a form with 3 inputs: 2 text inputs for a Username and E-mail and a third password input for, you guessed it, a password.
I'm validating these input fields in JQuery and when an input is either empty or doesn't match it's format, it adds a class to the input with a red border. The code goes as follows:
if ($("input#username").val().length < 6) {
$("input#username").addClass('input-error');
next_step = false;
} else if (!isEmail($("#email").val())) {
$("#email").addClass('input-error');
next_step = false;
} else if (!isPassword($("#pwd").val())) {
$("#pwd").addClass('input-error');
next_step = false;
}
else {
$(this).removeClass('input-error');
next_step = true;
}
It works perfectly with both Username and E-mail fields, and it also works if the Password field is empty, but even though it validates perfectly, the addClass() doesn't work if the Password doesn't meet it's requirements (At least one Uppercase letter and one number).
This is what the browser console shows:
As you can see, it kind of adds the class, but then not really.
What is happening? If you need the HTML code and/or the CSS code, tell me!
Thanks for your attention!
EDIT
Here is the HTML and CSS as requested:
<fieldset>
<div class="form-bottom">
<img src="img/gbsnlogo.svg" alt="GBSN Research" name="GBSN Research" width="50%" class="signupLogo" />
<br>
<br>
<br>
<div class="form-group">
<label for="username"><h1>USERNAME:</h1></label>
<input type="text" class="form-control" id="username" placeholder="Enter username..." name="username">
</div>
<div class="form-group">
<label for="email"><h1>E-MAIL:</h1></label>
<input type="text" class="form-control" id="email" placeholder="Enter e-mail..." name="email">
</div>
<div class="form-group">
<label for="pwd"><h1>PASSWORD:</h1></label>
<input type="password" class="form-control" id="pwd" placeholder="Enter password..." name="pwd">
</div>
<div class="text-center">
<button type="button" class="btn-next btn-nav"><h1>NEXT</h1></button>
</div>
</div>
</fieldset>
and the CSS:
.form-control {
height: 40px;
border: 2px solid black;
border-radius: 0;
font-size: 14px;
}
.form-control:focus {
border: 2px solid black;
box-shadow: 0;
}
.input-error {
border-color: #FF2859;
}
This is working for me.
Please comment what is still not working if you have this kind of setup?
function isEmail(email) { // dummy example
return email.indexOf("#")>1;
}
function isPassword(passwd) { // dummy example
return passwd.indexOf("x")>=0; // must contain x
}
$(function() {
$(".btn-next").on("click", function() {
$(".form-group input").removeClass('input-error');
var next_step = true,
user = $("#username").val(),
email = $("#email").val(),
pwd=$("#pwd").val();
if (user.length < 6) {
$("#username").addClass('input-error');
next_step = false;
} else if (!isEmail(email)) {
$("#email").addClass('input-error');
next_step = false;
} else if (!isPassword(pwd)) {
$("#pwd").addClass('input-error');
next_step = false;
}
console.log(next_step);
});
});
.form-control {
height: 40px;
border: 2px solid black;
border-radius: 0;
font-size: 14px;
}
.form-control:focus {
border: 2px solid black;
box-shadow: 0;
}
.input-error {
border-color: #FF2859;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<fieldset>
<div class="form-bottom">
<img src="img/gbsnlogo.svg" alt="GBSN Research" name="GBSN Research" width="50%" class="signupLogo" />
<br>
<br>
<br>
<div class="form-group">
<label for="username"><h1>USERNAME:</h1></label>
<input type="text" class="form-control" id="username" placeholder="Enter username..." name="username">
</div>
<div class="form-group">
<label for="email"><h1>E-MAIL:</h1></label>
<input type="text" class="form-control" id="email" placeholder="Enter e-mail..." name="email">
</div>
<div class="form-group">
<label for="pwd"><h1>PASSWORD:</h1></label>
<input type="text" class="form-control" id="pwd" placeholder="Enter password..." name="pwd">
</div>
<div class="text-center">
<button type="button" class="btn-next btn-nav"><h1>NEXT</h1></button>
</div>
</div>
</fieldset>
From what I see from the image you posted
I can only speculate this is what happened.
The line [input#pwd.form-control.input-error] was evaluated immediately when it got printed to the console. So that mean at that time, the dom does have the class input error in it. However, when you expand it, the dom got re-evaluated again. And at that time, the dom's class input-error got removed, so you don't see it anymore. I was able to prove this by running $('#pwd').addClass('input-error') and $('#pwd').removeClass('input-error') in that order, image below
Based on that, I suspect you have another logic in the code that remove the class shortly after you have added the class to the dom, highly possibly $(this).removeClass('input-error');.

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