Java Script Form Validation - javascript

I am building adding JavaScript validation to my sign in form, i can successfully validate the username against certain criteria, however i am struggling to validate the password input. Any help would be greatly appreciated. Many Thanks.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>An AJAX Username Verification Tool</TITLE>
<META NAME="Keywords" CONTENT="form, username, checker">
<META NAME="Description" CONTENT="An AJAX Username Verification Script">
<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css" />
<SCRIPT type="text/javascript">
pic1 = new Image(16, 16);
pic1.src = "loader.gif";
$(document).ready(function(){
$("#username").change(function() {
var usr = $("#username").val();
if(usr.length <= 4)
{
$("#status").html('<font color="red">The username should have more than <strong>4</strong> characters.</font>');
$("#username").removeClass('object_ok'); // if necessary
$("#username").addClass("object_error");
}
else if(usr.length >= 14)
{
$("#status").html('<font color="red">The username not be longer than <strong>14</strong> characters.</font>');
$("#username").removeClass('object_ok'); // if necessary
$("#username").addClass("object_error");
}
else if(usr.indexOf('#') === -1 )
{
$("#status").html('<font color="red">Please insert correct <strong>Email</strong> format.</font>');
$("#username").removeClass('object_ok'); // if necessary
$("#username").addClass("object_error");
}
else
{
$("#status").html('<img src="loader.gif" align="absmiddle"> Checking availability...');
$.ajax({
type: "POST",
url: "check.php",
data: "username="+ usr,
success: function(msg){
$("#status").ajaxComplete(function(event, request, settings){
if(msg == 'OK')
{
$("#username").removeClass('object_error'); // if necessary
$("#username").addClass("object_ok");
$(this).html(' <img src="tick.gif" align="absmiddle">');
}
else
{
$("#username").removeClass('object_ok'); // if necessary
$("#username").addClass("object_error");
$(this).html(msg);
}
});
}
});
}
});
// HERE IS WHERE I AM HAVING THE PROBLEMS
$("#password").change(function() {
var pass = $("#password").val();
if(pass.length <= 4){
$("#status2").html('<font color="red">The username should have more than <strong>4</strong> characters.</font>');
$("#password").removeClass('object_ok'); // if necessary
$("#password").addClass("object_error");
}
});
// END OF PROBLEM
});
</SCRIPT>
</HEAD>
<BODY>
<center>
<div align="center">
<h2 align="center">AJAX Username Verification</h2>
<form>
<table width="700" border="0">
<tr>
<td width="200"><div align="right">Username: </div></td>
<td width="100"><input id="username" size="20" type="text" name="username"></td>
<td width="400" align="left"><div id="status"></div></td>
</tr>
<tr>
<td width="200"><div align="right">Password: </div></td>
<td width="100"><input size="20" type="text" name="password"></td>
<td width="400" align="left"><div id="status2"></div></td>
</tr>
<tr>
<td width="200"><div align="right">Confirm Password: </div></td>
<td width="100"><input size="20" type="text" name="confirm_password"></td>
<td width="400" align="left"><div id="status3"></div></td>
</tr>
</table>
</form>
</div>
</center>
</BODY>
</HTML>

You haven't placed the id on password field.
<td width="100"><input size="20" type="text" name="password"></td> this should be like
<td width="100"><input size="20" type="text" id="password"></td>
So you can replace your <tr> with this
<tr>
<td width="200"><div align="right">Password: </div></td>
<td width="100"><input size="20" type="text" name="password" id="password"></td>
<td width="400" align="left"><div id="status2"></div></td>
</tr>

At first, you must assign id "password" to your input, then JQUERY will can to find this input. And, I think, it much better to change attribute "type" to "password" for password inputs:
<input size="20" type="password" name="password" id="password"/>

Related

How to fetch database values in html text boxes on button press without refreshing page in php?

