javascript validate form check - echo out errors in form? - javascript

i have currently got a javascript code which validates my form and shows an error if a field is not completed. i also want to know how i could echo out the errors in the form so for instance if 'fname' is not filled in then this says 'You did not fill in fname' or if 'fname' and fcompany' are not filled in this says
You did not fill in fname
you did not fill in fcompany
Heres my html:
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
Company Name: <input type="text" name="fname">
Company Registration Number: <input type="text" name="fcompany">
heres my javascript:
<script>
function validateForm()
{
var x=document.forms["myForm"]["cname"].value;
if (x==null || x=="")
{
document.body.scrollTop = document.documentElement.scrollTop = 0;
document.getElementById("alertBox").style.display='block';
return false;
}
}
</script>

Have your validate function build an array of errors, then have another function take the errors array and build the HTML:
http://jsfiddle.net/J9LJj/
function displayErrors(errors){
var container = document.getElementById("alertBox");
var html = "<ul>";
for(var i=0; i<errors.length; i++){
html += "<li>" + errors[i] + "</li>";
}
html += "</ul>";
container.innerHTML = html;
container.style.display = "block";
}
function validateForm(){
var fname = document.forms["myForm"]["fname"].value;
var fcompany= document.forms["myForm"]["fcompany"].value;
var errors = [];
if(fname == ""){
errors.push("you did not fill in fname");
}
if(fcompany == ""){
errors.push("you did not fill in fcompany");
}
if(errors.length > 0){
displayErrors(errors);
return false;
} else {
return true;
}
}

Related

Form Validation Error(Beginner)

