script to validate birthdate - javascript

I got this script
$("#SocialSecurityNumber").attr("placeholder","YYYY-MM-DD-XXXX").blur(function () {
var str = $('#SocialSecurityNumber').val();
var res = /^([1-2]\d{3})\-([0-1][1-9])\-([0-3][0-9])\-([0-9]{4})$/.exec(str);
var todays_date = new Date();
var birth_date = new Date(res[1], res[2], res[3]);
if (todays_date - birth_date > 565633905872) {
$("#btn-activation").removeAttr('disabled');
$("#SocialSecurityNumber").removeClass("input-validation-error");
} else {
$("#SocialSecurityNumber").attr("placeholder","Please enter date of birth as YYYY-MM-DD-XXXX").addClass("input-validation-error");
$("#btn-activation").attr("disabled", "disabled");
}
});
});
Which will validate age, from input #SocialSecurityNumber
However, when entering letters or other jibberish it doesnt validate at all and i get js error
Uncaught TypeError: Cannot read property '1' of null
Could somone help me with how i can add so this script also validates incorrect characters? (when regex is not matched)

As per my comment, in javascript, if the RegEx does not match, then the result is null.
Therefore you are attempting to index a null variable... which is why you're seeing the error.
You need to check for a null value, with something like this...
var res = /^([1-2]\d{3})\-([0-1][1-9])\-([0-3][0-9])\-([0-9]{4})$/.exec(str);
var todays_date = new Date();
var birth_date = null;
if (res != null) {
birth_date = new Date(res[1], res[2], res[3]);
}
if (birth_date == null || todays_date - birth_date > 565633905872) {
...
You'll need to sort out the exact logic yourself, but hopefully this gives you an idea of what is going wrong.

If there is no match, then res will be null. So one thing which you can do is:
if(res.length==3)
var birth_date = new Date(res[1], res[2], res[3]);
This confirms that you get only right number of matches.

Related

data range in TypeScript

Update:
I have several objects with start dates and end date
When inserting / modifying an object, the starting or ending date of the new object can not be included in the existing object.
Exist : 06/06/2018-----30/06/2018
can input:
04/06/2018-------05/06/2018
02/02/2018------ until less than date Start of which exists (05/06/2018)
or higher:
31/06/2018--------
can not get in :
04/06/2018-------07/06/2018 The end is already understood between the beginning and the end exists.
Or
07/06/2018---08/06/2018 because it is also included between the beginning and the end of the.
Code:
validateParamsDates(url, newConfig) {
return this.http.get<any>(url).pipe(map(param => {
let messageError = { message: "", showAlert: false };
let userStart = newConfig.startdatevalidity;
let userFinish = newConfig.enddatevalidity;
param[1]['params'].array.forEach(element => {
if(userStart > element.startdatevalidity && userFinish > element.enddatevalidity
|| userStart < element.startdatevalidity && userFinish < element.enddatevalidity
&& userStart > element.enddatevalidity
){
console.log('good');
}else{
console.log('=(');
}
});
return messageError ;
}));
}
You should first convert the strings to a Date object. Then you can compare dates and everything will work as it should ;)
So you would do something like:
const start2: Date = new Date(Object2.start);
const end1: Date = new Date(Object1.end);
if (start2 > end1) { console.log('good'); }
Please also note that in order for all of this to work in javascript, the dates should be defined in MM/DD/YYYY format not in DD/MM/YYYY
I would probably do something like this.
var start = new Date(Object2.start);
var end = new Date(Object1.end);
if(start.getTime() > end.getTime()) console.log('good');
Similar to this answer: Compare two dates with JavaScript

JavaScript RegExp returns false in every valid and invalid inputs

