Javascript handling data in a gridview - javascript

I have from date and to date. I am getting valid date on submit button in gridview.
I have kept validations on date fields but if valid dates are given the data is shown, then again without refreshing the page if I give the wrong dates the validations are shown but the last data is also visible.
How to handle that situation?
function Validate() {
var FromDate = document.getElementById('<%=frmDate.ClientID %>').value;
var ToDate = document.getElementById('<%=toDate.ClientID %>').value;
if (FromDate == "") {
alert("Select From date");
return false;
}
if (ToDate == "") {
alert("Select To Date");
return false;
}
if (Date.parse(FromDate) > Date.parse(ToDate)) {
alert("Invalid Date Range!\nStart Date cannot be after End Date!")
return false;
}
}

Hide the gridview if validation fails
$('table[id$=gridViewId]').hide();
else if all validations pass then show it
$('table[id$=gridViewId]').show();
function Validate() {
var FromDate = document.getElementById('<%=frmDate.ClientID %>').value;
var ToDate = document.getElementById('<%=toDate.ClientID %>').value;
if (FromDate == "") {
$('table[id$=gridViewId]').hide();
alert("Select From date");
return false;
}
if (ToDate == "") {
$('table[id$=gridViewId]').hide();
alert("Select To Date");
return false;
}
if (Date.parse(FromDate) > Date.parse(ToDate)) {
$('table[id$=gridViewId]').hide();
alert("Invalid Date Range!\nStart Date cannot be after End Date!")
return false;
}
//Validations passed hence show the gridview
$('table[id$=gridViewId]').show();
}

Related

Javascript alert message is not working, why?