I am beginning with JavaScript. I just wrote a code for form validation but the checkfields() function is not working. I tried to find the error but couldn't spot it after several attempts. It will be very helpful if someone out there can point out the error.
<html>
<title> Sign-Up </title>
<head>
<style>
body {
background-color: lightblue;
}
input {
height: 30px;
widht: 100px;
}
</style>
<script>
function valform() {
var x = document.forms["f2"]["fn"].value;
var y = document.forms["f2"]["ln"].value;
var z = document.forms["f2"]["eid"].value;
var a = document.forms["f2"]["pass"].value;
var b = document.forms["f2"]["cpass"].value;
if (x == "" || y == "" || z == "" || a == "" || b == "") {
alert("Please fill the form completely");
}
}
function checkfields() {
var p1 = document.forms["f2"]["pass"].value;
var p2 = document.forms["f2"]["cpass"].value;
if (p1 != p2) {
document.getElementByID("message").innerHTML = "Password Doesn't match";
return false;
}
}
</script>
</head>
<body>
<center>
<h1> Sign-Up </h1>
<form name="f2" onsubmit="return checkfields()">
First-Name: <input type="text" name="fn"> Last-Name :<input type="text" name="ln"><br><br><br> Email-Id:
<input type="text" name="eid"><br><br><br> Password:
<input type="password" name="pass"><br><br><br> Confirm-Password
<input type="password" name="cpass">
<span id='message'></span>
<br><br><br>
<input type="Submit" onclick="valform()" value="Submit">
</form>
</center>
</body>
</html>
Two things, you need to prevent the default submit event...
<form name="f2" id="myForm" onsubmit="event.preventDefault(); checkfields()">
Note.. I also gave your form an ID which will be needed for the next step...
I also removed the onclick from the submit button...
<input type="Submit"value="Submit">
I modified your method to return a boolean depending on the validation result
function valform() {
var x = document.forms["f2"]["fn"].value;
var y = document.forms["f2"]["ln"].value;
var z = document.forms["f2"]["eid"].value;
var a = document.forms["f2"]["pass"].value;
var b = document.forms["f2"]["cpass"].value;
if (x == "" || y == "" || z == "" || a == "" || b == "") {
alert("Please fill the form completely");
return false;
}
return true;
}
and I call it within checkfields method where upon being success I submit the form using the ID we assigned above...
function checkfields() {
var p1 = document.forms["f2"]["pass"].value;
var p2 = document.forms["f2"]["cpass"].value;
if (p1 != p2) {
document.getElementById("message").innerHTML = "Password Doesn't match";
return false;
}
if(valform()){
document.getElementById("myForm").submit();
}
}
Here's a little JSFiddle demonstrating the above.
Note: you had one error getElementByID should be lower case d (getElementById)
There is a js error, getElementByID should be getElementById
Also I have modified how the validations goes below
You don't need the click handler on the submit, the return is enough on the onsubmit.
Onsubmit calls valform, and all validation is done within. Since you have a checkfields function already, you can simply call it in the validation function.
You also need to return false if the form is incomplete or else it's going to submit anyway. You could make the code a bit cleaner as well by caching document.forms["f2"] into a variable
You also had a typo in the css widht: 100px;
// saving form into a variable to make it a bit cleaner below
var form_f2 = document.forms["f2"];
function checkfields() {
var p1 = form_f2["pass"].value;
var p2 = form_f2["cpass"].value;
if (p1 != p2) {
document.getElementById("message").innerHTML = "Password Doesn't match";
return false;
}
}
function valform() {
var x = form_f2["fn"].value;
var y = form_f2["ln"].value;
var z = form_f2["eid"].value;
var a = form_f2["pass"].value;
var b = form_f2["cpass"].value;
// call to check passwords
checkfields();
if (x == "" || y == "" || z == "" || a == "" || b == "") {
alert("Please fill the form completely");
// need to return false due to incomplete form
return false;
}
}
body {
background-color: lightblue;
}
input {
height: 30px;
width: 100px;
}
<center>
<h1> Sign-Up </h1>
<form name="f2" onsubmit="return valform()">
First-Name: <input type="text" name="fn"> Last-Name :<input type="text" name="ln"><br><br><br> Email-Id:
<input type="text" name="eid"><br><br><br> Password:
<input type="password" name="pass"><br><br><br> Confirm-Password
<input type="password" name="cpass">
<span id='message'></span>
<br><br><br>
<input type="Submit" value="Submit">
</form>
</center>
You could actually combine the checkfields function content into valform. I don't see any need for the extra function in the given code
In your valform() function you need to pass in the event object to prevent submission of the form is validation does not pass with event.preventDefault(). Also, document.getElementByID should be document.getElementById.
<html>
<title> Sign-Up </title>
<head>
<style>
body {
background-color: lightblue;
}
input {
height: 30px;
widht: 100px;
}
</style>
<script>
function valform(e) {
var x = document.forms["f2"]["fn"].value;
var y = document.forms["f2"]["ln"].value;
var z = document.forms["f2"]["eid"].value;
var a = document.forms["f2"]["pass"].value;
var b = document.forms["f2"]["cpass"].value;
if (x == "" || y == "" || z == "" || a == "" || b == "") {
alert("Please fill the form completely");
e.preventDefault();
}
}
function checkfields() {
var p1 = document.forms["f2"]["pass"].value;
var p2 = document.forms["f2"]["cpass"].value;
if (p1 != p2) {
document.getElementById("message").innerHTML = "Password Doesn't match";
return false;
}
return true;
}
</script>
</head>
<body>
<center>
<h1> Sign-Up </h1>
<form name="f2" onsubmit="return checkfields()">
First-Name: <input type="text" name="fn"> Last-Name :<input type="text" name="ln"><br><br><br> Email-Id:
<input type="text" name="eid"><br><br><br> Password:
<input type="password" name="pass"><br><br><br> Confirm-Password
<input type="password" name="cpass">
<span id='message'></span>
<br><br><br>
<input type="Submit" onclick="valform(event)" value="Submit">
</form>
</center>
</body>
</html>

how to validate URL in dynamically added textbox

