Angular JS 24hr time Input Validation - javascript

I using HTML5 with AngularJS,i have an input field where i am allowing users to enter the time in 24 hour format eg:(13:00) . when the user clicks on submit button i need to validate whether the input is entered in the above format . If not i would like to throw an error message saying its invalid time . The problem is when i try to do it using normal javascript on ng-click its not working . please suggest me a good way of doing it . How should i do i angular way .
this is my javascript code
function validateTime(obj)
{
var timeValue = obj.value;
if(timeValue == "" || timeValue.indexOf(":")<0)
{
alert("Invalid Time format");
return false;
}
else
{
var sHours = timeValue.split(':')[0];
var sMinutes = timeValue.split(':')[1];
if(sHours == "" || isNaN(sHours) || parseInt(sHours)>23)
{
alert("Invalid Time format");
return false;
}
else if(parseInt(sHours) == 0)
sHours = "00";
else if (sHours <10)
sHours = "0"+sHours;
if(sMinutes == "" || isNaN(sMinutes) || parseInt(sMinutes)>59)
{
alert("Invalid Time format");
return false;
}
else if(parseInt(sMinutes) == 0)
sMinutes = "00";
else if (sMinutes <10)
sMinutes = "0"+sMinutes;
obj.value = sHours + ":" + sMinutes;
}
return true;
}

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 validation not working on android device 4.4.4

I am developing phone gap application.In application I used html textbox for inputing date from user and I wrote date validation code using javascript. When I run the application on emulator date validation is working fine. But when I run the application on android device date validation not working.
Device:Micromax AQ4501
Device Version:Android Kitkat 4.4.4
Emulator:Android 4.4.2
Code:
var isShift=false;
var seperator = "/";
function DateFormat(txt , keyCode)
{
if(keyCode==16)
isShift = true;
//Validate that its Numeric
if(((keyCode >= 48 && keyCode <= 57) || keyCode == 8 ||
keyCode <= 37 || keyCode <= 39 ||
(keyCode >= 96 && keyCode <= 105)) && isShift == false)
{
if ((txt.value.length == 2 || txt.value.length==5) && keyCode !=
8)
{
txt.value += seperator;
}
return true;
}
else
{
return false;
}
}
function ValidateDate(txt,keyCode)
{
//alert("validate function called");
if(keyCode==16)
isShift = false;
var val=txt.value;
if(val.length == 10)
{
var splits = val.split("/");
var dt = new Date(splits[1] + "/" + splits[0] + "/" + splits[2]);
alert(dt);
//Validation for Dates
if(dt.getDate()==splits[0] && dt.getMonth()+1==splits[1]
&& dt.getFullYear()==splits[2])
{
//do nothing
}
else
{
return;
}
//Range Validation
if(txt.id.indexOf("txtRange") != -1)
RangeValidation(dt);
//BirthDate Validation
if(txt.id.indexOf("txtBirthDate") != -1)
BirthDateValidation(dt)
}
else if(val.length < 10)
{    //do nothing
}
}
function BirthDateValidation(dt)
{
var dtToday = new Date();
var pastDate = new Date(Date.parse(dtToday.getMonth()+"/"+
dtToday.getDate()+"/"+parseInt(dtToday.getFullYear()-100)));
if (dt<pastDate || dt>=dtToday)
{
alert("Invalid BirthDate");
}
else
{
alert("Valid BirthDate");
}
}
function RangeValidation(dt)
{
var startrange = new Date(Date.parse("01/01/1900"));
var endrange = new Date(Date.parse("12/31/2099"));
//var lblmesg = document.getElementById("<%=lblMesg.ClientID%>") ;
if (dt<startrange || dt>endrange)
{
alert("Date should be between 01/01/1900 and 31/12/2099");
}
}

Javascript Focus

I am using this script for i need a focus on every alert.i tried many ways but it is not working.
script:
function validateTime(obj) {
var timeValue = obj.value;
if(timeValue == "" || timeValue.indexOf(":") < 0) {
alert("Invalid Time format");
obj.value = "";
return false;
} else {
var sHours = timeValue.split(':')[0];
var sMinutes = timeValue.split(':')[1];
if(sHours == "" || isNaN(sHours) || parseInt(sHours) > 23) {
alert("Invalid Time format");
obj.value = "";
return false;
} else if(parseInt(sHours) == 0) sHours = "00";
else if(sHours < 10) sHours = "0" + sHours;
if(sMinutes == "" || isNaN(sMinutes) || parseInt(sMinutes) > 59) {
alert("Invalid Time format");
return false;
} else if(parseInt(sMinutes) == 0) sMinutes = "00";
else if(sMinutes < 10) sMinutes = "0" + sMinutes;
obj.value = sHours + ":" + sMinutes;
}
return true;
}
aspx:
<asp:TextBox ID="lblMonday" CssClass="lblMonday" runat="server" Width="55px" onchange="validateTime(this);"></asp:TextBox>
You just need to call obj.focus() after each alert. As in:
alert("Invalid Time format");
obj.value = "";
obj.focus();
You probably haven't called the focus() method on the text element. Also it is not a good practice to mix presentation and functionality. You must not use the onchange attribute in the HTML markup.
document.getElementById("lblMonday").onchange = function() {
if(!validateTime(this)) { this.focus(); }
}
You can remove much of the duplication by calling alert() and resetting the field's value in a single place, as in
document.getElementById("lblMonday").onchange = function() {
if(!validateTime(this)) {
this.focus();
this.value="";
alert("Invalid time format");
}
else {
//Do something else
}
}

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