In my JSP page I have one table in that one of the column is for the Time shown in the HH:mm format and the datatype is String (I converted it from Date to String in server). Now I am applying the Inline table row editing using the Jquery plugin Tabledit.
While I edit the column and before sending to the server I am checking it with RegExp.
var inTime = [];
var timeRegEx = new RegExp("^([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-9]|0[0-9]|([1-5][0-9]))$");
inTime[1] = "14:34";
if (timeRegEx.test(inTime[1])) {
alert("Matched");
//return true;
} else {
alert("Not Mateched");
//return false;
}
I have checked the validity of the RegExp in some onilne resources and it is correct.
But in my case in every valid and invalid input it always goes to the else block.
And the more thing is that the while I print the value of the inTime[1] in alert. it gives the output like : 14%3A13
So I also replaced the : with %3A in RegExp but it also not worked.
So please tell me where I am going the wrong and what is the correct solution.
Edit:
Here : interpreted as %3A so may be this creates the problem.
Here inTime is array which get values from the table row.
var inTime = [];
var timeRegEx = new RegExp("^([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-9]|0[0-9]|([1-5][0-9]))$");
inTime[1] = "14%A334";
if (decodeURIComponent(timeRegEx.test(inTime[1]))) {
console.log("Matched");
//return true;
} else {
console.log("Not Mateched");
//return false;
}
Does this suite your needs?
var regex = /^[12]?\d:[012345]\d$/,
tests = [
'56:12',
'03:68',
'2:49',
'12:59',
'23:00',
'abcs',
'12,23'
];
tests.forEach(test => {
var isValid = regex.test(test);
console.log(`is ${test} valid: ${isValid}`);
});
As I mentioned in the question that the array variable inTime[1] get the data from the HTML table. It takes the: as the %3A, so it creates the problem to test the RegExp.
#Spanky give me hint to try decodeURIComponent(timeRegEx.test(inTime[1])) but it also not worked for me.
So I have slight modify his solution and applied the decodeURIComponent() to only inTime[1] Variable. This worked for me.
The solution code snippet is as follow:
var inTime = [];
var timeRegEx = new RegExp("^([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-9]|0[0-9]|([1-5][0-9]))$");
inTime[1] = "14%3A34";
if (timeRegEx.test(decodeURIComponent(inTime[1]))) {
console.log("Matched");
//return true;
} else {
console.log("Not Mateched");
//return false;
}

internet explorer match() not working correctly

I have a really weird error on IE.
I am using knockout custom validations. And one of my custom validations is to validate date.
function:
function isValidDate(txtDate) {
var currVal = txtDate;
if (currVal == '' || currVal == null)
return false;
//Declare Regex
var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
var dtArray = currVal.match(rxDatePattern); // is format OK?
if (dtArray == null)
return false;
/*continue of logic*/
}
This works great, when I run it first time. But then I do a redirect to server and return to the same page.
And the validation is called again at that point the problem begins.
I have a two snapshots of memory. They look identical to me. But there has to be some difference that I don't see or the match method is somehow broken.
The difference is not the dtArray == null that is the problem. You can try to run it in console. And it parse the dtArray correctly....
Both snapshot are on the same line ( if (dtArray == null) )
beforeRedirect:
afterRedirect:
Update. I solved my problem.
problem was that I was setting my observable property something like this:
var date = "1990-01-01T00:00:00";
var dob = new Date(date).toLocaleDateString();
masterModel.Dob(dob);
when I do it like this the match works fine now:
var date = "1990-01-01T00:00:00"
var dob = new Date(date);
var dobstring = dob.getDate() + "/" + (dob.getMonth()+1) + "/" + dob.getFullYear();
masterModel.Dob(dobstring);
if you want to see the difference run this on IE in console. My IE version is 11.0.9600
//because I am in UK my locale string is dd/MM/yyyy if you get different one this problem won't work for you!
var date = "1990-01-01T00:00:00"
var dob = new Date(date).toLocaleDateString();
var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
console.log(dob);
console.log(dob.match(rxDatePattern));
//vs
var date = "1990-01-01T00:00:00"
var dob = new Date(date);
var dobstring = dob.getDate() + "/" + (dob.getMonth()+1) + "/" + dob.getFullYear();
var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
console.log(dobstring);
console.log(dobstring.match(rxDatePattern));
Try simply checking for falsy values. The empty string, null and undefined are all falsy, there is no need to be more specific than that here.
function isValidDate(txtDate) {
if (!txtDate) return false;
var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
var dtArray = currVal.match(rxDatePattern);
if (!dtArray) return false;
/*continue of logic*/
}
That being said, I strongly suggest you use a date library (most prominently: moment.js) to do any date parsing, -calculation and -validation work. Don't roll your own regex when a fully functional and properly tested library has been written.
To think one step further, with knockout it's much easier to store an actual date object in an observable, so there is no need to parse any date strings at all, ever. You can also format it for display on screen any way you like, instead of limiting yourself/the user to a single format.
This way you would not need to do any date format validation at all. Either the observable contains a date - or not. For best effect use that together with a date picker widget (for example the one from knockout-jqueryui).
View model:
this.exampleDate = ko.observable();
View, assuming jQueryUI + knockout-jqueryui:
<input type="text" data-bind="datepicker: {
dateFormat: 'dd.mm.yyyy'
}, value: exampleDate" />

Local Storage Not Working As Expected