I want to fetch database values into text boxes without refreshing page. with page refresh it goes fine but I don't want to refresh it.
My code is shown below.
PHP
<?php
include 'Connection.php';
$sql=mysqli_query($connect,"select * from `registration`");
while ($row=mysqli_fetch_array($sql))
{
echo "<tr>
<td>".$row['Emp_Code']."</td>
<td>".$row['Full_Name']."</td>
<td>".$row['Permanent_Address']."</td>
<td>".$row['Mobile_No']."</td>
<tr>";
if (isset($_POST['Fetchdetails']))
{
$userid = $_POST['userid'];
$fetchquery = mysqli_query($connect,"select * from `registration` where `Emp_Code` = '$userid'");
if (mysqli_num_rows($sql)>0)
{
while ($row=mysqli_fetch_array($fetchquery))
{
$employeecode=$row['Emp_Code'];
$fullname=$row['Full_Name'];
$permanentaddress=$row['Permanent_Address'];
$mobileno=$row['Mobile_No'];
}
}
}
}
?>
My HTML Code is
<html>
<body>
<div align="center" id="div">
<table width="400" border="1">
<tr align="right" style="background-color:#FFF;">
<td width="100">Permanent Address : </td>
<td width="100">
<input type="text" name="permanentaddress" id="permanentaddress" placeholder="Permanent Address" size="15" value="<?php echo $permanentaddress;?>"/> </td>
</tr>
<tr align="right" style="background-color:#FFF;">
<td width="100">Employee Code : </td>
<td width="100"> <input type="text" name="employeecode" id="employeecode" placeholder="Employee Code" size="15" value="<?php echo $employeecode;?>"/> </td>
</tr>
<tr align="right" style="background-color:#FFF;">
<td width="100">Full Name : </td>
<td width="100"> <input type="text" name="fullname" id="fullname" placeholder="Full Name" size="15" value="<?php echo $fullname;?>"/> </td>
</tr>
<tr align="right" style="background-color:#FFF;">
<td width="100">Mobile No. : </td>
<td width="100"> <input type="text" name="mobileno" id="mobileno" placeholder="Mobile No." size="15" value="<?php echo $mobileno;?>"/> </td>
</tr>
</table>
</div>
<br>
<div align="center">
<input type="submit" name="Fetchdetails" value="Fetch Details" id="Fetchdetails" />
</div>
</body>
</html>
How can I fetch values from database into text boxes without refreshing web page?
You can use AJAX to achieve the dynamic loading of the data.An Example would be:
$.ajax({
url: "yourscript.php",
cache: false,
success: function(html){
$("#results").append(html);
}
});
where yourscript.php is your backend script, where the database calls would be executed and returned back to your success on successful request.
Please note that the data should be exchanged in a serialized format(for AJAX requests the most common approach is JSON).
You can achieve this by json.
Try the following code.
PHP Code
<?php
include 'Connection.php';
$userid = $_GET['userid'];
$fetchquery = mysqli_query($connect,"select * from `registration` where `Emp_Code` = '$userid'");
if (mysqli_num_rows($sql)>0)
{
while ($row=mysqli_fetch_array($fetchquery))
{
$return['employeecode']=$row['Emp_Code'];
$return['fullname']=$row['Full_Name'];
$return['permanentaddress']=$row['Permanent_Address'];
$return['mobileno']=$row['Mobile_No'];
}
}
echo json_encode($return);
Javascript Code
$("#Fetchdetails").click(function(e) {
e.preventDefault();
var userId = $(this).attr('data-user-id');
$.ajax({
type: "GET",
url : 'http://localhost/test/get_data.php?userid='+userId,
dataType : 'json',
success : function(response) {
$('#permanentaddress').val(response.permanentaddress);
$('#employeecode').val(response.employeecode);
$('#fullname').val(response.fullname);
$('#mobileno').val(response.mobileno);
},
error : function() {
alert('There was an error');
}
});
});
Note : you have to replace following line with your php file url.
url : 'http://localhost/test/get_data.php

Javascript to show content if checkbox is checked