how to check URL is correct or not when i will enter into dynamically added textbox .
here t3 is given as id of input tag but that is works only for first dynamically added textbox not for others.
how to validate another URL present into next dynamically added textbox ?
<script type="text/javascript">
function GetDynamicTextBox(value){
return '<Label> Enter the URL : </label>' +
'<input name = "habits" type="text" id = "t3" value = "' + value + '" />' +
' <input type="button" value="Remove" onclick = "RemoveTextBox(this)" /><br><br>'
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var values = eval('<%=Values%>');
if (values != null) {
var html = "";
for (var i = 0; i < values.length; i++) {
html += "<div>" + GetDynamicTextBox(values[i]) + "</div>";
}
document.getElementById("TextBoxContainer").innerHTML = html;
}
}
window.onload = RecreateDynamicTextboxes;
</script>
<html>
<head>
<title>T-SUMM</title>
<script type="text/javascript">
function check()
{
if (document.getElementById('t1').value==""
|| document.getElementById('t1').value==undefined)
{
alert ("Please Enter a Query");
return false;
}
var regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
if(!regex .test(document.getElementById('t2').value)||!regex .test(document.getElementById('t3').value))
{
alert("Please enter valid URL.");
return false;
}
return true;
}
</script>
</head>
<body>
<center>
<form method="Post" action="./result.jsp">
<table>
<br><br><Label> Enter a Query : </label>
<input name='habits' id='t1'> <br><br>
<Label> Enter the URL : </label>
<input name='habits' id='t2'>
<input id="btnAdd" type="button" value="add another URL" onclick="AddTextBox()" /><br><br>
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<input type="submit" name="submit" onclick="return check();">
</table>
</form>
</body>
</html>
HTML - index.html
<html>
<head>
<title>T-SUMM</title>
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript">
function check()
{
if (document.getElementById('t1').value==""
|| document.getElementById('t1').value==undefined)
{
alert ("Please Enter a Query");
return false;
}
var regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
var boxes = document.getElementsByTagName('input');
for(i = 0; i < boxes.length; i++) {
if(boxes[i].type == "text" && boxes[i].className==="urls" && !regex.test(boxes[i].value)) {
alert("Please enter valid URL. Error in Text Box "+boxes[i].value);
return false;
}
}
return true;
}
</script>
</head>
<body>
<center>
<form method="Post" action="./result.jsp">
<table>
<br><br><Label> Enter a Query : </label>
<input name='habits' id='t1'> <br><br>
<Label> Enter the URL : </label>
<input name='habits' class="urls" id='t2'>
<input id="btnAdd" type="button" value="add another URL" onclick="AddTextBox()" /><br><br>
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<input type="submit" name="submit" onclick="return check();">
</table>
</form>
</body>
</html>
JS - script.js
function GetDynamicTextBox(value){
return '<Label> Enter the URL : </label>' +
'<input name = "habits" type="text" class="urls" value = "' + value + '" />' +
' <input type="button" value="Remove" onclick = "RemoveTextBox(this)" /><br><br>'
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var values = eval('<%=Values%>');
if (values != null) {
var html = "";
for (var i = 0; i < values.length; i++) {
html += "<div>" + GetDynamicTextBox(values[i]) + "</div>";
}
document.getElementById("TextBoxContainer").innerHTML = html;
}
}
window.onload = RecreateDynamicTextboxes;
I think you can first try to add an "onchange" handler to the "TextBoxContainer" div and user event.target or event.srcElement to identify whether it is a textbox that triggered the "onchange" event. If the trigger dom is exactly the ones you want, then you can try to validate its value and if it is not, you don't need to do anything. If this is done, then the rest things will be simply add/remove textboxes to the container element. Below are some sample codes that may help:
<script type="text/javascript">
var _container = document.getElementById('TextBoxContainer');
function add(){
var _txt = document.createElement("INPUT");
_txt.type = "text";
_container.appendChild(_txt);
}
_container.onchange = function(event){
var _dom = event.target || event.srcElement;
if(_dom && _dom.tagName === "INPUT" && _dom.type === "text"){
//alert(_dom.value);
//You can validate the dom value here
}
};
document.getElementById('add').onclick=function(){
add();
};
</script>

storing user input in arrays for a log in site?

