Link to home
Start Free TrialLog in
Avatar of puneet kumar
puneet kumar

asked on

need to validate date in tabular formate

Hi I m populating data like below in tabular foarmat . my requirement is like while submiting ajax call before that
each row which is cheked having 3 date field need to validate Q Date should greater then P Date ,
B Date sholud be greater then Q Date and P Date. pelase help me out with some code snippet.


<table align=center>

<tr>			<th>Check/UnCheck</th>
                <th>MYear</th>
                <th>P Date</th>
                <th>Q Date</th>
                <th>B Date</th>
</tr>
<%for(int i=0 ; i<mVector.size();i++)
{
	
%>
 <tr>
<td align="top">
<INPUT type="checkbox" class="chkValues" id="ckbCheckAll" name="chkBox" type="checkbox" data-row="row<%=i%>" value="" size="50">
</td>
<td align="left">
<input class="inputText row<%=i%>" type="text" name="mYear" id="mYear"  value="<%=mVector.elementAt(i)%>">
</td>

				<td>
		            <input class="date row<%=i%>" id="pDate<%=i%>" name="dob" type="text" value="<%=(oldValues.elementAt(0)==null?"":oldValues.elementAt(0))%>" />
				</td>
				<td>
		            <input class="date row<%=i%>" id="qDate<%=i%>" name="dob" type="text" value="<%=(oldValues.elementAt(1)==null?"":oldValues.elementAt(1))%>" />
				</td>
				<td>
		            <input class="date row<%=i%>" id="bDate<%=i%>" name="dob" type="text" value="<%=(oldValues.elementAt(2)==null?"":oldValues.elementAt(2))%>" />
				</td>

</tr> 
<%}%>

</table>

Open in new window



ajax call is like below


$(document).ready(function() {

	$(".date").datepicker({dateFormat:'dd/mm/yy'});
	

	$('.chkValues').on('click', function() {

		//get values of dates
		var array = [];
		$row = $(this).data('row'); //row1, row2, row3 etc
		$('input.' + $row).each(function() {
			array.push($(this).val());
		});
		$('#btnSubmit').click(function(evt) {
    	evt.preventDefault();
    	$.ajax({
            type: "POST",
            url: "Test.jsp",
            data: {array : array},
            success: function(responseFromServer) {
            	 $.each(responseFromServer, function(resultMessageKey,resultMessageValue) {	
                    $('#content').html(resultMessageKey);
                });
    	    	//getClearDateValues();
    		
            },
            error: function() {
                alert(" Ajax call Failed to Update Values  into Database ");
            }
        }); 
		});

	});

});

Open in new window

Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Your input's all have the same name - that is potentially going to cause a problem.

To validate - are you validating the entire table or only a specific row?