In this Fiddle I have made script that should show the form if the checkbox is checked but I can't make it work. It says that the function is unknown variable.
Html
<input type="checkbox" id="_My.notFinal" onclick='toggleCheckbox();'>
<label>
<b>Buying for someone else.</b>
</label>
<span id="LicenseCustomer" style="display:none">/*some form*/</span>
And javascript
function toggleCheckbox() {
var lfckv = document.getElementById("_My.notFinal").checked;
if (lfckv) {
document.getElementById("LicenseCustomer").style.display = "block";
} else {
document.getElementById("LicenseCustomer").style.display = "none";
}
}
https://jsfiddle.net/00gckvxw/1/
Here it is the corrected version https://jsfiddle.net/00gckvxw/24/.
document.getElementById("_My.notFinal").onclick = toggleCheckbox;
It has to do with when the events are attached. check this out: testing a function in jsfiddle.
I also changed the span to div and class attribute to id. I wouldn't recommend using <tr> inside a <div> or <span>, better use id on <tr> directly or use <tbody> if you have multiple lines.
I think you missed out to include the Javascript file in your in html, because it is not able to find the function toggleCheckbox on click of checkbox. Also
Also span element has class = 'LicenseCustomer', change this to id='LicenseCustomer'
try including inline script
<script>
function toggleCheckbox() {
var lfckv = document.getElementById("_My.notFinal").checked;
console.log(lfckv);
if (lfckv) {
document.getElementById("LicenseCustomer").style.display = "block";
} else {
document.getElementById("LicenseCustomer").style.display = "none";
}
}
</script>
<input type="checkbox" id="_My.notFinal" onclick='toggleCheckbox();'>
<label><b>Buying for someone else.</b>
<label>
<span id="LicenseCustomer" style="display:none">
<tr valign=middle>
<td class="bodycopy" align=right width=160><b>License Contact:</b> </td>
<td class="smallcopy" nowrap><input name="_My.LicenseContact" type="text" class="inputBox" size="32" _label="<br>License Contact"></td>
</tr>
<tr valign=middle>
<td class="bodycopy" align=right><b> License E-mail Address:</b> </td>
<td class="smallcopy" nowrap><input name="_My.LicenseEmail" type="text" class="inputBox" size="32" _label="<br> License E-mail Address"></td>
</tr>
<tr valign=middle>
<td class="bodycopy" align=right><b> License Phone:</b> </td>
<td class="smallcopy" nowrap><input name="_My.LicensePhone" type="text" class="inputBox" size="32" _label="<br> License Phone"></td>
</tr>
</span>
corrected version:
http://pastebin.com/RrMD78AG
Few mistakes i want to tell you:-
first you are using class="LicenseCustomer" and you are using document.getElementById selector (it cannot get element with class name).
second you are using onclick="toggleCheckbox();", when you calling function you does not have to use 'semicolon' at the end of a function name (its an incorrect syntax) - onclick="toggleCheckbox()" (no semicolon).
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input type="checkbox" id="_My.notFinal" class='checkbox'>
<label><b>Buying for someone else.</b>
</label>
<span class="LicenseCustomer" style="display:none">
<tr valign=middle>
<td class="bodycopy" align=right width=160><b>License Contact:</b> </td>
<td class="smallcopy" nowrap><input name="_My.LicenseContact" type="text" class="inputBox" size="32" _label="<br>License Contact"></td>
</tr>
<tr valign=middle>
<td class="bodycopy" align=right><b> License E-mail Address:</b> </td>
<td class="smallcopy" nowrap><input name="_My.LicenseEmail" type="text" class="inputBox" size="32" _label="<br> License E-mail Address"></td>
</tr>
<tr valign=middle>
<td class="bodycopy" align=right><b> License Phone:</b> </td>
<td class="smallcopy" nowrap><input name="_My.LicensePhone" type="text" class="inputBox" size="32" _label="<br> License Phone"></td>
</tr>
</span>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
</body>
</html>
Below is the Javascript
$(document).ready(function()
{
$(".checkbox").change(function() {
if(this.checked)
{
$(".LicenseCustomer").css('display','block');
}
else
{
$(".LicenseCustomer").css('display','none');
}
})
});
Demo : https://jsbin.com/bowicivupa/edit?html,js,console,output
Try to something like this.
function toggleCheckbox(){
var lfckv = document.getElementById('myCheck').checked;
if(lfckv){
document.getElementsByTagName("span")[0].setAttribute("style", "display:none");
} else {
document.getElementsByTagName("span")[0].setAttribute("style", "display:block");
}
}