i am trying to make a mock up site that will allow you to create a username and password then for it to send that array of usernames and passwords over to a log in page where you will put in a username or password and it will go threw a process of checking weather it is wright or wrong and then what to do from there. what i have realized is that when i hit the button to send the information over it will not register on the other page. may you please help me find out what i screwed up on.
here is the code for where i create the username and password:
<!DOCTYPE html>
<html>
<head>
<title>
create account
</title>
<script>
function createLogIn() {
var usernameArray = document.getElementById("usernameMake").value;
var paswordArray = document.getElementById("pwordMake").value;
unArray.push("usernameArray");
pwArray.push("paswordArray");
localStorage.setItem("unArray", JSON.stringify([]));
localStorage.setItem("pwArray", JSON.stringify([]));
}
</script>
</head>
<body>
<form name = "makeLogIn">
<p class="log_on">
ENTER YOUR NEW USERNAME <input type="text" id="usernameMake"><br><br><br><br><br>
ENTER YOUR NEW PASSWORD <input type="text" id="pwordMake">
<input type="button" value="create it" id="Submit" onclick="createLogIn">
</p>
</form>
</body>
</html>
here is the code for logging in with that username and password:
<!DOCTYPE html>
<html>
<head>
<title>
log on page
</title>
<script type = "text/javascript">
var count = 2;
function validate() {
var un = document.getElementById("username").value;
var pw = document.getElementById("pword").value;
var valid = false;
var unArray = JSON.parse(localStorage.getItem("unArray"));
var pwArray = JSON.parse(localStorage.getItem("pwArray"));
for (var i = 0; i < unArray.length; i++) {
if ((un == unArray[i]) && (pw == pwArray[i])) {
valid = true;
break;
}
}
if (valid) {
alert ("Login was successful");
window.location = "http://www.google.com";
return false;
}
var t = " tries";
if (count == 1) {t = " try"}
if (count >= 1) {
alert ("Invalid username and/or password. " +
"You have " + count + t + " left.");
document.myform.username.value = "";
document.myform.pword.value = "";
setTimeout("document.myform.username.focus()", 25);
setTimeout("document.myform.username.select()", 25);
count --;
}
else {
alert ("Still incorrect! You have no more tries left!");
document.myform.username.value = "No more tries allowed!";
document.myform.pword.value = "";
document.myform.username.disabled = true;
document.myform.pword.disabled = true;
return false;
}
}
</script>
<style>
p.log_on{
position: fixed;
top: 30px;
left: 20px;
}
</style>
</head>
<body>
<form name = "myform">
<p class="log_on">
ENTER USER NAME <input type="text" id="username"><br><br><br><br><br>
ENTER PASSWORD <input type="password" id="pword">
<input type="button" value="Check In" id="Submit" onclick="validate()">
</p>
</form>
</body>
</html>
In function for create login you:
You use undefined arrays unArray and pwArray
You push to this arrays string but not value of variables
You save to local storage empty array.

Array value not accesible in another function in javascript