This seems to be a duplicate / extension of your other question (https://www.experts-exchange.com/questions/29168950/in-grid-view-checkbox-is-Enable-while-particular-row-cell-is-clicked.html) where I asked you some questions that you have not answered.

Still don't have the answers but will try to answer your question here.

Firstly I cannot see the sense in the checkbox - you have not explained this functionality - I am assuming that (in this case) the user must click the checkbox when they have changed the dates (in the other question it seems the checkbox has a different function).

Let's go with the click checkbox to validate
(Assumes the table is not dynamically generated - if it is then the event below will not fire after the table has been dynamically re-rendered).

$(function() {
  $('.chkValues').on('click', function() {
    // First get the parent row.
    var parent = $(this).closest('tr');
    
    // Now find all the child <inpu> elements with class "date"
    var last = 0;
    $('.date', parent).each(function(i,e) {
      var dt = new Date(e.value);
      // Compare this input to the value of the last and if it is less than or equal display an error
      if (dt.getTime() <= last) {
        alert('Error: ' + e.id + ' has an invalid value');
      }
      
      last = dt.getTime();
    });
    
  });
});

Open in new window

Avatar of puneet kumar
puneet kumar

ASKER

Hi Julian

not same question let me explain again i have a tabular form where 3 dates are there
if some changes the date i want to validate that 2nd date should greater then 1st one
and 3rd one should greater them 2nd and 1st.
in above code it is comparing with 0   how can i get previous date and compare with other clicked date .
please help me on this and give me some code snippet based on my code .
I understand the situation - what is not clear is the mechanics around it.
How is the checkbox used - that is what you seem reluctant to elaborate on.
in above code it is comparing with 0   how can i get previous date and compare with other clicked date .
The above code is correct as it stands.
Line 8 collects all the input elements in the row with class date.
P first
Then Q
Then B
We then iterate over that collection of elements and look for instances where the current date is <= to the previous date.
For P there IS NO PREVIOUS DATE so we use 0 as the comparison as P will always be greater than 0
After the first iteration last is now equal to P's date so when we go around again and compare Q we are now comparing Q to the value of P - if Q is less  than or equal to P you get an error.
Again we set last to Q and proceed on to evaluate B.

The code is correct as it stands.
I have put a working sample here to demonstrate
https//www.marcorpsa.com/ee/t3786.html
Thanx julian can you please give me code snippet with my code to understand easy . i am very new to java script , jquery , ajax
so for that i m asking it will help me a lot. and i want different validation alerts like below -
for 1st date and 2nd date = 2nd date should greater then 1st one .
for 2nd date and 3rd date = 3rd date should be greater then 2nd one.
for 3nd date and 1rd date = 3rd date should be greater then 1st one.
I have already given you code. You can use that exactly as it is. It does exactly what you are asking for.
Here it is again.
$(function() {
  $('.chkValues').on('click', function() {
    // First get the parent row.
    var parent = $(this).closest('tr');
    
    // Now find all the child <inpu> elements with class "date"
    var last = 0;
    $('.date', parent).each(function(i,e) {
      var dt = new Date(e.value);
      // Compare this input to the value of the last and if it is less than or equal display an error
      if (dt.getTime() <= last) {
        alert('Error: ' + e.id + ' has an invalid value');
      }
      
      last = dt.getTime();
    });
    
  });
});

Open in new window

yes julian this is right but how can i display 3 different alert as i mentioned above -

for 1st date and 2nd date = 2nd date should greater then 1st one .
for 2nd date and 3rd date = 3rd date should be greater then 2nd one.
for 3nd date and 1rd date = 3rd date should be greater then 1st one.
Hi julian i tried to insert into my document.redy () function as below but its not alerting please help me out where i m doing wrong -

[code]$(document).ready(function() {

	$(".date").datepicker({dateFormat:'dd/mm/yy'});
	$('.chkValues').on('click', function() {
		//get values of dates
		var array = [];
		var parent = $(this).closest('tr');
	    
	    // Now find all the child <inpu> elements with class "date"
	    var last = 0;
	    $('.date', parent).each(function(i,e) {
	      var dt = new Date(e.value);
	      console.log(dt.getTime());
	      if (dt.getTime() <= last) {
	        alert('Error: ' + e.id + ' has an invalid value');
	      }
	      last = dt.getTime();
	    });
		$row = $(this).data('row'); //row1, row2, row3 etc
		$('input.' + $row).each(function() {
			array.push($(this).val());
		});
		$('#btnSubmit').click(function(evt) {
    	evt.preventDefault();
    	$.ajax({
            type: "POST",
            url: "Test.jsp",
            data: {array : array},
            success: function(responseFromServer) {
            	 $.each(responseFromServer, function(resultMessageKey,resultMessageValue) {	
                    $('#content').html(resultMessageKey);
                });
    	    },
            error: function() {
                alert(" Ajax call Failed to Update Values  into Database ");
            }
        }); 
		});

	});

});

Open in new window

Are there any errors in your console?

I copied the above code directly into my test code which looks as below and it works fine
  <tr>
    <th>Check/UnCheck</th>
      <th>MYear</th>
      <th>P Date</th>
      <th>Q Date</th>
      <th>B Date</th>
  </tr>
  <tr>
    <td align="top">
      <input type="checkbox" class="chkValues" id="ckbCheckAll" name="chkBox" type="checkbox" data-row="1" value="" size="50">
    </td>
    <td align="left">
      <input class="inputText row1" type="text" name="mYear" id="mYear"  value="2020">
    </td>
    <td>
      <input class="date row1" id="pDate1" name="dob" type="date" value="2020-01-01" />
    </td>
    <td>
      <input class="date row1" id="qDate1" name="dob" type="date" value="2020-01-01" />
    </td>
    <td>
      <input class="date row1" id="bDate1" name="dob" type="date" value="2020-01-01" />
    </td>
  </tr> 
  <tr>
    <td align="top">
      <input type="checkbox" class="chkValues" id="ckbCheckAll" name="chkBox" type="checkbox" data-row="2" value="" size="50">
    </td>
    <td align="left">
      <input class="inputText row2" type="text" name="mYear" id="mYear"  value="2020">
    </td>
    <td>
      <input class="date row2" id="pDate2" name="dob" type="date" value="2020-02-01" />
    </td>
    <td>
      <input class="date row2" id="qDate2" name="dob" type="date" value="2020-02-01" />
    </td>
    <td>
      <input class="date row2" id="bDate2" name="dob" type="date" value="2020-02-01" />
    </td>
  </tr> 
</table>  

Open in new window


You will need to provide a link to your page so we can see what is going on - or post the rendered HTML (NOT THE JSP CODE).
HI julian please find the attached rendered html please let me know where i m doing wrong. thanx for the help.
PostRendered.html
Hi Julian please help me out on above.
Your problem is that your date strings are not formatted correctly. If you look at the Date documentation you will see that it refers to the ISO date standard.

Try outputting your date strings as Y-m-d - when I change the values to this format the code works.
HI julian,

you are right its working please tell me the way without changing my format can i achieve that and also that 3 different alerts what i need to show end user like below -

for 1st date and 2nd date = 2nd date should greater then 1st one .
for 2nd date and 3rd date = 3rd date should be greater then 2nd one.
for 3nd date and 1rd date = 3rd date should be greater then 1st one.

because i don't want to change the format its requirement hope you understand  it would be great thanx to you .
The format is as it is. You will have to modify the format in your code before testing the values.

var dateParts = e.value.split('/');
var dt = new Date(dateParts[2], dateParts[0], dateParts[1]);
// Date is now in correct format

Open in new window


if (dt.getTime() <= last) {
  alert('Error: ' + e.id + ' must be greater than ' + lastId);
}
...
lastId = e.id;

Open in new window

hi julian

thanx for all of your support i want to print alert like (2nd date is must be greater then 1st date)
here its "showing date0 invalid id" its alerting id like 0,1,2
please tell how to change it .
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you julian you help me a lot to solve this you are very knowledgeable and supportive  .thank you once again.
You are welcome.
Hi Julian one bug is coming when validation fails then also ajax request is executing please tell me the solution.
var valid = true;
if (dt.getTime() <= last) {
  alert('Error: ' + (i+1) + lbl[i] + ' date must be greater than ' + i + lbl[i-1] + ' date');
  valid = false;
}
...
if (valid) {
  // do AJAX here
}

Open in new window

[..] one bug is coming when validation fails then also ajax request is executing please tell me the solution.
Obviously. Cause you mixed the checkbox event with the submit event..

$(document).ready(function() {
    $(".date").datepicker({dateFormat:'dd/mm/yy'});
    $('.chkValues').on('click', function() {
        $('#btnSubmit').click(function(evt) {
        });
    });
});

Open in new window

instead of

$(document).ready(function() {
    $(".date").datepicker({dateFormat:'dd/mm/yy'});
    $('.chkValues').on('click', function() {
    });
    $('#btnSubmit').click(function(evt) {
    });
});

Open in new window