I have developed some code in bootstrap and I am getting an error while I was validating the fields (name, email). Please help me out.
This is the code for the form:
<div class="container">
<h3 class="text-center">CONTACT</h3>
<p class="text-center"><em>I love my Fans!</em></p>
<div class="row test">
<div class="col-md-4">
<p><span class="glyphicon glyphicon-map-marker"></span>4429, Rainier Street, Irving, Texas ,United States</p>
<p><span class="glyphicon glyphicon-phone"></span>Phone:Phone</p>
<p><span class="glyphicon glyphicon-envelope"></span>Email: Email</p>
</div>
<div class="col-md-8">
<div class="row">
<div class="col-sm-6 form-group">
<input class="form control" id="name" placeholder="Name" type="text" onBlur="txt_Blur(this,'errorName')" />
<span id="errorName" style="display:none;">Please enter a valid name!</span>
</div>
<div class="col-sm-6 form-group">
<input class="form control" id="email" name="email" placeholder="Email" type="email" required>
<span id="errorName" style="display:none;">Please enter a valid email!</span>
</div>
</div>
<div class="textarea">
<textarea class="form-control" id="comments" name="comments" placeholder="Comment" rows="5"></textarea>
<span id="errorName" style="display:none">Please enter your comments!</span>
</div>
<br>
<div class="row">
<div class="col-md-12 form-group">
<button class="btn pull-right" type="submit" onclick="button_Click()">Send</button>
</div>
</div>
</div>
</div>
</div>
The JavaScript for validation below:
function txt_Blur(ref, errorId) {
if (ref.value == "") {
document.getElementById(errorId).style = "color:red;";
} else {
document.getElementById(errorId).style = "display:none;";
}
}
function button_Click() {
if (document.getElementById("name")).value == "") {
document.getElementById("errorName").style = "color:red;";
} else {
document.getElementById("errorName").style = "display:none;";
}
if (document.getElementById("email")).value == "") {
document.getElementById("errorName").style = "color:red;";
} else {
document.getElementById("errorName").style = "display:none;";
}
}
I need the error displayed when someone tries to leave the name field empty and goes to the next text field (email).
Related
I have a simple form page, where there are several form validations. So far, the RESET button only clears the text field values.
But I need the validation messages to clear when the RESET button is pressed.
So far I have seen jQuery methods, but have no idea of implementing it as I am still learning.. Are there any other methods to do this without jQuery..?
Any help would be highly appreciated.
Here's my code...
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="author" content="Koshila">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Contact|Frittery</title>
<link rel="stylesheet" href="about.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/css/bootstrap.min.css" integrity="sha384-VCmXjywReHh4PwowAiWNagnWcLhlEJLA5buUprzK8rxFgeH0kww/aWY76TfkUoSX" crossorigin="anonymous">
<script>
function validation() {
var formFname = document.getElementById("fname").value;
var formLname = document.getElementById("lname").value;
var formEmail = document.getElementById("email").value;
var formNumber = document.getElementById("pnumber").value;
//Validate first name
if (formFname.length == 0) {
document.getElementById("fnameMessage").innerHTML = "<em>You did not enter your first name</em>"
}
//Validate last name
if (formLname.length == 0) {
document.getElementById("lnameMessage").innerHTML = "<em>You did not enter your last name</em>"
}
//Validate email
if (formEmail.length == 0) {
document.getElementById("emailMessage").innerHTML = "<em>You did not enter your email</em>"
} else {
var regex = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (regex.test(formEmail) === false) {
document.getElementById("emailMessage").innerHTML = "<em>Please enter a valid email</em>"
}
}
//Validate phone
if (formNumber.length == 0) {
document.getElementById("phoneMessage").innerHTML = "<em>You did not enter your phone number</em>"
} else if (formNumber.length != 10) {
document.getElementById("phoneMessage").innerHTML = "<em>Phone Number must be exactly 10 digits</em>"
return false;
} else
return true;
}
</script>
</head>
<body>
<div class="container">
<h2>General Enquiry Form</h2>
<form method="POST" action="#" onsubmit="validation(); return false;">
<div class="form-group row">
<label class="col-form-label col-sm-2" for="fname">First Name</label>
<div class="col-sm-6">
<input class="form-control" type="text" id="fname" name="fname">
</div>
<div class="col-sm-4">
<span id="fnameMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="lname">Last Name</label>
<div class="col-sm-6">
<input class="form-control" type="text" id="lname" name="lname">
</div>
<div class="col-sm-4">
<span id="lnameMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="email">Email</label>
<div class="col-sm-6">
<input class="form-control" type="email" id="email" name="email">
</div>
<div class="col-sm-4">
<span id="emailMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="pnumber">Phone</label>
<div class="col-sm-6">
<input class="form-control" type="tel" id="pnumber" name="pnumber">
</div>
<div class="col-sm-4">
<span id="phoneMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="message">Message</label>
<div class="col-sm-10">
<textarea class="form-control" id="message" name="message" style="height: 200px;"></textarea>
</div>
</div>
<div class="form-group row">
<div class="offset-sm-2 ">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-secondary">Reset</button>
</div>
</div>
</form>
</div>
<hr>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/js/bootstrap.min.js" integrity="sha384-XEerZL0cuoUbHE4nZReLT7nx9gQrQreJekYhJD9WNWhH8nEW+0c5qq7aIo2Wl30J" crossorigin="anonymous"></script>
</body>
</html>
Don't reset them manual by repeating code. Define a custom reset function which iterates over error messages and empty all of them:
function resetForm() {
var elems = document.querySelectorAll(".text-danger");
elems.forEach(itm => {
document.getElementById(itm.id).innerHTML = ''
})
}
Also don't put any script tag in your head tag. Read more here
Full code:
function resetForm() {
var elems = document.querySelectorAll(".text-danger");
elems.forEach(itm => {
document.getElementById(itm.id).innerHTML = ''
})
}
function validation() {
var formFname = document.getElementById("fname").value;
var formLname = document.getElementById("lname").value;
var formEmail = document.getElementById("email").value;
var formNumber = document.getElementById("pnumber").value;
//Validate first name
if (formFname.length == 0) {
document.getElementById("fnameMessage").innerHTML = "<em>You did not enter your first name</em>"
}
//Validate last name
if (formLname.length == 0) {
document.getElementById("lnameMessage").innerHTML = "<em>You did not enter your last name</em>"
}
//Validate email
if (formEmail.length == 0) {
document.getElementById("emailMessage").innerHTML = "<em>You did not enter your email</em>"
} else {
var regex = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (regex.test(formEmail) === false) {
document.getElementById("emailMessage").innerHTML = "<em>Please enter a valid email</em>"
}
}
//Validate phone
if (formNumber.length == 0) {
document.getElementById("phoneMessage").innerHTML = "<em>You did not enter your phone number</em>"
} else if (formNumber.length != 10) {
document.getElementById("phoneMessage").innerHTML = "<em>Phone Number must be exactly 10 digits</em>"
return false;
} else
return true;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="author" content="Koshila">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Contact|Frittery</title>
<link rel="stylesheet" href="about.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/css/bootstrap.min.css" integrity="sha384-VCmXjywReHh4PwowAiWNagnWcLhlEJLA5buUprzK8rxFgeH0kww/aWY76TfkUoSX" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h2>General Enquiry Form</h2>
<form method="POST" action="#">
<div class="form-group row">
<label class="col-form-label col-sm-2" for="fname">First Name</label>
<div class="col-sm-6">
<input class="form-control" type="text" id="fname" name="fname">
</div>
<div class="col-sm-4">
<span id="fnameMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="lname">Last Name</label>
<div class="col-sm-6">
<input class="form-control" type="text" id="lname" name="lname">
</div>
<div class="col-sm-4">
<span id="lnameMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="email">Email</label>
<div class="col-sm-6">
<input class="form-control" type="email" id="email" name="email">
</div>
<div class="col-sm-4">
<span id="emailMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="pnumber">Phone</label>
<div class="col-sm-6">
<input class="form-control" type="tel" id="pnumber" name="pnumber">
</div>
<div class="col-sm-4">
<span id="phoneMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="message">Message</label>
<div class="col-sm-10">
<textarea class="form-control" id="message" name="message" style="height: 200px;"></textarea>
</div>
</div>
<div class="form-group row">
<div class="offset-sm-2 ">
<button onclick="validation(); return false;" class="btn btn-primary">Submit</button>
<button class="btn btn-secondary" onclick="resetForm(); return false;">Reset</button>
</div>
</div>
</form>
</div>
<hr>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/js/bootstrap.min.js" integrity="sha384-XEerZL0cuoUbHE4nZReLT7nx9gQrQreJekYhJD9WNWhH8nEW+0c5qq7aIo2Wl30J" crossorigin="anonymous"></script>
</body>
<button type="reset" class="btn btn-secondary" onclick="clearErrors();">Reset</button>
function clearErrors() {
document.getElementById("emailMessage").innerHTML = "";
// ... repeat for other messages
}
You need to call the eraseText function separately like mentioned below
function eraseText() {
document.getElementById("fnameMessage").innerHTML = "";
document.getElementById("lnameMessage").innerHTML = "";
document.getElementById("emailMessage").innerHTML = "";
document.getElementById("phoneMessage").innerHTML = "";
}
<button onClick="eraseText()" type="reset" class="btn btn- secondary">Reset</button>
As the error/validation messages are displayed within span elements of the same class text-danger you can easily query the DOM using querySelectorAll to return a nodelist and then iterate through that collection and set the span text content to an empty string.
Note that I added a name to the form and used that name within the anonymous function in the event handler. With a name assigned to the form also means that you can identify elements simply by doing something like this:
const form=document.forms.enquiry;
const formFname=form.fname;
const formLname=form.lname;
etc etc
document.querySelector('button[type="reset"]').addEventListener('click',e=>{
e.preventDefault();
document.querySelectorAll('.text-danger').forEach(span=>span.textContent='')
document.forms.enquiry.reset()
})
function validation()
{
var formFname = document.getElementById("fname").value;
var formLname = document.getElementById("lname").value;
var formEmail = document.getElementById("email").value;
var formNumber = document.getElementById("pnumber").value;
//Validate first name
if(formFname.length ==0)
{
document.getElementById("fnameMessage").innerHTML ="<em>You did not enter your first name</em>"
}
//Validate last name
if(formLname.length ==0)
{
document.getElementById("lnameMessage").innerHTML ="<em>You did not enter your last name</em>"
}
//Validate email
if(formEmail.length ==0)
{
document.getElementById("emailMessage").innerHTML ="<em>You did not enter your email</em>"
}
else
{
var regex = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(regex.test(formEmail)===false)
{
document.getElementById("emailMessage").innerHTML ="<em>Please enter a valid email</em>"
}
}
//Validate phone
if(formNumber.length ==0)
{
document.getElementById("phoneMessage").innerHTML ="<em>You did not enter your phone number</em>"
}
else if(formNumber.length !=10)
{
document.getElementById("phoneMessage").innerHTML ="<em>Phone Number must be exactly 10 digits</em>"
return false;
}
else
return true;
}
<div class="container">
<h2>General Enquiry Form</h2>
<form name='enquiry' method="POST" action="#" onsubmit="validation(); return false;">
<div class="form-group row">
<label class="col-form-label col-sm-2" for="fname">First Name</label>
<div class="col-sm-6">
<input class="form-control" type="text" id="fname" name="fname" >
</div>
<div class="col-sm-4">
<span id="fnameMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="lname">Last Name</label>
<div class="col-sm-6">
<input class="form-control" type="text" id="lname" name="lname" >
</div>
<div class="col-sm-4">
<span id="lnameMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="email">Email</label>
<div class="col-sm-6">
<input class="form-control" type="email" id="email" name="email" >
</div>
<div class="col-sm-4">
<span id="emailMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="pnumber">Phone</label>
<div class="col-sm-6">
<input class="form-control" type="tel" id="pnumber" name="pnumber">
</div>
<div class="col-sm-4">
<span id="phoneMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="message">Message</label>
<div class="col-sm-10">
<textarea class="form-control" id="message" name="message" style="height: 200px;"></textarea>
</div>
</div>
<div class="form-group row">
<div class="offset-sm-2 ">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-secondary">Reset</button>
</div>
</div>
</form>
</div>
take a look for my code
html code:
<div class="tech-news__search__container">
<div class="tech-news__search">
<input
id="subscribeInput"
type="text"
class="tech-news__search-input"
placeholder="example#gmail.com"
>
<button class="tech-news__search-button" id="subscribeButton">Subscribe</button>
</div>
<div class="resultBlock">
<p class="listOfSubscribers" id="listOfSubscribers"></p>
<div id="result"></div>
<div id="deleteAll"></div>
</div>
</div>
js code:
let node = null
let deleteAll
function renderItems() {
const items = getItem()
if (items.length) {
const listOfSubscribers = document.getElementById('listOfSubscribers')
listOfSubscribers.innerHTML = 'Subscribers'
items.map(item => {
node = document.createElement("LI");
let textnode = document.createTextNode(item);
node.appendChild(textnode);
document.getElementById("result").appendChild(node);
})
deleteAll = document.getElementById('deleteAll')
deleteAll.innerHTML = 'Delete All'
deleteAll.addEventListener('click', deleteItems)
}
}
renderItems()
function deleteItems() {
sessionStorage.removeItem('subscribers')
window.location.reload()
}
could you please tell me how to show validation message on button click ? here is my code
https://stackblitz.com/edit/angular-ugdbvg?file=src/app/app.component.html
I want to show required error message when user press submit button.
<form novalidate [formGroup]="searchForm" class="calform">
<section class="col-sm-6 bg-white pl-20 pr-20">
<div class="form-group col-sm-4 pl-0 error">
<label class="field-title mb-5">name<span class="color-red fontWt"> *</span></label>
<input type="text" placeholder="Enter name" formControlName="name">
<p class="message" [hidden]="searchForm.get('name')">Required</p>
</div>
<div class="form-group col-sm-4 pl-0 error">
<label class="field-title mb-5">last name <span class="color-red fontWt"> *</span></label>
<input type="text" placeholder="Enter last name" formControlName="lastName">
<p class="message" [hidden]="searchForm.get('lastName')">Required</p>
</div>
<button (click)="submitHandler()">submit</button>
</section>
</form>
js
this.searchForm = this.fb.group({
name: ['', Validators.required],
lastName: ['', Validators.required]
});
Add the following line to check:
<span class="error" *ngIf="!!searchForm.controls.name.errors.required && (!!searchForm.controls.name.dirty || !!searchForm.controls.name.touched)">
Name is required.
</span>
<span class="error" *ngIf="!!searchForm.controls.lastName.errors.required && (!!searchForm.controls.lastName.dirty || !!searchForm.controls.name.touched)">
lastName is required.
</span>
in your ts file:
submitHandler() {
if(this.searchForm.valid) {
// Logic
}
}
https://stackblitz.com/edit/angular-utvw23
You need to use *ngIf. Updated Stackblitz code . https://stackblitz.com/edit/angular-fzyrji
Try like this:
Use [hidden] or *ngIf
DEMO
<div class="form-group col-sm-4 pl-0 error">
<label class="field-title mb-5">name<span class="color-red fontWt"> *</span></label> {{show}}
<input type="text" placeholder="Enter name" formControlName="name"> {{searchForm.get('name').invalid}}
<p class="message" [hidden]="!(show && searchForm.get('name').invalid)">Required</p>
</div>
<div class="form-group col-sm-4 pl-0 error">
<label class="field-title mb-5">last name <span class="color-red fontWt"> *</span></label>
<input type="text" placeholder="Enter last name" formControlName="lastName">
<p class="message" [hidden]="!(show && searchForm.get('lastName').invalid)">Required</p>
</div>
<button (click)="show = true ; submitHandler();">submit</button>
</section>
</form>
I have a registration form that I would like to have multiple field validation. What I mean by this is if more than one field is not filled in it will be highlighted red. I have some code already written but instead of highlighting the field not filled in, it's highlighting all of them. I realise it is quite long winded but I'm fairly new to this. My JS code is as follows:
`function formCheck() {
var val = document.getElementById("fillMeIn").value;
var val = document.getElementById("fillMeIn2").value;
var val = document.getElementById("fillMeIn3").value;
var val = document.getElementById("fillMeIn4").value;
var val = document.getElementById("fillMeIn5").value;
var val = document.getElementById("fillMeIn6").value;
var val = document.getElementById("fillMeIn7").value;
if (val == "") {
alert("Please fill in the missing fields");
document.getElementById("fillMeIn").style.borderColor = "red";
document.getElementById("fillMeIn2").style.borderColor = "red";
document.getElementById("fillMeIn3").style.borderColor = "red";
document.getElementById("fillMeIn4").style.borderColor = "red";
document.getElementById("fillMeIn5").style.borderColor = "red";
document.getElementById("fillMeIn6").style.borderColor = "red";
document.getElementById("fillMeIn7").style.borderColor = "red";
return false;
}
else {
document.getElementById("fillMeIn").style.borderColor = "green";
document.getElementById("fillMeIn2").style.borderColor = "green";
document.getElementById("fillMeIn3").style.borderColor = "green";
document.getElementById("fillMeIn4").style.borderColor = "green";
document.getElementById("fillMeIn5").style.borderColor = "green";
document.getElementById("fillMeIn6").style.borderColor = "green";
document.getElementById("fillMeIn7").style.borderColor = "green";
}
}`
My HTML is as follows:
'<form id="mbrForm" onsubmit="return formCheck();" action="thanks.html" method="post">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
FIRST NAME:
<input id="fillMeIn" type="text" class="form-control" placeholder="First Name" >
</div>
<div class="col-md-4 vertical-gap">
LAST NAME:
<input id="fillMeIn2" type="text" class="form-control" placeholder="Last Name" >
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8 vertical-gap">
ADDRESS:
<input id="fillMeIn3" type="text" class="form-control vertical-gap" placeholder="First Line" >
<input id="fillMeIn4" type="text" class="form-control vertical-gap" placeholder="Second Line" >
<input id="fillMeIn5" type="text" class="form-control vertical-gap" placeholder="Town/City" >
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
POST CODE:
<input id="fillMeIn6" type="text" class="form-control vertical-gap" placeholder="Postcode" >
</div>
<div class="col-md-4 vertical-gap">
PHONE No:
<input type="number" class="form-control vertical-gap" placeholder="Tel no">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
EMAIL ADDRESS:
<input id="fillMeIn7" type="email" class="form-control vertical-gap" placeholder="Email address" >
</div>
<div class="col-md-2"></div>
</div>
<div class="row vertical-gap">
<div class="col-md-2"></div>
<div class="col-md-8">
DISCIPLINE:
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Cross Country"> CROSS COUNTRY
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Enduro"> ENDURO
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Downhill"> DOWNHILL
</label>
</div>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-10">
<!--<button type="button" input type="hidden" class="btn btn-success" name="redirect" value="thanks.html">SUBMIT</button>-->
<input type="submit" value="SUBMIT" class="btn btn-success btn-lg">
</div>
<div class="col-md-2"></div>
</div>
</form>'
Thanks!
You could have the ids in an Array, iterate through its values, and execute the repeatable code in a function that groups all the logic inside.
example :
["fillMeIn1", "fillMeIn2", "fillMeIn3", "fillMeIn4"].each(function(id){
// do things with id
})
Why not use the html "required" property instead?
If you want to do this with JS, you should give each variable a different name. In the code you posted you are continuously overwriting the same variable, and then, it evaluates val (which ended up being assigned to the (fill me7 value) to "", and if true, setting all the borders to red.
Set different variables, push the input values into an array when submit is triggered and loop through them if variables[i]==0, set getElementId(switch case[i] or another array with the name of the inputs[i]).bordercolor to red.
AGAIN, this sound VERY INEFFICIENT and I am not sure at all it would work. My guess is that it would take A LOT of time, and probably get timed out (except you are using some asych/try-catch kind of JS).
I would simply go for an HTML required property and then override the "required" property in CSS to make it look as you intend to. Simpler, easy and clean.
The main issue in your code is that you override the variable val each time you wrote var val = ....
Keeping your own your logic, you could write something like that.
var formModule = (function () {
var $fields = [
document.getElementById('fillMeIn'),
document.getElementById('fillMeIn2'),
document.getElementById('fillMeIn3'),
document.getElementById('fillMeIn4'),
document.getElementById('fillMeIn5'),
document.getElementById('fillMeIn6'),
document.getElementById('fillMeIn7')
];
function markInvalid($field) {
$field.style.borderColor = 'red';
}
function markValid($field) {
$field.style.borderColor = 'green';
}
return {
check: function () {
var isValid = true;
$fields.forEach(function ($f) {
if ($f.value === '') {
if (isValid) alert('Please fill in the missing fields');
isValid = false;
markInvalid($f);
}
else markValid($f);
});
return isValid;
}
};
})();
There are some extra concepts in this example which may be useful:
Working with the DOM is really slow, that's why you should
put your elements in a variable once for all and not everytime you
click on the submit button.
In my example i wrap the code with var formModule = (function () {...})();.
It's called module pattern. The goal is to prevent variables to leak in the rest of the application.
A better solution could be this one using the 'power' of html form validation:
HTML:
<form id="mbrForm" action="thanks.html" method="post">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
FIRST NAME:
<input id="fillMeIn" type="text" required class="form-control" placeholder="First Name">
</div>
<div class="col-md-4 vertical-gap">
LAST NAME:
<input id="fillMeIn2" type="text" required class="form-control" placeholder="Last Name">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8 vertical-gap">
ADDRESS:
<input id="fillMeIn3" type="text" required class="form-control vertical-gap" placeholder="First Line">
<input id="fillMeIn4" type="text" required class="form-control vertical-gap" placeholder="Second Line">
<input id="fillMeIn5" type="text" required class="form-control vertical-gap" placeholder="Town/City">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
POST CODE:
<input id="fillMeIn6" type="text" required class="form-control vertical-gap" placeholder="Postcode">
</div>
<div class="col-md-4 vertical-gap">
PHONE No:
<input type="number" class="form-control vertical-gap" placeholder="Tel no">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
EMAIL ADDRESS:
<input id="fillMeIn7" type="email" required class="form-control vertical-gap" placeholder="Email address">
</div>
<div class="col-md-2"></div>
</div>
<div class="row vertical-gap">
<div class="col-md-2"></div>
<div class="col-md-8">
DISCIPLINE:
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Cross Country"> CROSS COUNTRY
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Enduro"> ENDURO
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Downhill"> DOWNHILL
</label>
</div>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-10">
<input id="btnSubmit" type="submit" value="SUBMIT" class="btn btn-success btn-lg">
</div>
<div class="col-md-2"></div>
</div>
</form>
JS:
var formModule = (function () {
var $form = document.getElementById('mbrForm');
var $btn = document.getElementById('btnSubmit');
var $fields = [
document.getElementById('fillMeIn'),
document.getElementById('fillMeIn2'),
document.getElementById('fillMeIn3'),
document.getElementById('fillMeIn4'),
document.getElementById('fillMeIn5'),
document.getElementById('fillMeIn6'),
document.getElementById('fillMeIn7')
];
checkValidation();
$form.addEventListener('change', checkValidation);
$form.addEventListener('keyup', checkValidation);
$fields.forEach(function ($f) {
$f.addEventListener('change', function () {
markInput($f, $f.checkValidity());
});
});
function checkValidation() {
$btn.disabled = !$form.checkValidity();
}
function markInput($field, isValid) {
$field.style.borderColor = isValid ? 'green' : 'red';
}
})();
In this example, the button gets disabled until the form is valid and inputs are validated whenever they are changed.
I added required attribute in HTML inputs so they can be handled by native javascript function checkValidity(). Note that in this case inputs email and number are also correctly checked. You could also use attribute pattern to get a more powerfull validation:
<input type="text" pattern="-?[0-9]*(\.[0-9]+)?">
Hope it helps.
<script>
function validate2(id)
{
var regex = [a-z];
var ctrl = document.getElemetnById(id);
if (regex.test(ctrl.value)) {
return true;
}
else {
return false;
}
}
</script>
<script>
function TestCompanyName(txtCompanyName){
var obj = document.getElementById(txtCompanyName);
var RegEx = /THE DAMN REGULAR EXPRESSION/
if(RegEx.test(obj.value)==false)
{
alert("Invalid");
}
}
</script>
</script>
<script>
function checklname(input1)
{
var pattern=/^([a-zA-Z0-9_.-])+#([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
return pattern.test(input1);
}
if(!isvalid) {
alert('Invalid name');
document.getElementById("input1").value = "";
}
}
</script>
<script>
function phonenumber(telno) {
var phoneno = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
if(telno.value.match(phoneno))
{
return true;
}
else {
alert("message");
return false;
}
}
</script>
<script>
function phonenumber2(mobileno) {
var phoneno1 = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
if(mobileno.value.match(phoneno1))
{
return true;
}
else {
alert("message");
return false;
}
}
</script>
<script>
function validate() {
var ta = document.getElementById("ta").value;
var answer = document.getElementbyId("answer").value;
var digit1 = parseInt(document.getElementById("digit1").innerHTML);
var digit2 = parseInt(document.getElementById("digit2").innerHTML);
var sum = digit1 + digit2;
if(answer == null || answer == ""){
alert("please add the number");
return false;
}else if(answer != sum){
alert("you math is wrong");
}else if(ta == null || ta == ""){
alert("please fill in the textarea");
}else{
document.getElementById("status").innerHTML = "processing";
document.getElementById("answer").innerHTML = "";
}
}
function randomNums(){
var rand_num1 = Math.floor(Math.random() * 10) +1;
var rand_num2 = Math.floor(Math.random() * 10) +1;
document.getElementById("digit1").innerHTML = rand_num1;
document.getElementById("digit2").innerHTML = rand_num2;
}
</script
<script>
function checkEmail(inputvalue){
var pattern=/^([a-zA-Z0-9_.-])+#([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
return pattern.test(inputvalue);
}
checkEmail('rte#co') // false
checkEmail('rte#co.com') // true
</script>
<script>
var address = /^[a-zA-Z0-9-\/] ?([a-zA-Z0-9-\/]|[a-zA-Z0-9-\/] )*[a-zA-Z0-9-\/]$/;
if ( address.test($.trim($('#address').val())) == false)
{
alert('invalid address ');
}
</script>
<script>
function IsValidZipCode(zipcode) {
var isValid = /[\^$%#!#&\*:<>\?\/\\~\{\}\(\)\+|]/.test(zipcode);
if (!isValid){
alert('Invalid ZipCode');
document.getElementById("zipcode").value = "";
}
</script>
<script type="text/javascript" src="js/bootstrap-3.1.1.min.js"></script>
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<?php include("include files/favicon.php"); ?>
</head>
<body itemscope itemtype="http://schema.org/Organization">
<?php
include("include files/header.php");
?>
<?php
include("include files/navigation.php");
?>
<!--breadcrumb-->
<div id='location'>
<div id="BannerAndNavigatorHtmlBlock_StoreNavigator_pnNavigator" itemscope="" itemtype="http://schema.org/BreadcrumbList" class="btn-group btn-breadcrumb">
<span itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem" class="btn btn-success">
<a itemprop="item" href="/">
<span class="glyphicon glyphicon-home" itemprop="name">
</span>
</a>
<span itemprop="position" content="1">
</span>
</span>
</span>
<span itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem"class="btn btn-success">
<span itemprop="name">Playing Card Quote</span><span itemprop="position" content="2"></span>
</span>
</div>
</div>
<!--Main Content-->
<div class="wrapper">
<div class="container">
<div> </div>
<div class="well">
<form action="thank-you.php" method="post" id="form1" onsubmit="MM_validateForm('quantity','','R','fname','','R','email','','NisEmail','telno','','RisNum','address','','R','city','','R','state','','R','country','','R','zipcode','','R');return document.MM_returnValue && jcap();">
<fieldset>
<legend>
<h1>Fill Quote Form</h1>
</legend>
<div class="quote-form">
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6">Plastic Coated Paper :</label>
<div class="col-sm-3">
<select class="form-control" name="plastic_coated_paper" id="plastic_coated_paper" onchange="chgSelect('coatedpaper');">
<option selected value="0" id="selectpaper">Select Paper</option>
<option>Black Centered 330</option>
<option>Black Centered 320</option>
<option>Black Centered 315</option>
<option>Black Centered 305</option>
<option>Black Centered 300</option>
<option>Black Centered 280</option>
<option>White Centered 330</option>
<option>White Centered 320</option>
<option>White Centered 315</option>
<option>White Centered 305</option>
<option>White Centered 300</option>
<option>White Centered 280</option>
</select>
</div>
<div class="col-sm-3" style="text-align:center;">
</div>
<br>
<br>
<center>OR</center>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6">100% Pure Plastic : </label>
<h2>Your Contact Information :</h2>
<form action="" method="POST">
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> First Name</label>
<div class="col-sm-3">
<div>
<input name="fname" id= "id" type="text" onSubmit="" tabindex="2" required="required">
</div>
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> Last Name</label>
<div class="col-sm-3">
<div>
<label>
<input name="lname" id="input1" type="text" tabindex="2" required="required">
</label>
</div>
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> Email Id</label>
<div class="col-sm-3">
<div>
<label>
<input name="email" type="email" tabindex="2" required="required">
</label>
</div>
</div>
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<div class="col-sm-6">
</div>
<div class="col-sm-5">(Please type in a correct email address , as the quotes will be forwarded there)</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> Telephone Number</label>
<div class="col-sm-3">
<div>
<label>
<input name="telno" id="telno" type="text" tabindex="2" required="required">
</label>
</div>
</div>
<div class="col-sm-3">( Do not enter space)
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> Mobile Number</label>
<div class="col-sm-3">
<div>
<label>
<input name="mobileno" id="mobileno" type="text" tabindex="2" required="required">
</label>
</div>
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"> <i>*</i> Company Name</label>
<div class="col-sm-3">
<div>
<label>
<input type="text" name="txtCompanyName" id="txtCompanyName" required="required" onclick="TestCompanyName('txtCompanyName')">
</label>
</div>
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> Address</label>
<div class="col-sm-3">
<input id="address" class="address" type="text" name="address"
onchange="IsValidAddress(this.form.address.value)" required="required" >
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> Zip Code :</label>
<div class="col-sm-3">
<input id="zipcode" class="zipcode" type="text" name="zipcode" onchange="IsValidZipCode(this.form.zipcode.value)" required="required" >
<br />
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> City</label>
<div class="col-sm-3">
<input class="form-control" name="city" type="text" id="city" required="required" value="">
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> State</label>
<div class="col-sm-3">
<input class="form-control" name="state" type="text" id="state" value="" required ="required">
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> Country</label>
<div class="col-sm-3">
<input class="form-control" name="country" type="text" id="country" value="" required="required">
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"> Fax</label>
<div class="col-sm-3">
<input class="form-control" name="fax" type="text" id="fax" value="" required ="required">
</div>
<div class="col-sm-3">
</div>
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-6"><i>*</i> Captcha</label>
<div class="col-sm-2">
</div>
<div class="col-sm-3">
<body>
<form name="review" ACTION="newpg.html" METHOD="POST" onsubmit="return checkform(this);">
<font color="#DD0000">Enter Code ></font> <span id="txtCaptchaDiv" style="background-color:#A51D22;color:#FFF;padding:5px"></span>
<input type="hidden" id="txtCaptcha" />
<input type="text" name="txtInput" id="txtInput" size="15" />
<input type="submit" value="Submit"/>
</form>
<script type="text/javascript">
function checkform(theform){
var why = "";
if(theform.txtInput.value == ""){
why += "- Security code should not be empty.\n";
}
if(theform.txtInput.value != ""){
if(ValidCaptcha(theform.txtInput.value) == false){
why += "- Security code did not match.\n";
}
}
if(why != ""){
alert(why);
return false;
}
}
//Generates the captcha function
var a = Math.ceil(Math.random() * 9)+ '';
var b = Math.ceil(Math.random() * 9)+ '';
var c = Math.ceil(Math.random() * 9)+ '';
var d = Math.ceil(Math.random() * 9)+ '';
var e = Math.ceil(Math.random() * 9)+ '';
var code = a + b + c + d + e;
document.getElementById("txtCaptcha").value = code;
document.getElementById("txtCaptchaDiv").innerHTML = code;
// Validate the Entered input aganist the generated security code function
function ValidCaptcha(){
var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
var str2 = removeSpaces(document.getElementById('txtInput').value);
if (str1 == str2){
return true;
}else{
return false;
}
}
// Remove the spaces from the entered and generated code
function removeSpaces(string){
return string.split(' ').join('');
}
</script>
</body>
<div class="col-sm-3">
</div>
</div>
<div> </div>
<div class="row">
<div class="form-group">
<div class="col-sm-12">
<center>
<input type="submit" value="Submit" class="btn1" name="submit" id="send">
</center>
</div>
</div>
</div>
<div> </div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
<!---footer---><?php include("include files/footer.php");?>
</body>
</html>
I am not able to provide validation for captcha using validation? My function is not displaying message for me if security code did not match or security code should not be empty.
What is the problem in the program? Why is not validating my captcha properly? I tried it many times but not able to validate my captcha code
What is the error in the page for captcha validation? What is the correct validation for captcha ?
The code you posted does not have any issues. It does what it is supposed to do, generate a code and validate that the input matches it before allowing the form to be submitted.
However, if you are really interested in preventing bots from submitting the form, then this code is not going to help you at all. You generate the code on the client and save it in your input. A bot would read that input and provide the captcha with no issues at all.
EDIT: suggestion for recaptcha
I would suggest that you integrate your application with an established recaptcha provider, as is for example recaptcha. Please note that the validation of the captcha input should be performed in your server
You can find further details for recaptcha here.
The code is working as you might expect. Please review the fiddle I had to made no change at all.
https://jsfiddle.net/43m63ezf/
HTML
<label>Captcha</label>
<form name="review" ACTION="palying-cards-quote.php" METHOD="POST" onsubmit="return checkform(this);">
<font color="#DD0000">Enter Code </font> <span id="txtCaptchaDiv" style="background-color:#A51D22;color:#FFF;padding:5px"></span>
<input type="hidden" id="txtCaptcha" />
<input type="text" name="txtInput" id="txtInput" size="15" />
<input type="submit" value="Submit" />
</form>
JS
function checkform(theform) {
var why = "";
if (theform.txtInput.value == "") {
why += "- Security code should not be empty.\n";
}
if (theform.txtInput.value != "") {
if (ValidCaptcha(theform.txtInput.value) == false) {
why += "- Security code did not match.\n";
}
}
if (why != "") {
alert(why);
return false;
}
}
//Generates the captcha function
var a = Math.ceil(Math.random() * 9) + '';
var b = Math.ceil(Math.random() * 9) + '';
var c = Math.ceil(Math.random() * 9) + '';
var d = Math.ceil(Math.random() * 9) + '';
var e = Math.ceil(Math.random() * 9) + '';
var code = a + b + c + d + e;
document.getElementById("txtCaptcha").value = code;
document.getElementById("txtCaptchaDiv").innerHTML = code;
// Validate the Entered input aganist the generated security code function
function ValidCaptcha() {
var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
var str2 = removeSpaces(document.getElementById('txtInput').value);
if (str1 == str2) {
return true;
} else {
return false;
}
}
// Remove the spaces from the entered and generated code
function removeSpaces(string) {
return string.split(' ').join('');
}
I am using bootstrap in my web page and trying to make a form on that page.
I've used the standard classes of bootstrap for making the form. I've already used the validation to check the emptiness of the form. I just want to add the email and phone number validation further in my code.
The code for the form and the and the already declared validation script is given below:
<script type="text/javascript">
function validateText(id) {
if ($("#" + id).val() == null || $("#" + id).val() == "") {
var div = $("#" + id).closest("div");
div.removeClass("has-success");
$("#glypcn" + id).remove();
div.addClass("has-error has-feedback");
div.append('<span id="glypcn' + id
+ '" class="glyphicon glyphicon-remove form-control-feedback"></span>');
return false;
} else {
var div = $("#" + id).closest("div");
div.removeClass("has-error");
$("#glypcn" + id).remove();
div.addClass("has-success has-feedback");
div.append('<span id="glypcn' + id
+ '" class="glyphicon glyphicon-ok form-control-feedback"></span>');
return true;
}
}
$(document).ready(function() {
$("#contactButton").click(function() {
if (!validateText("contactName")) {
return false;
}
if (!validateText("contactEmail")) {
return false;
}
if (!validateText("contactMobile")) {
return false;
}
if (!validateText("contactAddress1")) {
return false;
}
if (!validateText("contactCity")) {
return false;
}
$("form#contactForm").submit();
}
);
});
<form class="form-horizontal" id="contactForm">
<div class="form-group">
<label for="contactName" class="col-sm-2 control-label">Name<sup>*</sup></label>
<div class="col-sm-10">
<input type="text" class="form-control" id="contactName">
</div>
</div>
<div class="form-group">
<label for="contactEmail" class="col-sm-2 control-label">Email<sup>*</sup></label>
<div class="col-sm-10">
<input type="email" class="form-control" id="contactEmail">
</div>
</div>
<div class="form-group">
<label for="contactMobile" class="col-sm-2 control-label">Mobile
Number<sup>*</sup>
</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="contactMobile">
</div>
</div>
<div class="form-group">
<label for="contactAddress1" class="col-sm-2 control-label">Address1<sup>*</sup></label>
<div class="col-sm-10">
<textarea class="form-control" rows="5" id="contactAddress1"></textarea>
</div>
</div>
<div class="form-group">
<label for="contactAddress2" class="col-sm-2 control-label">Address2</label>
<div class="col-sm-10">
<textarea class="form-control" rows="5" id="contactAddress2"></textarea>
</div>
</div>
<div class="form-group">
<label for="contactCity" class="col-sm-2 control-label">City<sup>*</sup></label>
<div class="col-sm-10">
<select class="form-control" id="contactCity">
<option>KURUKSHETRA</option>
<option>PEHOWA</option>
<option>KARNAL</option>
</select>
</div>
</div>
<div class="col-xs-12 col-lg-12 col-md-12 col-sm-12">
<p>
<span id="helpBlock" class="help-block"><sup>*</sup> marked fields
are compulsory!</span>
</p>
</div>
<div class="checkbox">
<label> <input type="checkbox"> I agree to the <a href="#">Terms of
Service</a>
</label>
</div>
<div class="col-xs-12 col-lg-12 col-md-12 col-sm-12">
<center>
<p>
<button type="button" class="btn btn-primary btn-lg btn-block"
id="contactButton">
Submit <span class="glyphicon glyphicon-arrow-right"> </span>
</button>
</p>
</center>
</div>
</form>
You should use a regex like mentioned in the comment.
The regex is also mentioned here.
var email_regex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i;
Here is a working example.
you have to require additional plugin for this.
Try this:
<form id="emailForm" class="form-horizontal">
<div class="form-group">
<label class="col-xs-3 control-label">Email address</label>
<div class="col-xs-7">
<input type="text" class="form-control" name="email" />
</div>
</div>
</form>
<script>
$(document).ready(function() {
$('#emailForm').formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
email: {
validators: {
emailAddress: {
message: 'The value is not a valid email address'
}
}
}
}
});
});
</script>