I am developing a simple address book. I am using four different arrays to store name,phone no ,address and email of user.When I am calling add() method its adding values to these arrays,but when I am calling display the details its showing address book empty and all these arrays empty. Thanks in advance please help..
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Address Book</title>
<link rel="stylesheet" type="text/css" href="addressBook.css" />
<script src="jquery-2.1.1.min.js"></script>
<script>
$(document).ready(function () {
$('#add').click(function () {
add();
});
$('#delete').click(function () {
remove_con();
});
$('#view').click(function () {
display();
});
});
</script>
<script type="text/javascript">
var BOOK = new Array();
var BOOKNO = new Array();
var ADDR = new Array();
var EMAIL = new Array();
function add() {
//Take values from text fields
var conname = document.getElementById('userNam').value;
var lenname = BOOK.length;
var x = BOOK.indexOf(conname);
var conno = document.getElementById('userNo').value;
var lenno = BOOKNO.length;
var y = BOOKNO.indexOf(conno);
var conaddr = document.getElementById('userAdd').value;
var lenaddr = ADDR.length;
var z = ADDR.indexOf(conaddr);
var conemail = document.getElementById('userEmail').value;
var lenemail = EMAIL.length;
var w = EMAIL.indexOf(conemail);
//Validations
if (conname.length == 0) {
alert("Name field cannot be blank");
return;
}
else if (conno.length == 0) {
alert("Phone number field cannot be Left blank");
return;
}
else if (conno.length != 10) {
alert("Enter a Valid Phone Number");
return;
}
else if (conaddr.length == 0) {
alert("Address field cannot be blank");
return;
}
else if (conemail.length == 0) {
alert("Email field cannot be blank");
return;
}
//RegEX
alphaExp = /^[a-zA-Z]+$/;
numExp = /^[0-9]+$/;
betaExp = /^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
if (!conname.match(alphaExp)) {
alert("Please enter alphabets only");
return;
}
else if (!conno.match(numExp)) {
alert("Please enter numerals only");
return;
}
else if (!conemail.match(betaExp)) {
alert("Please enter a valid email");
return;
}
else if (y >= 0) {
alert("Phone number already Present");
return;
}
else {
BOOK[lenname] = conname;
BOOKNO[lenno] = conno;
ADDR[lenaddr] = conaddr;
EMAIL[lenemail] = conemail;
var l = BOOK.length;
alert("Contact " + conname + " Added Sucesfully!!!!" +l);
return BOOK,BOOKNO,ADDR,EMAIL;
}
}
function display() {
//document.getElementById('hiddenDiv').style.display = "block";
BOOK = BOOK.sort();
var l = BOOK.length;
alert(l);
var view = "";
if (l == 0) {
document.getElementById('hiddenDiv').innerHTML = "ADDRESS BOOK EMPTY!!!";
}
if (l >= 1) {
view = view + "<table border=1px><tr><td><B>NAME</B></td><td><B>PHONE NUMBER</B></td><td><B>ADDRESS</B></td><td><B>EMAIL</B></td>";
for (var i = 0; i < BOOK.length; i++) {
view = view + "<tr><td>" + BOOK[i] + "</td><td>" + BOOKNO[i] + "</td><td>" + ADDR[i] + "</td><td>" + EMAIL[i] + "</td></tr>";
}
document.getElementById('hiddenDiv').innerHTML = view + "</table>";
}
}
function remove_con() {
var remname = prompt("Enter the name to be removed");
var remlen = BOOK.LENGTH;
/*var remnam=document.getElementById('name').value;
var remno=document.getElementById('phno').value;*/
var z = BOOK.indexOf(remname);
var z1 = z;
var z2 = z;
var z3 = z;
if (remlen == 0) {
alert("ADDRESS BOOK IS EMPTY");
return;
}
if (z >= 0) {
BOOK.splice(z, 1);
BOOKNO.splice(z1, 1);
ADDR.splice(z2, 1);
EMAIL.splice(z3, 1);
alert("Contact deleted");
}
if (z == -1) {
alert("Contact not present");
}
}
function searchcon() {
var lenn1 = BOOK.length;
if (lenn1 == 0) {
alert("ADDRESS BOOK EMPTY");
return;
}
var coname = prompt("Enter name");
var ind = BOOK.indexOf(coname);
if (ind >= 0) {
alert("contact found");
return;
}
else {
alert("Contact not present in address book");
}
}
</script>
</head>
<body>
<div id="mainDiv">
<header id="startHeader">
<p id="headerPara">Welcome to Address Book</p>
</header>
<div id="midDiv">
<form id="submissionForm">
<div class="entryDiv">
<p class="inputType">Name:</p>
<input id="userNam" type="text" class="buttonsClass" placeholder="Enter Your Name" required="" />
</div>
<div class="entryDiv">
<p class="inputType">Number:</p>
<input id="userNo" type="text" class="buttonsClass" placeholder="Enter Your Number" required="" />
</div>
<div class="entryDiv">
<p class="inputType">Address:</p>
<input id="userAdd" type="text" class="buttonsClass" placeholder="Enter Your Address" required="" />
</div>
<div class="entryDiv">
<p class="inputType">Email:</p>
<input id="userEmail" type="email" class="buttonsClass" placeholder="Enter Your Email" required="" />
</div>
<div id="Buttons">
<input id="reset" type="reset" value="Reset" />
<input id="delete" type="button" value="Delete Contact" />
<input id="view" type="button" value="View Book" />
<input id="add" type="submit" value="AddToContacts" />
</div>
</form>
<div id="hiddenDiv">
</div>
</div>
</div>
</body>
</html>
Change add button's type "submit" to "button" then remove return statement from add function as it is not needed.
This code has many issues.
You don't need four array to store address detail. you can make one array that can have objects containing the address information.eg.
var Address=function(name,address,email,mobile){
this.name=name;
this.address=address||"not available";
this.email=email||"not available";
this.mobile=mobile;
}
var AddressBook=new Array();
//Adding data in address book
AddressBook.push(new Address("jhon","baker street","a#in.com","049372497"))
You can use jquery to get value of element instead of pure javascript. eg.
var conname = document.getElementById('userNam').value;
//instead of this use jquery
var conname=$("#userNam").val(); // recommended approach
There is no need to calculate array length everywhere.To check duplicate mobile number you can write a function.
there are many other improvement you can have in code. for more examples go through Jquery site and Github public repositories.
Fiddle Demo
Change the <input id="add" type="submit" value="AddToContacts" /> to type="button". type="submit" will refresh the page to form's action and will reset all variables including BOOK.