window.location.href still not working after cancelling form submission

I have an login form
<div id='login_form'>
<table>
<tr>
<td>Username:</td>
<td><input size=25 type='text' id='username'></td>
</tr>
<tr>
<td>Password:</td>
<td><input size=25 type='password' id='password'></td>
</tr>
<tr>
<td colspan='2' align='right'>
<input type='button' id='login' value='Login' onkeydown='normalobjKeyFunc(this)' onfocus='itemFocus(this)' onblur='itemBlur(this)'/>
</td>
</tr>
</table>
</div>
then I have javaScript
var input_username = document.getElementById("username").value;
var input_password = document.getElementById("password").value;
if(input_username === "123" && input_password === "456"){
alert("Correct username & password");
window.location.href="../../result.html";
return false;
}
But when I received the alert "Correct username & password", the page was not redirected to result.html. And I checked, "../../result.html" exists.
I found some people said the submission should be cancelled, so I deleted form and changed the " type = "submit" " to " type = "button" "for Login button, but it was not working.
And there is also another method, add "return false" after " window.location.href="../../result.html" ", but it was not working as well.
Any one has any idea????
Thanks in advance!
Username/password checking should be done on the backend (Java, PHP, Node, .NET)
Your form should be in a form tag though. The checking should be done in the onsubmit callback:
<script>
function authenticate(){
var input_username = document.getElementById("username").value;
var input_password = document.getElementById("password").value;
if(input_username==="123"&&input_password==="456"){
alert("Correct username & password");
window.location.href = "../../result.html";
}
else {
// Error
}
return false;
}
</script>
<form onsubmit="authenticate()">
<table>
<tr>
<td>Username:</td>
<td><input size="25" type="text" id="username"></td>
</tr>
<tr>
<td>Password:</td>
<td><input size="25" type="password" id="password"></td>
</tr>
<tr>
<td colspan="2" style="text-align: right">
<button onkeydown="normalobjKeyFunc(this)" onfocus="itemFocus(this)" onblur="itemBlur(this)">Login</button>
</td>
</tr>
</table>
</form>
Put an onclick in your button to call your javascript function..
<input type='button' id='login' onclick="authenticate()" value='Login' onkeydown='normalobjKeyFunc(this)' onfocus='itemFocus(this)' onblur='itemBlur(this)'/>

Jsfiddle code not working in localhost wamp