I built an app that I then built with PhoneGap Build.THe purpose is for it to run a code (starts at var Quotes once per day when the app is loaded).
When debugging why it wasn't working I noticed that in console I was getting back my message "Local storage didn't work". This means that my initial localstorage.getItem which is supposed to make sure the local storage can be read is returning null. So my code never gets executed.
What am I doing wrong?
function onDeviceReady() { //Do something when the app on device is loaded
var localVal = localStorage.getItem('DateOpened');
if(localVal == null){
console.log("LocalStorage did not work...")}
else
{
var tempd = new Date(); //Get today's date
var str = tempd.getDay() + tempd.getMonth() + tempd.getFullYear();
if(localVal.localeCompare(str) == -1)
{
var Quotes = [];
var ID = [];
var Tag = [];
var seen = [];
localStorage.setItem('DateOpened',str);
console.log("The App Ran, you can get a new fat tomorrow");
console.log("Todays date:" + str);
}
}
}
Initially, there will be no DateOpened item in local storage, so your code will follow the "did not work" branch, because getItem returns null for things that don't exist. That branch never sets anything in DateOpened, so...you'll always follow that branch.
The fix is not to skip over your code setting DateOpened if the device has local storage.
There's also an unrelated problem: Your var str = tempd.getDay() + tempd.getMonth() + tempd.getFullYear() does not produce a string, it produces a number formed by adding those values together, since they're all numbers. Your later localeCompare will fail because it's not a string. You also have the fields in the wrong order for a meaningful textual comparison — you need year first, then month, then day.
Here's a minimal fix, see comments:
function onDeviceReady() {
var tempd = new Date();
// Note that by adding strings in there, we end up with a string instead of adding.
// Note the order: Year first, then month, then day.
// Also, since we display it, we put separators in and add 1 to month (since Jan = 0).
var str = tempd.getFullYear() + "-" + (tempd.getMonth() + 1) + "-" + tempd.getDay();
var localVal = localStorage.getItem('DateOpened');
// If we have no stored value, or it's more than a day old by your definition,
// do your stuff and store the new date
if (localVal == null || localVal.localeCompare(str) < 0) {
var Quotes = [];
var ID = [];
var Tag = [];
var seen = [];
localStorage.setItem('DateOpened', str);
console.log("The App Ran, you can get a new fat tomorrow");
console.log("Todays date:" + str);
}
}
I think this is help full for you.
function onDeviceReady() { //Do something when the app on device is loaded
var localVal = localStorage.getItem('DateOpened');
if (typeof(DateOpened) == "undefined")
console.log("LocalStorage did not work...")}
else
{
var tempd = new Date(); //Get today's date
var str = tempd.getDay() + tempd.getMonth() + tempd.getFullYear();
var allRecords=JSON.parse(localStorage.getItem("DateOpened"));
if(allRecords == -1)
{
var Quotes = [];
var ID = [];
var Tag = [];
var seen = [];
localStorage.setItem('DateOpened',str);
console.log("The App Ran, you can get a new fat tomorrow");
console.log("Todays date:" + str);
}
}
}

compare start "Time" is less than the end "Time" in javascript

I have a value in two text fields which is already formatted as hh:mm, How can I compare the values of these two fields?
I am trying the following code:
function check_ToFromTime(toTime) {
if (getControl('txtStartTimeFrom').value == '00:00' && getControl(toTime).value == '00:00') { return true; }
var fromDate = new Date(getControl('txtStartTimeFrom').value);
var toDate = new Date(getControl('txtEndTimeTo').value);
var fromT = fromDate.getTime();
var toT = toDate.getTime();
return (toT >= fromT);
}
the if statement in the first line works, but the last statement
return (toT >= fromT);
does not work. it always returns false. where am i going wrong?
I wouldn't worry about converting these String objects to Date objects. Just split the string and compare:
var fromDate = "04:05";
var toDate = "04:04";
var fromTokens = fromDate.split(":");
var toTokens = toDate.split(":");
alert(fromTokens[0] < toTokens[0] || (fromTokens[0] == toTokens[0] && fromTokens[1] < toTokens[1]));
You could place this functionality in a nice function for re-usability:
function isAfter(fromDate, toDate){
var fromTokens = fromDate.split(":");
var toTokens = toDate.split(":");
return (fromTokens[0] < toTokens[0] || (fromTokens[0] == toTokens[0] && fromTokens[1] < toTokens[1]));
}
//Tests
alert(isAfter("04:04", "05:05"));
alert(isAfter("06:04", "05:05"));
alert(isAfter("05:05", "05:05"));
JS Fiddle: http://jsfiddle.net/X5v5F/
I'm not going to head down this route, since I think splitting the strings is sufficient, but if you were fixed on a date, I would recommend using Moment.js.
it will always print false because end time will always be greater than start time.U need to change the condition i.e. return (toT <= fromT);

Categories

Resources