I have an issue to create dynamic fields with string count using Javascript OR Jquery

I have an issue to create dynamic fields with string count using JavaScript or jQuery.
Briefing
I want to create dynamic fields with the help of sting count, for example when I write some text on player textfield like this p1,p2,p3 they create three file fields on dynamicDiv or when I remove some text on player textfield like this p1,p2 in same time they create only two file fields that's all.
The whole scenario depend on keyup event
Code:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function commasperatedCount(){
var cs_count = $('#player').val();
var fields = cs_count.split(/,/);
var fieldsCount = fields.length;
for(var i=1;i<=fieldsCount;i++){
var element = document.createElement("input");
element.setAttribute("type", 'file');
element.setAttribute("value", '');
element.setAttribute("name", 'file_'+i);
var foo = document.getElementById("dynamicDiv");
foo.appendChild(element);
}
}
</script>
<form>
<label>CountPlayerData</label>
<input type="text" name="player" id="player" onkeyup="return commasperatedCount();" autocomplete="off" />
<div id="dynamicDiv"></div>
<input type="submit" />
</form>
var seed = false,
c = 0,
deleted = false;
$('#player').on('keyup', function(e) {
var val = this.value;
if ($.trim(this.value)) {
if (e.which == 188) {
seed = false;
}
if (e.which == 8 || e.which == 46) {
var commaCount = val.split(/,/g).length - 1;
if (commaCount < c - 1) {
deleted = true;
}
}
commasperatedCount();
} else {
c = 0;
deleted = false;
seed = false;
$('#dynamicDiv').empty();
}
});
function commasperatedCount() {
if (deleted) {
$('#dynamicDiv input:last').remove();
deleted = false;
c--;
return false;
}
if (!seed) {
c++;
var fields = '<input value="" type="file" name="file_' + c + '">';
$('#dynamicDiv').append(fields);
seed = true;
}
}​
DEMO
<script>
function create(playerList) {
try {
var player = playerList.split(/,/);
} catch(err) {
//
return false;
}
var str = "";
for(var i=0; i<player.length; i++) {
str += '<input type="file" id="player-' + i + '" name="players[]" />';
//you wont need id unless you are thinking of javascript validations here
}
if(playerList=="") {str="";} // just in case text field is empty ...
document.getElementById("dynamicDiv").innerHTML = str;
}
</script>
<input id="playerList" onKeyUp="create(this.value);" /><!-- change event can also be used here -->
<form>
<div id="dynamicDiv"></div>
</form>

Categories

Resources