compare only time vlaue from textbox using javascript? - 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;
}

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

I have a javascript that checks if my form is valid and it stops checking after a certain field

So I made a form in a table in html and the javascript code checks till the (creditcard.value.length) after that the code doesn't check anything
<script language="javascript" type="text/javascript">
function ispsd(form) {
var passed = false;
if (form.Fullname.value.length < 4) {
alert("Enter a valid Full Name");
} else if (form.Email.value.indexOf("#") == -1) {
alert("Enter a valid E-mail adress.")
} else if (form.Email.value.indexOf(".") == -1) {
alert("Enter a valid E-mail adress.")
} else if (form.Cardholder.value.length < 3) {
alert("Card Holder name is not Valid.")
} else if (form.Creditcard.value.length != 16) {
alert("Credit card number is not valid.")
} else if (isNan(form.Creditcard.value)) {
alert("Credit card number cannot contain letters.")
} else if (isNan(form.Zip.value)) {
alert("Enter a valid Postal Code.")
} else if ((form.Expyear.value) * 1 < 2021) {
alert("Credit Card has Expired.")
} else if (isNan(form.Expyear.value)) {
alert("Enter a valid Year.")
} else if (form.cvv.value.length != 3) {
alert("Enter a valid CVV.")
} else if (isNan(form.cvv.value)) {
alert("CVV cannot contain letters.")
} else {
passed = true;
}
return passed;
}
</script>
and the thing is when I moved the (form.Expyear.value) * 1 < 2021) above the (form.Creditcard.value.length != 16) the validation worked and when I tried to add all the (else if) above the Credit card check it didn't work
don't know what's the problem
if anyone can help I would be thankful
You can always use console.log() to check what the variable has
function validate(form) {
if (form.Fullname.value.length < 4) {
alert('Enter a valid Full Name');
document.form.Fullname.focus();
return false;
}
if (form.Email.value.indexOf('#') == -1 || form.Email.value.indexOf('.') == -1) {
alert('Enter a valid E-mail adress.');
document.form.Email.focus();
return false;
}
if (form.Cardholder.value.length < 3) {
alert('Card Holder name is not Valid.');
document.form.Cardholder.focus();
return false;
}
console.log(form.Creditcard.value);
if (isNaN(form.Creditcard.value)) {
alert('Credit card number cannot contain letters.');
document.form.Creditcard.focus();
return false;
}
if (form.Creditcard.value.length < 16) {
alert('Credit card number is not valid.');
document.form.Creditcard.focus();
return false;
}
if (isNaN(form.Zip.value)) {
alert('Enter a valid Full Name');
document.form.Zip.focus();
return false;
}
if (isNaN(form.Expyear.value)) {
alert('Enter a valid Year.');
document.form.Expyear.focus();
return false;
}
if (Number(form.Expyear.value) < 2021) {
alert('Enter a valid Year.');
document.form.Expyear.focus();
return false;
}
if (isNaN(form.cvv.value)) {
alert('CVV cannot contain letters.');
document.form.cvv.focus();
return false;
}
if (form.cvv.value.length != 3) {
alert('Enter a valid Year.');
document.form.cvv.focus();
return false;
}
return true;
}
Try to remove the * 1, not sure what's the purpose there
isNaN, and not isNan
I would also handle it differently, what you need is to return true if they pass, rather than identify errors, for example, the demo here below. For example, it will pass your test if you have more than 16 numbers since you're checking x !== 16
function validate() {
var x, text;
// Get the value of the input field with id="numb"
x = document.getElementById("cc").value;
// If x is Not a Number or less than one or greater than 10
if (!isNaN(x) && x.length > 3 && x.length <= 16) {
text = "Input OK";
} else {
text = "Input not valid";
}
document.getElementById("error").innerHTML = text;
}
<p>Please write only numbers, from 4 to 16 maximum characters</p>
<input type="number" id="cc"/><br>
<span id="error"></span><br>
<input type="submit" onclick="validate()" />
Last but not least, this is so verbose and difficult to maintain, I strongly suggest using a library like this one https://www.npmjs.com/package/validator to handle validation, or even jQuery has .validate() useful function for beginner.

