datetime comparision in javascript is not working - javascript

I want to validate dateTime input fields in form and it need to give alert message if not entered and if "FromDate"(ex:17-12-2013 19:14:58) > than the "CurrentDate" it need to give alert message in the same way "ToDate" > than the "CurrentDate" it need to give mes and if "FromDate">"ToDate" in that cse also it need to give some alert message i written code for it but it is not working can any one help me?
Code wiill be like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://displaytag.sf.net" prefix="display" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Preva Tracking Systems</title>
<link rel="icon" href="pictures/preva_logo.png" />
<link rel="stylesheet" href="css/screen.css" type="text/css">
<link rel="stylesheet" href="css/site.css" type="text/css">
<link href="css/sty.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/datetimepicker.js"></script>
<script type="text/javascript" src="js/overspeedvalidate.js" >
</script>
</head>
<body>
<form name="myForm" onsubmit="return validateForm()" action="ReportGenerator?action=OverspeedEventDBReport" method="post">
<table width=100% border="1">
<tr bgcolor=#075A99 >
<td width=100% align=left><b><font color=white>OverSpeed Event Report</font></b></td>
</tr>
</table>
<table cellpadding="0" cellspacing="0" width="100%" class="reportSearchBorder">
<tr><td> </td></tr>
<tr>
<td width="100%">
<table width="100%" cellpadding="0" cellspacing="0" border=0>
<tr>
<td align="left" id="VehicleIdDescDiv" valign="middle">Vehicle Number</td>
<td >
<table align=left border=0>
<tr>
<td align=left>
<select name="vehicleId" class="txtbig" ><option value="">Select vehicle number</option>
<c:forEach var="vehiclelist" items="${devicelists}">
<option value="${vehiclelist.deviceID}">${vehiclelist.description}</option>
</c:forEach></select>
</td>
</tr>
<tr><td align="center"></td></tr>
<tr>
<td valign="middle"></td>
</tr>
</table>
</td><td id="VehicleIdDescDiv" valign="middle">Show overspeed instances more than</td>
<td >
<select name="speed" class="txtbig" >
<option value="">Select</option>
<option value=">100km">>100km</option>
<option value=">90km">>90km</option>
<option value=">80km">>80km</option>
<option value=">70km">>70km</option>
<option value=">60km">>60km</option>
<option value=">50km">>50km</option>
<option value=">40km">>40km</option>
<option value=">30km">>30km</option>
<option value=">20km">>20km</option>
<option value=">10km">>10km</option>
</select> </td>
</tr></table>
<table>
<tr><td> </td></tr>
<tr>
<td width="60%">
<table>
<tr><td>From Date</td>
<td>
<input type="Text" name="AnotherDate" id="demo1" maxlength="25" size="25"><img src="pictures/cal.gif" width="16" height="16" border="0" alt="select">
<br>(eg:- 17-12-2013 19:14:58)
</td>
<td>To Date</td>
<td>
<input type="Text" id="demo2" name="ADate" maxlength="25" size="25"><img src="pictures/cal.gif" width="16" height="16" border="0" alt="select">
<br>(eg:- 17-12-2013 19:14:58)
</td>
</tr>
</table>
</td>
</tr>
<tr><td> </td></tr>
<tr>
<td width="60%"><table width="100%" cellpadding="0" cellspacing="0">
<tr>
<td align="right"><input type="submit" value="Show Report" class="button1"></td>
</tr>
</table></td>
</tr>
<tr><td> </td></tr>
</table>
</td>
</tr>
</table>
</form>
</body>
</html>
overspeedvalidate.js Code wiil be like this:
function validateForm() {
var todayDate = new Date();
var fromDate=document.myForm.AnotherDate.value;
var toDate=document.myForm.ADate.value;
var fromparts = fromDate.split(" ");
var fromdate= fromparts[0];
var fromtime=fromparts[1];
var fromdayfield = fromdate.split("-")[0];
var frommonthfield = fromdate.split("-")[1];
var fromyearfield = fromdate.split("-")[2];
var fromhourfield = fromtime.split(":")[0];
var fromminfield = fromtime.split(":")[1];
var fromsecfield = fromtime.split(":")[2];
var toparts = toDate.split(" ");
var todate= toparts[0];
var totime=toparts[1];
var todayfield = todate.split("-")[0];
var tomonthfield = todate.split("-")[1];
var toyearfield = todate.split("-")[2];
var tohourfield = totime.split(":")[0];
var tominfield = totime.split(":")[1];
var tosecfield = totime.split(":")[2];
var fromDate = new Date(fromyearfield, frommonthfield-1, fromdayfield,fromhourfield,fromminfield,fromsecfield);
var toDate = new Date(toyearfield, tomonthfield-1, todayfield,tohourfield,tominfield,tosecfield);
if(document.myForm.vehicleId.selectedIndex ==0 ){
alert("Please select vehicle number");
document.myForm.vehicleId.focus();
return false;
}else if (document.myForm.speed.selectedIndex == 0){
alert("Please select Speed");
return false;
}else if (document.myForm.AnotherDate.value == null || document.myForm.AnotherDate.value == ""){
alert("Please select FromDate");
document.myForm.AnotherDate.focus();
return false;
}else if (fromDate.getTime()>todayDate.getTime()){
alert("Please select FromDate lessthan CurrentDate");
document.myForm.AnotherDate.focus();
return false;
}
else if (document.myForm.ADate.value == null || document.myForm.ADate.value == ""){
alert("Please select ToDate");
document.myForm.ADate.focus();
return false;
}else if(toDate.getTime()>todayDate.getTime()){
alert("Please select ToDate lessthan CurrentDate");
document.myForm.ADate.focus();
return false;
}else if (fromDate.getTime()>toDate.getTime()){
alert("Please select FromDate lessthan ToDate");
document.myForm.AnotherDate.focus();
return false;
}
return true;
}
when i consider only upto date it is working fine but when i consider both date and time it is not working can any solve my problem