i have implemented validation for fundtransfer in jsfiddle.
it works fine in jsfiddle but not working in localhost.
i am using wamp.
here is my jsfiddle link - http://jsfiddle.net/BzdfN/31/
but when i am implementing this in localhost.its not working.
my html code is
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="validate.js"></script>
<title> Infy Bank Fund Transfer Entry Page </title>
</head>
<body>
<table class="layout" border="0" width="90%" align="center">
<form name="addcust" method ="POST" action ="http://localhost:8080/myapp/jsp/AddCustomerJSP.jsp">
<td colspan="2">
<table border="0" width="70%" align="center">
<tr>
<td align="center" colspan="2">
<div class="heading2">Infy Bank</div>
</td>
</tr>
<tr>
<td align="center" colspan="2"><p class="heading3">Fund transfer</p></td>
</tr>
<tr>
</tr>
<tr>
</tr>
<tr>
<td>Payers account no<span class="mandatory">*</span></td>
<td><input type="text" name="text10" id="text10" size="25" />
<div width="100%" id="equal"></div>
</td>
</tr>
<!--<tr>
<td>Payees account no<span class="mandatory">*</span></td>
<td>
<input type="text" name="name" value=2008 maxlength="25">
</td>
</tr>
<tr>
<td>Amount<span class="mandatory">*</span></td><td><input type="text" Value=500 name="state" maxlength="25"></td>
</tr>
<tr>
<td>Description<span class="mandatory">*</span></td><td><input type="text" name="pin" value=self maxlength="6"></td>
</tr>
<tr>
<td><span class="mandatory">*mandatory field</span></td>
<td><input type="submit" name="AccSubmit" value="Submit" onClick="return validatebal();">
<input type="reset" name="res" value="Reset"></td>
</tr>-->
</form>
</table>
<p align="right">Home</p>
</body>
</html>
and my validate.js is
$("#text10").keyup(function(){
$("#text10").blur();
$("#text10").focus();
});
$("#text10").change(function(){
var name = $('#text10').val();
var numbers = /^[0-9]+$/;
var specialChars = "<>#!#$%^&*()_+[]{}?:;|'\"\\,./~`-=";
if (name == "" || name == " " )
{
$("#equal").show();
$("#equal a").html("please enter account number");
}
else if(name.match(numbers))
{
$("#equal").hide();
$("#equal a").html("correct account number"); // alert('All Boxes have elements.');
}
else if(name.match(specialChars))
{
$("#equal").show();
$("#equal a").html("correct account number"); // alert('All Boxes have elements.');
}
else
{
$("#equal").show();
$("#equal a").html("please check your account number correctly");
}
});
So guys can you what i am doing wrong.
please help
start your jQuery with:
$( document ).ready(function() {
.../ and end with:
});
maybe this will solve your problem
In jsfFiddle your code is executed on the onload event.
But with including validate.js in the head the content of the script is execute right at the place where you placed <script src="validate.js"></script>. So your jQuery selectors don't find any elements, because they are not in the DOM at the time the script is executed.
You have different possibilities.
Wrap the content of your validate.js into jQuery(function() { /*your code of validate.js **/ })
Another possibility is to place <script src="validate.js"></script> at the end of your document instead placing it in the head.
You can use delegated events like $(document).on("keyup","#text10", function() { /* .... */ }); that way it does not matter if #text10 is in the DOM at this time.
wrap your validate.js code in jQuery ready function as follows should solve the issue:
$(document).ready(function() {
// validate.js code
});

JavaScript checking & adding text to a table dynamically on submit button click