Stop page from reloading after alert in if statement

I am facing this issue here.After i click alert in if statement the page should not reload.I have tried everything here
return false;
event.preventDefault();
3.window.stop();//This is working but for other conditions where page should reload it is not getting loaded.
4.return;
So as you can see in if statement when sel.options[sel.selectedIndex].text!="Meeting Room Name the alert is showed after i click ok the page should not reload.I have tried each and every solution and referred many posts.
$("input[id$='diidIOSaveItem']").click(function(ev)
{
var startDate = $("input[id$='DateTimeField_DateTimeFieldDate']")[0].value;
var EndDate = $("input[id$='DateTimeField_DateTimeFieldDate']")[1].value;
var startH = $("select[id$='DateTimeFieldDateHours']")[0].value;
var endH = $("select[id$='DateTimeFieldDateHours']")[1].value;
var startM = $("select[id$='DateTimeFieldDateMinutes']")[0].value;
var endM = $("select[id$='DateTimeFieldDateMinutes']")[1].value;
var meetingTitle = $("input[id$='TextField']").val();
if(meetingTitle == "" || meetingTitle == "undefined")
{
alert("You have not entered a Meeting Title.");
$("input[id$='TextField']").focus();
}
if(startDate != EndDate)
{
alert("Each Meeting must start and finish on the same day.");
$("input[id$='DateTimeField_DateTimeFieldDate']").focus();
}
if(startH == endH && startM == endM)
{
alert("End Hour/Minutes and Start Hour/Minutes can not be same.");
$("select[id$='DateTimeFieldDateHours']").focus();
}
if(startH > endH )
{
alert("End Hour must be greator than or equal to Start Hour.");
$("select[id$='DateTimeFieldDateHours']").focus();
}
if(sel.options[sel.selectedIndex].text =="Meeting Room Name") //if no meeeting room or more then one meeting room is selected.
{
alert("Please select One Meeting Room");
//$("input[id$='DateTimeField_DateTimeFieldDate']").focus();
// ev.preventDefault();
return false;
}
if(sel.options[sel.selectedIndex].text!="Meeting Room Name")
{
//if without any room selection clicking on save.
if(selectedValue.length == 1)
{
if(selectedValue.options[selectedValue.selectedIndex] != "undefined")
{
selectedValueres= selectedValue.options[selectedValue.selectedIndex].text;
//sel.options[sel.selectedIndex].text= selectedValueres ;
if((selectedValueres != "")&&(selectedValue.length == 1))
{console.log("selectedValueres "+ selectedValueres);
if (!PreSaveItem())return false;
WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$ctl40$g_2543e208_7ccd_45b5_9c3c_703dd452cee7$savebutton2$ctl00$diidIOSaveItem", "", true, "", "", false, true));
}
else //if no meeeting room or more then one meeting room is selected.
{
//alert("Please refresh page and click on new booking your booking is conflict with other user.");
GipAddSelectedItemsModified(ctl00_ctl40_g_2543e208_7ccd_45b5_9c3c_703dd452cee7_ff41_ctl00_ctl00_MultiLookupPicker_m);
selectedValueres= $("tr.tobehide select[id$='SelectResult']").find(":selected").text();
$("<option value='new value' selected='selected'>"+selectedValueres+"</option>").prependTo($("tr.tobehide select[id$='SelectCandidate']"));
}
//sel.options[sel.selectedIndex].text= selectedValueres ;
}
else //if no meeeting room or more then one meeting room is selected.
{
alert("Please select One Meeting Room");
return;
}
}
}
return false;
});

Javascript handling data in a gridview

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();
}

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