Javascript alert message is not working in dev server but works in test instance? Please help to find the issue.
if (expdt.value == "") {
alert("Expiration Date must be entered");
expdt.focus();
formSubmitted = false;
return false;
}else
{
var dtpattern = /(0|1)[0-9]\/(19|20)[0-9]{2}/;
if (dtpattern.test(expdt.value))
{
var date_array = expdt.value.split('/');
var month = date_array[0]-1;
var year = date_array[1];
source_date = new Date();
if (year >= source_date.getFullYear())
{
if (month >= source_date.getMonth())
{
return '';
} else {
if (year == source_date.getFullYear())
{
alert("Expiration Date: Month must be greater than or equal to current month");
expdt.focus();
formSubmitted = false;
return false;
}
}
} else {
alert("Expiration Date: Year must be greater than or equal to current year");
expdt.focus();
formSubmitted = false;
return false;
}
}
else
{
alert("Expiration Date must match the format MM/YYYY");
expdt.focus();
formSubmitted = false;
return false;
}
}
if (cardnumber.value == "") {
alert("Card Number must be entered");
cardnumber.focus();
formSubmitted = false;
return false;
}
Only expiry date validation alert message is working in dev server but other alert messages after exp date validation also works in test instance. What is the issue?
Thanks in advance.
The reason your code doesn't execute the cardnumber validation is when
if (year >= source_date.getFullYear()) {
if (month >= source_date.getMonth()) {
return "";
}
No more checking occurs when this condition is met because you've returned "", that's it. Function over man!
Try coding without using else - it makes code flatter and more readable
Inverting some of the conditions (e.g. instead of if (dtpattern.test(expdt.value)) do if (!dtpattern.test(expdt.value)) since you return in that case) you can use a series of so-called "guard clauses" to drastically improve the readability of your code
An example guide on guard clauses - there's many more if you search.
For example - your code is simply this
if (expdt.value == "") {
alert("Expiration Date must be entered");
expdt.focus();
formSubmitted = false;
return false;
}
var dtpattern = /(0|1)[0-9]\/(19|20)[0-9]{2}/;
if (!dtpattern.test(expdt.value)) {
alert("Expiration Date must match the format MM/YYYY");
expdt.focus();
formSubmitted = false;
return false;
}
var date_array = expdt.value.split("/");
var month = date_array[0] - 1;
var year = date_array[1];
const source_date = new Date();
const source_year = source_date.getFullYear();
const source_month= source_date.getMonth();
if (year < source_year) {
alert(
"Expiration Date: Year must be greater than or equal to current year"
);
expdt.focus();
formSubmitted = false;
return false;
}
if (month < source_month && year == source_year) {
alert(
"Expiration Date: Month must be greater than or equal to current month"
);
expdt.focus();
formSubmitted = false;
return false;
}
if (cardnumber.value == "") {
alert("Card Number must be entered");
cardnumber.focus();
formSubmitted = false;
return false;
}
return "";
Notice how all the fail conditions are at the "root" indentation of the code?
Side note: I decided to remove else in a medium sized company PWA - I'm down to ONE in the whole project, and I could remove it fairly easily, but I find that remaining else to be more readable than the alternative

How to stop button text change after page load?

I have a two text box and Enable button.If the data is entered wrongly in the text box on clicking enable button it alerts it.If all the data is correct, on clicking the enable button,text must become disable .The problem is once i click enable it becomes disable for a second then the page loads it again goes to Enable.Can any one tell me what i am doing wrongly .Please provide a example if possible .Thanks in advance
Script to validate and change the button text
function validate
{
var cal1 = document.getElementById('<%=txtEndDate.ClientId%>').value;
var cal2 = document.getElementById('<%=txtStartDate.ClientId%>').value;
var button=document.getElementById('<%=button1.ClientId %>')
if (cal1 == '' && cal2 == '') {
alert("Start Date and End Date can not be left blank ");
return false;
}
if (cal1 == '') {
alert("End Date can not be left blank ");
return false;
}
if (cal2 == '') {
alert("Start Date can not be left blank ");
return false;
}
if (cal1 != '' || cal2 != '')
{
var dt1 = Date.parse(cal1);
var dt2 = Date.parse(cal2);
if (dt1 <= dt2) {
alert("End Date must occur after the Start date ");
return false;
}
}
//if the all the validation are correct it comes to this
if (button.value == "Enable")
button.value = "Disable";
else
button.value = "Enable";
return true;
}
button
<asp:Button ID="button1" OnClientClick=" return validate()" runat="server" Text="Enable" />
Condition will be && in place of || and you pass return false to stop postback
After completing your validation try to return false and use if - else will save your time of validate
function validate()
{
var cal1 = document.getElementById('<%=txtEndDate.ClientId%>').value;
var cal2 = document.getElementById('<%=txtStartDate.ClientId%>').value;
var button=document.getElementById('<%=button1.ClientId %>')
if (cal1 == '') {
alert("End Date can not be left blank ");
return false;
}
else if (cal2 == '') {
alert("Start Date can not be left blank ");
return false;
}
else if (cal1 != '' && cal2 != '')
{
var dt1 = Date.parse(cal1);
var dt2 = Date.parse(cal2);
if (dt1 <= dt2) {
alert("End Date must occur after the Start date ");
return false;
}
else{
//if the all the validation are correct it comes to this
if (button.value == "Enable")
button.value = "Disable";
else
button.value = "Enable";
}
}
return false;
}
and Button - <asp:Button ID="button1" OnClientClick=" return validate();" runat="server" Text="Enable" />
Your problem is that the default action of a click event of an button (<input type="button">) is to submit the form. You can prevent that by returning false from the event handler. the simplest way to do that in your case would be to ALWAYS return false from your validate function.
After completing your validation try to return false
function validate()
{
var cal1 = document.getElementById('<%=txtEndDate.ClientId%>').value;
var cal2 = document.getElementById('<%=txtStartDate.ClientId%>').value;
var button=document.getElementById('<%=button1.ClientId %>')
if (cal1 == '') {
alert("End Date can not be left blank ");
return false;
}
if (cal2 == '') {
alert("Start Date can not be left blank ");
return false;
}
if (cal1 != '' || cal2 != '')
{
var dt1 = Date.parse(cal1);
var dt2 = Date.parse(cal2);
if (dt1 <= dt2) {
alert("End Date must occur after the Start date ");
return false;
}
}
//if the all the validation are correct it comes to this
if (button.value == "Enable")
button.value = "Disable";
else
button.value = "Enable";
return false;
}

JavaScript date throws Invalid Date

i am trying to compare two dates from date and to date following is my method :
function isValidDate() {
var fromDate ="";
var toDate ="";
var fromDateTemp = $("#fromRequestDate").val(); //2013-12-05
var toDateTemp = $("#toRequestDate").val(); //2013-12-01
if(fromDateTemp.length != '0' && toDateTemp.length != '0'){
fromDate = new Date(fromDateTemp);
toDate = new Date(toDateTemp);
}
if (fromDate.length != '0' || toDate.length != '0') {
$("#validationMessage").text("Please Select From Date and To Date");
return false;
} else if (fromDate.getDate() > toDate.getDate()) {
$("#validationMessage").text("From Date is greater than To Date");
return false;
} else {
$("#validationMessage").text("");
return true;
}
}
but i get Ivalid Date as well as undefined when calculating length.
so please help me to find the issue.
Thanks
We usually compare two Dates using getTime (it returns the number of milliseconds passed since 1970)
So,
fromDate.getTime() > toDate.getTime()
ought to work. Assuming, of course, that the values being taken from the #fromReqDate and #toReqDate are instances of Date (simple check fromDate instanceOf Date should return true)
Try using this.
if(isNaN(new Date(fromDateTemp)))
{
alert("Please enter a valid from date");
return;
}
var fromDateTemp = $("#fromRequestDate").val(); //2013-12-05
var toDateTemp = $("#toRequestDate").val(); //2013-12-01
instead of these two code just replace the following codes
var fromDateTemp = new Date(''+$("#fromRequestDate").val()); //2013-12-05
var toDateTemp = new Date(''+$("#toRequestDate").val()); //2013-12-01
I think mistake is in your condition checking if (fromDate.length == '0' || toDate.length == '0') instead of this you used if(fromDateTemp.length != '0' && toDateTemp.length != '0') check the code and revert if you are facing issue still.
var fromDate ="";
var toDate ="";
var fromDateTemp = '2013-12-05'; //2013-12-05
var toDateTemp = '2013-12-01'; //2013-12-01
if(fromDateTemp.length != '0' && toDateTemp.length != '0'){
fromDate = new Date(fromDateTemp);
toDate = new Date(toDateTemp);
}
if (fromDate.length == '0' || toDate.length == '0') {
alert("Please Select From Date and To Date");
return false;
} else if (fromDate.getDate() > toDate.getDate()) {
alert("From Date is greater than To Date");
return false;
} else {
alert("");
return true;
}
Here's corrected js:
Demo
function isValidDate() {
var fromDate = null;
var toDate = null;
var fromDateTemp = $("#fromRequestDate").val();
var toDateTemp = $("#toRequestDate").val();
if(fromDateTemp.length != 0 && toDateTemp.length != 0){
fromDate = new Date(fromDateTemp);
toDate = new Date(toDateTemp);
}
if (fromDate == null || toDate == null) {
$("#validationMessage").text("Please Select From Date and To Date");
return false;
} else if (fromDate.getTime() > toDate.getTime()) {
$("#validationMessage").text("From Date is greater than To Date");
return false;
} else {
$("#validationMessage").text("");
return true;
}
}

compare only time vlaue from textbox using javascript?

I am taking three text boxes. time in text boxes are not to be same. means 1st text box value is 2013-10-01 12:00 date time.and second is 2013-10-01 12:00 and third also 2013-10-12 12:00.but actual problem is that when date are diff-rent then same time should be allow.when date and time are same so it should through error message or alert message to user.please help me to solve this.
function validate Form()
{
var a=document.get Element By Id("mybox1"). value;
var b=document.get Element By Id("mybox2"). value;
var c=document.get Element By Id("mybox3"). value;
var a_time = a.replace(/ /g,''). sub st r (a.replace(/ /g,''). length - 5);
var b_time = b.replace(/ /g,''). sub st r (b.replace(/ /g,''). length - 5);
var c_time = c.replace(/ /g,''). sub st r (c.replace(/ /g,''). length - 5);
if (a=="" && b=="" && c=="")
{
alert("Please select at least one date and time !");
return false;
}
else if (a_time === b_time)
{
alert("Please select diff-rent time!");
return false;
}
else if (a_time === c_time)
{
alert("Please select diff-rent time!");
return false;
}
else
{
return true;
}
}
Try this... only need to compare date too...
if (a=="" && b=="" && c=="")
{
alert("Please select at least one date and time !");
return false;
}
else if (a_time === b_time && a===b)
{
alert("Please select diff-rent time!");
return false;
}
else if (a_time === c_time && a===c)
{
alert("Please select diff-rent time!");
return false;
}

Date Validation not working using JavaScript

I have two two date fields - from date and to date, and i need to validate 3 things
Both the values are entered or not
Date datatype check
To date must be greater than from date.
But my script is not working.
can some body please check?
Thanks
function checkBothDates(sender,args)
{
var from = document.getElementById(sender.From);
var to = document.getElementById(sender.To);
var behaviorId = sender.behavior;
var from_value = from.value;
var to_value = to.value;
if((from_value == "")&&(to_value == ""))
{
args.IsValid = true;
}
else
{
if((from_value != "")&&(to_value != ""))
{
if((isValidDate(from_value))&&(isValidDate(to_value)))
{
if(from_value < to_value)
{
args.IsValid = false;
sender.errormessage = "To date must be greater than or equal to the from date";
}
}
else
{
args.IsValid = false;
sender.errormessage = "Please enter valid dates in both the fields";
if(behaviorId != null)
{
openCollapsiblePanel(behaviorId);
}
}
}
else
{
args.IsValid = false;
sender.errormessage = "Please make sure you enter both the values";
if(behaviorId != null)
{
openCollapsiblePanel(behaviorId);
}
}
}
}
function isValidDate(val)
{
var format = 'dd/MM/yyyy'
var regexp = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
if (!regexp.test(val))
{
return false;
}
else
{
try
{
$.datepicker.parseDate(format,val,null);
return true;
}
catch(Error)
{
return false;
}
}
}
Your code is pretty repetitive, you can shorten a lot of it.
Also note that the regex check is entirely unnecessary, since $.datepicker.parseDate() won't accept anything invalid anyway.
function checkBothDates(sender, args) {
var from = parseDate( $(sender.From).val() ),
to = parseDate( $(sender.To).val() );
args.IsValid = false;
if (from == "" && to == "" || from && to && from <= to) {
args.IsValid = true;
} else if (from == null || to == null) {
sender.errormessage = "Please enter valid dates in both the fields";
} else if (from > to) {
sender.errormessage = "To date must be greater than or equal to the from date";
} else {
sender.errormessage = "Please make sure you enter both the values";
}
if (!args.IsValid && sender.behavior) {
openCollapsiblePanel(sender.behavior);
}
}
function parseDate(val) {
if (val == "") return "";
try {
return $.datepicker.parseDate('dd/MM/yyyy', val);
} catch (ex) {
return null;
}
}
There is a problem in your code aroun the 19th line. You wrote:
if(from_value < to_value) {
args.IsValid = false;
sender.errormessage = "To date must be greater than or equal to the from date";
}
But you definitely want that from_value is smaller then to_value. Fix it!

Categories