Basically my HTML looks like this:
<form method="post" name="htmlform" onsubmit = "checkFields()">
<table style="width: 479px;" border="30" cellspacing="3" cellpadding="10">
<tbody>
<tr>
<td valign="top"><span id="firstNameSpan" >First Name *</span></td>
<td valign="top"><input type="text" name="first_name" id="first_name"
size="30" maxlength="50" /></td>
</tr>
<tr>
<td valign="top"><span id = "lastNameSpan" >Last Name *</span></td>
<td valign="top"><input type="text" name="last_name" size="30" maxlength="50"/>
/td>
</tr>
<tr>
<td style="text-align: center;" colspan="2"><input type="radio" name="sex"
value="male" /> Male <input type="radio" name="sex"
value="female" /> Female</td>
</tr>
<tr>
<td style="text-align: center;" colspan="2"><input type="submit" value="submit"
/></td>
</tr>
</tbody>
</table>
</form>
When the form is submitted, the onsubmit() event checks if first_name textfield is blank, if it is then the label or span to its left is appended to output "first name*" + " you must enter a first name" and similarly for last name and sex.
The problem is that the text in the table does not update with appendchild. When I enclosed the statement in an alert for debugging the message is appended then disappears.
The JavaScript code is below for the onsubmit = "checkFields()".
function checkFields() {
var firstName = document.getElementById("first_name").value;
var lastName = document.getElementById("last_name").value;
if (firstName == "") {
//<span style='color:red'> Please enter a first name </span>
var nameHint = " Please enter a first name";
var node = document.getElementById("firstNameSpan");
//alert(node.appendChild(document.createTextNode(nameHint)) );
//not working
node.appendChild(document.createTextNode(nameHint));
} if (lastName == "") {
//additional code
}
}
Thanks in advance, your help is much appreciated. Also are there any JavaScript debuggers?
Regards
David D
I believe your sample code is not working due to incorrect html. document.getElementById("last_name") will return undefined.
http://jsfiddle.net/5E6my/1/
Thanks all, Im getting the ropes of JFiddle the split screen is very useful although the error messages are not useful for debugging. Here is the completed code (1) HTML (2) JavaScript.
<form method="post" name="htmlform" onsubmit="return checkFields();">
<table style="width: 479px;" border="30" cellspacing="3" cellpadding="10">
<tbody>
<tr>
<td valign="top"><span id="firstNameSpan" >First Name *</span></td>
<td valign="top"><input type="text" name="first_name" id="first_name"
size="30" maxlength="50" /></td>
</tr>
<tr>
<td valign="top"><span id = "lastNameSpan" >Last Name *</span></td>
<td valign="top"><input type="text" name="last_name" id="last_name" size="30"
maxlength="50" /></td>
</tr>
<tr>
<td style="text-align: center;" colspan="2" id = "sexMessage">
Please select Male or Female*</td>
</tr>
<tr>
<td style="text-align: center;" colspan="2"><input type="radio"
name="sex" value="male" /> Male <input type="radio" name="sex"
value="female" /> Female</td>
</tr>
<tr>
<td style="text-align: center;" colspan="2"><input type="submit" value="submit"
/></td>
</tr>
</tbody>
</table>
</form>
The JavaScript code to react to the onsubmit button's unfilled fields in the form are: (any ways to make this code simpler??)
window.checkFields = function()
{
var firstName = document.getElementById("first_name");
var lastName = document.getElementById("last_name");
if(firstName.value == "")
{
//<span style='color:red'> Please enter a first name </span>
var nameHint = " *Please enter a first name ";
var fnNode = document.getElementById("firstNameSpan");
while(fnNode.firstChild)
{
fnNode.removeChild(fnNode.firstChild)
}
fnNode.appendChild(document.createTextNode(nameHint));
fnNode.style.color="red";
} else{
var nameHint = " First Name *";
var fnNode = document.getElementById("firstNameSpan");
while(fnNode.firstChild)
{
fnNode.removeChild(fnNode.firstChild)
}
fnNode.appendChild(document.createTextNode(nameHint));
fnNode.style.color="black";
}
if (lastName.value == "")
{
//additional code
var nameHint = " *Please enter a last name";
var lnNode = document.getElementById("lastNameSpan");
while(lnNode.firstChild)
{
lnNode.removeChild(lnNode.firstChild)
}
lnNode.appendChild(document.createTextNode(nameHint));
lnNode.style.color="red";
} else{
var nameHint = " Last Name *";
var lnNode = document.getElementById("lastNameSpan");
while(lnNode.firstChild)
{
lnNode.removeChild(lnNode.firstChild)
}
lnNode.appendChild(document.createTextNode(nameHint));
lnNode.style.color="black";
}
var radios = document.getElementsByName("sex");
var radioValue = ""
for(var i=0; i<radios.length; i++)
{
if(radios[i].checked)
{
radioValue = radios[i].value;
}
}
if(radioValue === "")
{
var sexNode = document.getElementById("sexMessage");
var nameHint = "*You did not choose a sex";
while(sexNode.firstChild)
{
sexNode.removeChild(sexNode.firstChild);
}
sexNode.appendChild(document.createTextNode(nameHint));
sexNode.style.color="red";
} else {
var sexNode = document.getElementById("sexMessage");
var nameHint = "Please select Male or Female*";
while(sexNode.firstChild)
{
sexNode.removeChild(sexNode.firstChild);
}
sexNode.appendChild(document.createTextNode(nameHint));
sexNode.style.color="black";
}
return false;
}
The trick is to use as Yury suggested was the onsubmit="return checkfields()" and then in the code block to use window.checkFields = function() { etc.
One question that I have... is JQuery a lot simpler to use, im learning JavaScript before JQuery... should I skip to JQUery instead. Also does JQuery support the AJAX framework?
Much appreciated
David

Categories

Resources