I've tried a javascript function as in the following fiddle it works for me.
Just comapare two date variables with date-time format it will works
http://jsfiddle.net/fNPvf/1307/
function change(){
// new Date(Year, Month, Date, Hr, Min, Sec);
var dateOne = new Date(2012, 04, 20, 14, 55, 59);
var dateTwo = new Date(2012, 04, 20, 12, 10, 20);
//Note: 04 is month i.e. May
if (dateOne > dateTwo) {
alert("Date One is greather then Date Two.");
}else {
alert("Date Two is greather then Date One.");
}
}

Related

Getting Error "(index):1 Uncaught ReferenceError: <func_name> is not defined at HTMLAnchorElement.onclick ((index):1:1)" on clicking delete button

I tried developing an expense tracker app using Javascript, in which the users keep entering the data. I also want to have a delete button which deletes the entered information. I've successfully added the information provided by the users but unable to delete any single information entered by the users. I'm getting the error "(index):1 Uncaught ReferenceError: deleteExpense is not defined at HTMLAnchorElement.onclick ((index):1:1)" after clicking the delete button. Requesting your help. Plese refer my code below.
document.getElementById("submit").addEventListener("click", (e) => {
e.preventDefault();
// Form validation
function validate() {
if (document.myForm.empId.value == "") {
alert("Please provide your Employee ID!");
document.myForm.empId.focus();
return false;
}
if (document.myForm.empName.value == "") {
alert("Please provide your Name!");
document.myForm.empName.focus();
return false;
}
if (document.myForm.PaymentMode.value == "") {
alert("Select your Payment Mode!");
document.myForm.PaymentMode.focus();
return false;
}
if (document.myForm.Date.value == "") {
alert("Please provide the Date!");
document.myForm.Date.focus();
return false;
}
if (document.myForm.Bill.value == "") {
alert("Please provide your Bill Amount!");
document.myForm.Bill.focus();
return false;
}
return true;
}
let id = document.getElementById("id").innerText;
let empId = document.getElementById("empID").value;
let name = document.getElementById("name").innerText;
let empName = document.getElementById("empname").value;
let using = document.getElementById("using").innerText;
let mode = document.getElementById("payment-mode").value;
let day = document.getElementById("day").innerText;
let date = document.getElementById("date").value;
let amount = document.getElementById("amount").innerText;
let bill = document.getElementById("bill").value;
let array = [
[id, empId],
[name, empName],
[using, mode],
[day, date],
[amount, bill],
];
let expenseList = Object.fromEntries(array);
const expenseTable = document.getElementById("expenseTable");
function output() {
if (validate()) {
for (let i = 0; i < Object.keys(expenseList).length; i++) {
expenseTable.innerHTML += `
<tr>
<td>${expenseList[id]}</td>
<td>${expenseList[name]}</td>
<td>${expenseList[using]}</td>
<td>${expenseList[day]}</td>
<td>$${expenseList[amount]}</td>
<td><a class="deleteButton" onclick="deleteExpense(${expenseList[id]})">
Delete</td>
</tr>
`;
break;
}
} else {
return false;
}
const deleteExpense = (id) => {
for (let j = 0; j < Object.keys(expenseList).length; j++) {
if (expenseList[id] == id) {
delete expenseList.id;
}
}
};
deleteExpense();
}
output();
});
.table {
border: 1px solid black;
width: 100%;
}
th {
border-right: 1px solid black;
}
.table td {
border: 1px solid black;
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Expense Tracker Project</title>
<link rel="stylesheet" href="./styles.css" />
</head>
<body>
<div class="employee-info">
<form
class="expenesesForm"
name="myForm"
onsubmit="return(validate());"
method="POST"
action=""
>
<table>
<tr>
<td id="id">Employee ID:</td>
<td>
<input id="empID" name="empId" type="text" placeholder="Employee ID" />
</td>
</tr>
<tr>
<td id="name">Name:</td>
<td>
<input id="empname" type="text" placeholder="Name" name="empName" />
</td>
</tr>
<tr>
<td id="using">Payment Mode:</td>
<td>
<select id="payment-mode" name="PaymentMode">
<option class="" value="" selected disabled>
Select from the list
</option>
<option class="mode" value="card">Card</option>
<option class="mode" value="cheque">Cheque</option>
<option class="mode" value="cash">Cash</option>
<option class="mode" value="other">Other</option>
</select>
</td>
</tr>
<tr>
<td id="day">Date of Transaction:</td>
<td><input id="date" type="date" name="Date" /></td>
</tr>
<tr>
<td id="amount">Amount:</td>
<td><input id="bill" type="number" name="Bill" /></td>
</tr>
<tr>
<td>
<br />
<input id="submit" type="submit" value="Submit" />
<input id="reset" type="reset" value="Cancel" />
</td>
</tr>
</table>
</form>
<br />
<table class="table">
<thead>
<tr>
<th>Employee Id</th>
<th>Name</th>
<th>Mode of Transaction</th>
<th>Date of Transaction</th>
<th>Amount</th>
</tr>
</thead>
<tbody id="expenseTable"></tbody>
</table>
</div>
</body>
</html>
Expected Output:
On clicking the delete button in the table, it should delete one row of information entered by the user.
You are trying to reference the function outside its scope. The snippet below works, but I do not know much about your other requirements, so if this approach is breaking something, then please let me know.
document.getElementById("submit").addEventListener("click", (e) => {
e.preventDefault();
// Form validation
function validate() {
if (document.myForm.empId.value == "") {
alert("Please provide your Employee ID!");
document.myForm.empId.focus();
return false;
}
if (document.myForm.empName.value == "") {
alert("Please provide your Name!");
document.myForm.empName.focus();
return false;
}
if (document.myForm.PaymentMode.value == "") {
alert("Select your Payment Mode!");
document.myForm.PaymentMode.focus();
return false;
}
if (document.myForm.Date.value == "") {
alert("Please provide the Date!");
document.myForm.Date.focus();
return false;
}
if (document.myForm.Bill.value == "") {
alert("Please provide your Bill Amount!");
document.myForm.Bill.focus();
return false;
}
return true;
}
let id = document.getElementById("id").innerText;
let empId = document.getElementById("empID").value;
let name = document.getElementById("name").innerText;
let empName = document.getElementById("empname").value;
let using = document.getElementById("using").innerText;
let mode = document.getElementById("payment-mode").value;
let day = document.getElementById("day").innerText;
let date = document.getElementById("date").value;
let amount = document.getElementById("amount").innerText;
let bill = document.getElementById("bill").value;
let array = [
[id, empId],
[name, empName],
[using, mode],
[day, date],
[amount, bill],
];
let expenseList = Object.fromEntries(array);
const expenseTable = document.getElementById("expenseTable");
function output() {
if (validate()) {
for (let i = 0; i < Object.keys(expenseList).length; i++) {
expenseTable.innerHTML += `
<tr>
<td>${expenseList[id]}</td>
<td>${expenseList[name]}</td>
<td>${expenseList[using]}</td>
<td>${expenseList[day]}</td>
<td>$${expenseList[amount]}</td>
<td><a class="deleteButton">
Delete</td>
</tr>
`;
for (let i = 0; i < expenseTable.children.length; i++)expenseTable.children[i].querySelector('.deleteButton').addEventListener("click", function() {
this.parentNode.parentNode.remove();
});
break;
}
} else {
return false;
}
/*const deleteExpense = (id) => {
for (let j = 0; j < Object.keys(expenseList).length; j++) {
if (expenseList[id] == id) {
delete expenseList.id;
}
}
};
deleteExpense();*/
}
output();
});
.table {
border: 1px solid black;
width: 100%;
}
th {
border-right: 1px solid black;
}
.table td {
border: 1px solid black;
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Expense Tracker Project</title>
<link rel="stylesheet" href="./styles.css" />
</head>
<body>
<div class="employee-info">
<form
class="expenesesForm"
name="myForm"
onsubmit="return(validate());"
method="POST"
action=""
>
<table>
<tr>
<td id="id">Employee ID:</td>
<td>
<input id="empID" name="empId" type="text" placeholder="Employee ID" />
</td>
</tr>
<tr>
<td id="name">Name:</td>
<td>
<input id="empname" type="text" placeholder="Name" name="empName" />
</td>
</tr>
<tr>
<td id="using">Payment Mode:</td>
<td>
<select id="payment-mode" name="PaymentMode">
<option class="" value="" selected disabled>
Select from the list
</option>
<option class="mode" value="card">Card</option>
<option class="mode" value="cheque">Cheque</option>
<option class="mode" value="cash">Cash</option>
<option class="mode" value="other">Other</option>
</select>
</td>
</tr>
<tr>
<td id="day">Date of Transaction:</td>
<td><input id="date" type="date" name="Date" /></td>
</tr>
<tr>
<td id="amount">Amount:</td>
<td><input id="bill" type="number" name="Bill" /></td>
</tr>
<tr>
<td>
<br />
<input id="submit" type="submit" value="Submit" />
<input id="reset" type="reset" value="Cancel" />
</td>
</tr>
</table>
</form>
<br />
<table class="table">
<thead>
<tr>
<th>Employee Id</th>
<th>Name</th>
<th>Mode of Transaction</th>
<th>Date of Transaction</th>
<th>Amount</th>
</tr>
</thead>
<tbody id="expenseTable"></tbody>
</table>
</div>
</body>
</html>
deleteExpense is defined inside your event listener function.
onclick attributes execute in the global scope.
It isn't defined in the scope you are trying to access.
This is one of many problems with onclick attributes. Use addEventListener instead.

Odd behavior of datatables.search function after modifying it

This question is a follow-up to this question.
I've created this JSFiddle for demonstration purposes.
Note that when searching for a value in column1 the search works as expected. However when searching for a value in column2 (using the same "search field"), data_table.search does not appear to be called at all and relevant rows can not be found (press F12 to see debug info in the console).
var data_table = $("#table").DataTable();
var search_term = null;
$.fn.DataTable.ext.search.push(
function(settings, row, index) {
if (search_term) {
search_term = search_term.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
search_term = search_term.toLowerCase();
}
console.log(`search_term is ${search_term}`)
var approver = $(data_table.cell(`:eq(${index})`, ':eq(0)').node()).find('.approver-select').val().toLowerCase();
console.log(`approver is ${approver}`)
var approver_match = approver.match(search_term);
console.log(`approver_match is ${approver_match}`)
var network_or_group = $(data_table.cell(`:eq(${index})`, ':eq(1)').node()).find('.network-or-group-text').val().toLowerCase();
console.log(`network_or_group is ${network_or_group}`)
var network_or_group_match = network_or_group.match(search_term);
console.log(`network_or_group_match is ${network_or_group_match}`)
console.log(`approver_match || network_or_group_match || !search_term is ${approver_match || network_or_group_match || !search_term}`)
console.log('')
console.log('')
return approver_match || network_or_group_match || !search_term;
}
);
$('#table_filter input', data_table.table().container()).on('keyup.DT cut.DT paste.DT input.DT search.DT', event => {
search_term = $(event.target).val();
data_table.draw();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<table id="table">
<thead>
<th>column1</th>
<th>column2</th>
</thead>
<tbody>
<tr>
<td>
<select class="approver-select">
<option selected>user1</option>
<option>user2</option>
</select>
</td>
<td>
<input class="network-or-group-text" type="text" value="1.1.1.1/32">
</td>
</tr>
<tr>
<td>
<select class="approver-select">
<option>user1</option>
<option selected>user2</option>
</select>
</td>
<td>
<input class="network-or-group-text" type="text" value="2.2.2.0/24">
</td>
</tr>
</tbody>
</table>
</body>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</html>
A simpler way of doing it using the html-input type is as below. You define the columns you're targeting and you're returning the value upon search. It works for both the select and the input.
You won't need to check for keyup.DT cut.DT paste.DT input.DT search.DT as datatables does that for you automatically as well.
$.fn.dataTableExt.ofnSearch['html-input'] = function(value) {
return $(value).val();
};
var data_table = $("#table").DataTable({
columnDefs: [{
"type": "html-input",
"targets": [0, 1]
}]
});
<html>
<body>
<table id="table">
<thead>
<th>column1</th>
<th>column2</th>
</thead>
<tbody>
<tr>
<td>
<select class="approver-select">
<option selected>user1</option>
<option>user2</option>
</select>
</td>
<td>
<input class="network-or-group-text" type="text" value="1.1.1.1/32">
</td>
</tr>
<tr>
<td>
<select class="approver-select">
<option>user1</option>
<option selected>user2</option>
</select>
</td>
<td>
<input class="network-or-group-text" type="text" value="2.2.2.0/24">
</td>
</tr>
</tbody>
</table>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</html>
This is cleaner and uses the basic type property of datatables rather than filtering all data upon search as you're doing right now.

java script doesn't get the data from jsp

It's about search and paging functions.
this shows keyWord and keyField well on console when i search keyWord .
<%
String keyWord = (String)request.getParameter("keyWord");
String keyField = (String)request.getParameter("keyField");
System.out.println(keyWord);
System.out.println(keyField);
%>
but this doesn't work.
address appear like this. didn't get data from javascript code.
http://localhost:8090/mvcBoard/list.do?page=2&keyWord=&keyField=
function PageMove(page){
var keyWord = '<%request.getParameter("keyword");%>';
var keyField = '<%request.getParameter("keyField");%>';
console.log(keyWord);
location.href = "list.do?page="+page+"&keyWord=" + keyWord + "&keyField=" + keyField;
}
but it works!
location.href = "list.do?page="+page;
this is list.jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<%
String keyWord = (String)request.getParameter("keyWord");
String keyField = (String)request.getParameter("keyField");
System.out.println(keyWord);
System.out.println(keyField);
%>
<script>
function searchCheck(frm){
//검색
if(frm.keyWord.value ==""){
alert("검색 단어를 입력하세요.");
frm.keyWord.focus();
return;
}
frm.submit();
}
function PageMove(page){
var keyWord = '<%request.getParameter("keyword");%>';
var keyField = '<%request.getParameter("keyField");%>';
console.log(keyWord);
if(keyWord){
location.href = "list.do?page="+page+"&keyWord=" + keyWord + "&keyField=" + keyField;
}
location.href = "list.do?page="+page+"&keyWord=" + keyWord + "&keyField=" + keyField;
}
</script>
</head>
<body>
<table width="800" cellpadding="0" cellspacing="0" border="1">
<tr>
<td>번호</td>
<td>이름</td>
<td>제목</td>
<td>날짜</td>
<td>조히수</td>
</tr>
<c:forEach items="${list}" var="dto">
<tr>
<td>${dto.bId}</td>
<td>${dto.bName}</td>
<td>
<c:forEach begin="1" end="${dto.bIndent}">-</c:forEach>
${dto.bTitle}</td>
<td>${dto.bDate}</td>
<td>${dto.bHit}</td>
</tr>
</c:forEach>
<tr>
<td colspan="5">
<form action="list.do" method="post" name="search">
<select name="keyField">
<option value="bTitle">글 제목</option>
<option value="bContent">글 내용</option>
<option value="bName">작성자</option>
</select>
<input type="text" name="keyWord">
<input type="button" value="검색" onclick="searchCheck(form)">
<input type="hidden" id=keyField value="${paging.keyField}">
<input type="hidden" id=keyWord value="${paging.keyWord}">
</form>
</td>
</tr>
<tr>
<td colspan="5"> 글작성 </td>
</tr>
</table>
<%-- <%=PageAction.pageNumber() %>
--%>
<div class="toolbar-bottom">
<div class="toolbar mt-lg">
<div class="sorter">
<ul class="pagination">
<li>맨앞으로</li>
<li>앞으로</li>
<c:forEach var="i" begin="${paging.startPageNo}" end="${paging.endPageNo}" step="1">
<c:choose>
<c:when test="${i eq paging.pageNo}">
<li class="active">${i}</li>
</c:when>
<c:otherwise>
<li>${i}</li>
</c:otherwise>
</c:choose>
</c:forEach>
<li>뒤로</li>
<li>맨뒤로</li>
</ul>
</div>
</div>
</div>
</body>
</html>
For a start this code looks wrong
<input type="hidden" value="${paging.getkeyField()}">
<input type="hidden" value="${paging.getKeyWord()}">
change to the same format as paging.nextPageNo
<input type="hidden" value="${paging.keyField}">
<input type="hidden" value="${paging.keyWord}">
next you either add an id to this hidden fields (and get the value using Javascript or jquery)
<input type="hidden" id="kf" value="${paging.keyField}">
or use the same parameter passing as paging.nextPageNo to PageMove
javascript:PageMove(${paging.nextPageNo}, ${paging.keyField}); // etc

I want to pop up a confirmation message after all message after submitting

This my jsp page and i'm doing Employee management work now and i want to popup a confirmation message after all my validations are successful or true and it should ask user yes or no. for the submission of the form.
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%# page session="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Employee Management System</title>
<link href="CSS/style.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/smoothness/jquery-ui.css" />
<script language="javascript" type="text/javascript">
function checkform(pform1){
var str=pform1.bloodGroup.value;
var email = pform1.email.value;
var phone = pform1.phoneNumber.value;
var cleanstr = phone.replace(/[\(\)\.\-\ ]/g, '');
var err={};
var validemail =/^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var income = pform1.annualIncome.value;
var Id = pform1.employeeId.value;
var salary = income.replace(/[\(\)\.\-\ ]/g, '');
var Eid = Id.replace(/[\(\)\.\-\ ]/g, '');
//check required fields
//password should be minimum 4 chars but not greater than 8
if (((str.length < 1) || (str.length > 3))&& (!(str.notequals("")))) {
err.message="Invalid blood group";
err.field=pform1.bloodGroup;
}
//validate email
else if( (email != "") && !(validemail.test(email))){
err.message="Invalid email";
err.field=pform1.email;
}
//check phone number
else if (isNaN((cleanstr))) {
err.message="Invalid phone number";
err.field=pform1.phoneNumber;
}
else if (isNaN((salary))) {
err.message="Invalid Annual Income";
err.field=pform1.annualIncome;
}
else if (isNaN((Eid))) {
err.message="Invalid EmployeeID";
err.field=pform1.annualIncome;
}
if(err.message)
{
document.getElementById('divError').innerHTML = err.message;
err.field.focus();
alert(err.message);
return false;
}
else
{
return true;
}
}
</script>
<script>
$(function() {
$( "#dateOfBirth" ).datepicker({
showOn: "button",
buttonImage: "Pictures/calendicon.jpg" ,
buttonImageOnly: true,
buttonText: "Select date",
/* dateFormat: 'dd/mm/yy ' */
});
});
</script>
</head>
<body><center>
<h2>Employee Management System</h2>
<form:form method="POST" action="./add.html" modelAttribute ="employee" onsubmit="return checkform(this);" >
<div id="errmsgbox">
<div id="divError"></div>
</div>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="14%">Employee ID<span class="mandatory" >*</span></td>
<td width="35%"> <form:hidden path="ID" />
<form:input path="employeeId" required = "required"/></td>
<td width="16%">Employee Name<span class="mandatory" >*</span></td>
<td width="35%"><form:input path="employeeName" required = "required" /></td>
</tr>
<tr>
<td>DOB<span class="mandatory" >*</span></td>
<td><form:input path ="dateOfBirth" required = "required" id="dateOfBirth"></form:input></td>
<style>
img.ui-datepicker-trigger {
width: 15px;
height: 15px;
}
</style>
<td>Blood group </td>
<td><form:input path="bloodGroup" /></td>
</tr>
<tr>
<td>Annual Income </td>
<td><form:input path ="annualIncome" /></td>
<td>Qualification</td>
<td><form:input path ="qualification" /></td>
</tr>
<tr>
<td>Pan No.</td>
<td><form:input path="panNumber" /></td>
<td>Phone No. </td>
<td><form:input path="phoneNumber" /></td>
</tr>
<tr>
<td>Sex</td>
<td><form:radiobutton path="sex" value="m"/>Male
<form:radiobutton path="sex" value="f"/>Female</td>
<td>Email</td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td>Address</td>
<td colspan="3"><textarea name="" cols="" rows="2"></textarea></td>
</tr>
</table>
<div>
<input name="submit2" type="submit" title="Submit" value="Submit" />
<input type="button" name="reset_form" value="Reset" onclick="this.form.reset();"/>
<input name="submit3" type="button" title="Reset" value="View All"/>
</div>
</form:form>
</center>
</body>
</html>
Replace you else block by following code in checkform():
if(confirm("Your question here?")) {
return true;
} else {
return false;
}
You can use alert() in the javascript.

JavaScript White Space Validation not working

I have written JSP code and I need to check white space validation, But it is not working can someone tell me the reason. While clicking submit button it must validate for white space and characters.
JSP Code
<%--
Document : LapsePeriodicFeedBack
Created on : Dec 7, 2012, 2:50:28 PM
Author : Admin
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%# page import="java.util.*" %>
<%#page import="PeriodicFeedBack.PeriodicType"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>LapsePeriodicList</title>
<script>
function validateForm(){
var selectindex=document.forms["lapse"]["periodmenu"].selectedIndex;
var whitespace = new RegExp("^\w*$");
var x= document.forms["lapse"]["lapsedays"].value;
var textlength=document.forms["lapse"]["lapsedays"].length;
if(x==""){
alert("Days Cant Be Empty");
return false;
}
if(x==whitespace){
alert("White Spaces are not Allowed");
return false;
}
if(selectindex==0){
alert("Please select Days from menu");
}
}
if(x=="/\\s"){
alert('Sorry, you are not allowed to enter any spaces');
x.value=x.value.replace(/\s/g,'');
}
</script>
</head>
<body>
<form method="post" name="lapse" onsubmit="return validateForm()">
<table width="500px" border="1" align="center" style='border-collapse: collapse;font: 13px Arial, Helvetica, sans-serif;' bordercolor='#000000'>
<tr style="color:'#ffffff';background-color:#CA1619;background-repeat:repeat-x;font: 13px Arial, Helvetica, sans-serif;">
<td colspan="4" align="center">
<font color="#ffffff" > <b>Periodic Feedback List</b></font></td></tr>
<tr>
<td align="center">
Periodic Feedback Days</td>
<td align="center">
<select id="periodmenu">
<option> Select</option>
<%
PeriodicType p = new PeriodicType();
ArrayList periodicList = p.getPeriodicType();
for (int i = 0; i < periodicList.size(); i++) {%>
<option>
<% out.println(periodicList.get(i));
}%>
</option>
</select></td>
</tr>
<tr>
<td align="center">
Lapse Days </td>
<td align="center">
<p>
<input name="lapsedays" type="text" id="lapsedays" onkeyup="nospaces(this)"/></p>
<input name="Submit" type="submit" value="Submit" /></td>
</tr>
</table>
</form>
<p>
</p>
</body>
</html>
You can't use x==whitespace to check x against a regular expression. Use the following:
whitespace.test(x);
That'll return true or false.
In addition, you should not use new RegExp for this, you should instead use the literal operators:
var whitespace = /^\w*$/;

Categories

Resources