I am new to javascript. I am fixing bug programmed by others. I see validation code in javascript as:
function validateTime(str) {
var pattern = new RegExp(/^(([0-9])|([0-1][0-9])|([2][0-3])):(([0-9])|([0-5][0-9]))$/);
if (pattern.test(str)) {
return true;
}
else {
return false;
}
}
But it does't validate time:- 22-05-2015
How can it be done?
You can use the Date object's parse method to verify a date string.
You can then check if the value of Date.parse(str) is equal to "Invalid Date" to see if it is malformed. No need for regex at all.
Your regex validates time, not date. To check against date in your format, use this:
var pattern = new RegExp(/^(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[012])-(19|20)\d\d$/);
You can check this pattern here:
https://regex101.com/r/kB5nV2/1
function parseDate(str) {
var m = str.match(/^(\d{1,2})-(\d{1,2})-(\d{4})$/);
return (m) ? new Date(m[3], m[2]-1, m[1]) : null;
}
The function validateTime(str) used in your code is for time validation. Try the parseDate(str) for date validation.
Related
I've tested the three of the regex's on http://www.regexpal.com/ and they are what I need, but when doing a regex test 2 of them return false (BTC and CAD) and only the Bitcoin address seems to work (you may test with this wallet below).
13dHNxtbckAFM4PzdBqWgymFJmcv3Yzi32
https://jsfiddle.net/ps2fj1ff/1
(all the relevant code is in the html section)
var regWallet = new RegExp("^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$");
var regBTC = new RegExp("^\d*\.\d*$");
var regCAD = new RegExp("^\d+(\.(\d{2}))?$");
$('#button1').on('click', function() {
var btcCheck = $('#amount_btc').val();
if (regBTC.test(btcCheck)) {
} else {
alert("Invalid BTC value!");
}
var cadCheck = $('#amount_cad').val();
if (regCAD.test(cadCheck)) {
} else {
alert("Invalid CAD value!");
}
var walletCheck = $('#wallet').val();
if (regWallet.test(walletCheck)) {
} else {
alert("Invalid Bitcoin address, please make sure you've entered a valid address!");
}
});
The reason is that in var regBTC = new RegExp("^\d*\.\d*$"); the \ is used to escape the character so if you console.log(regBTC) you will see it as ^d*.d*$.
To prevent this you will have to double escape it: var regBTC = new RegExp("^\\d*\\.\\d*$");
Or better yet use / instead: var regBTC = /^\d*\.\d*$/;
The same goes for the other regex too.
(I initially thought single quote would work too, but apparently not in javascript)
Use this instead:
var regBTC = /^\d*\.\d*$/;
var regCAD = /^\d+(\.(\d{2}))$/;
It's cleaner and more readable as most editors will give you regexp syntax highlighting in this format.
There really isn't any good reason to use new RegExp which forces you to write the expression as a string, which forces you to use confusing escapes, when there is a proper regular expression syntax built into JavaScript.
Here are two angular2 custom validations that I wrote, the first one validateAge works, but the second one validateDob does not ... the difference is the validateAge uses the component that I am on and is a text based field, the second one needs to use a Date Entry field and find the difference between today's date and the birthdate to find the actual age and then measure it against the age field. but something is not right ... any ideas
function validateAge(control: FormControl): { [s: string]: boolean } {
if (parseInt(control.value) <= 0) {
return {invalidAge: true};
}
}
function validateDob(control: FormControl): {[s:string]: boolean}{
var today = new Date();
var calcAge = today - control.value;
if (calcAge != parseInt([{age}]) ){
return {invalidDate: true}
}
}
The issue you have here is that your control.value is not a Date object, but rather the string representation.
var today = new Date();
Difference in milliseconds between the current timestamp and the entered value
var diff = today - new Date(control.value);
divide by ms per year and take the floor
var calcAge = Math.floor(diff/ (1000*60*60*24*365)));
Now do whatever comparison you need against the appropriate value. You didn't show us what your age object is so I don't actually know what comparison you're looking for.
if (calcAge < someAgeThreshold) ){
return {invalidDate: true}
} else {
return null;
}
Also note that with custom validation the validator returns no error when you return null and anything with a value is considered to have an error.
Im trying to implement a validation for an input field in IBM BPM.
Im not really familiar with java script but I try to get method that returns
ture if a string contains any numbers.
awdadw = valid
awdawd2d = invalid
I tried this method:
function hasNumbers(t)
{
var pattern=new RegExp("^[A-Za-z]+$");
return pattern.test(t); // true if string. Returns false for numbers
}
When I try this function, it says that method / variable RegExp is unknown. Since it is rather basci stuff I hope to get some sources where this topic is explained.
You can use this:
function validate(){
var re = /^[A-Za-z]+$/;
if(re.test(document.getElementById("inputID").value))
alert('Valid Name.');
else
alert('Invalid Name.');
}
Based on adre3wap this worked for me:
function validate(t){
var re = /^[A-Za-z]+$/;
if(re.test(t))
return false;
else
return true;
}
I am developing a application. In this application have a input field. where the user can input the dates by different formats like
ddmmyy, ddmmyyyy, dd-mm-yy, mm-dd-yy
And I need to verify the date whether that valid or not. I can able to validate this way:
YYYY-MM-DD using:
var myDate = new Date("1987-08-06") // it returns me the date while this valid.
But I can't able to validate with other formats. how can i validate that?
example:
var myDate = new Date("08-06-1987")..etc?
I developed my app using jQuery. I am looking some solution without using a plug-in. since i used no.of plugins already.
thanks in advance!
I would do it with regular expressions. You could define a regexp pattern for each of your formats. Then you can test if the String from the input field matches any of the pattern.
Somthing like this:
var regExpDDMMYY = /[0-9]{2}[0-1][0-9][0-9]{2}/g;
var regExpddmmyyyy = ...;
...
...
if (regExpDDMMYY.test(yourInputStringFromDateField)) {
// handleDateAs DDMMYY
} else if (regExpddmmyyyy .test(yourInputStringFromDateField)) {
...
} else {
throw new YourException();
}
You can find an example here:
http://www.w3schools.com/js/js_regexp.asp
Unfortunately, there's no "parseExact" in native JS, that would also be crossbrowser. So you either need to use Date.js library or write some converter.
For this task i'd recommend you to use "Chain of responsibility" pattern
function DateTimeParser() {
this.parse = function (input) {
for (var key in Parsers) {
var result = Parsers[key].parse(input);
if (result !== null)
return result;
}
return null;
};
this.parseExact = function (input, format) {
var parser = Parsers[format];
return parser ? parser.parse(input) : null;
};
var ConcreteDateTimeParser = function (expression, parser) {
this.parse = function (input) {
if (!input.match(expression))
return null;
var result = parser(input);
return isNaN(result.getDate()) ? null : result;
};
};
var Parsers = {
"dd-mm-yyyy": new ConcreteDateTimeParser(/\d{2}\-\d{2}\-\d{4}/, function (input) {
var dd = parseInt(input.slice(0, 2)),
mm = parseInt(input.slice(3, 5)),
yyyy = parseInt(input.slice(-4));
return new Date(yyyy, mm, dd);
}),
"ddmmyyyy": new ConcreteDateTimeParser(/\d{8}/, function (input) {
var dd = parseInt(input.slice(0, 2)),
mm = parseInt(input.slice(2, 4)),
yyyy = parseInt(input.slice(-4));
return new Date(yyyy, mm, dd);
})
};
};
var instance = new DateTimeParser();
instance.parse('22122012');
instance.parseExact('22122012', 'ddmmyyyy');
instance.parseExact('22122012', 'dd-mm-yyyy'); // null
From this you can extend your Parsers lib with additional parsers. You also can use different sets of parsers by passing them into DateTimeParser as a constructor argument. My code is pretty trivial, for i didn't want to write it mega-deep, just wanted to show the way =)
I've just written this regular expression in javaScript however it doesn't seem to work, here's my function:
function isGoodDate(dt){
var reGoodDate = new RegExp("/^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2})*$/");
return reGoodDate.test(dt);
}
and this is how I call it in my form validation
if(!isGoodDate(userInput[1].value)){
alert("date not in correct format of MM/dd/YYYY");
return false;
}
now I want it to return MM/DD/YYYY however if I put a valid date in it raises the alert? Any ideas anyone?
Attention, before you copy+paste: The question contains some syntactic errors in its regex. This answer is correcting the syntax. It is not claiming to be the best regex for date/time parsing.
Try this:
function isGoodDate(dt){
var reGoodDate = /^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2})*$/;
return reGoodDate.test(dt);
}
You either declare a regular expression with:
new RegExp("^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2})*$")
Or:
/^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2})*$/
Notice the /
Maybe because you are declaring the isGoodDate() function, and then you are calling the isCorrectDate() function?
Try:
function isGoodDate(dt){
var reGoodDate = /^(?:(0[1-9]|1[012])[\/.](0[1-9]|[12][0-9]|3[01])[\/.](19|20)[0-9]{2})$/;
return reGoodDate.test(dt);
}
Works like a charm, test it here.
Notice, this regex will validate dates from 01/01/1900 through 31/12/2099. If you want to change the year boundaries, change these numbers (19|20) on the last regex block. E.g. If you want the year ranges to be from 01/01/1800 through 31/12/2099, just change it to (18|20).
I agree with #KooiInc, but it is not enough to test for NaN
function isGoodDate(dt){
var dts = dt.split('/').reverse()
,dateTest = new Date(dts.join('/'));
return !isNaN(dateTest) &&
dateTest.getFullYear()===parseInt(dts[0],10) &&
dateTest.getMonth()===(parseInt(dts[1],10)-1) &&
dateTest.getDate()===parseInt(dts[2],10)
}
which will handle 29/2/2001 and 31/4/2011
For this script to handle US dates do
function isGoodDate(dt){
var dts = dt.split('/')
,dateTest = new Date(dt);
return !isNaN(dateTest) &&
dateTest.getFullYear()===parseInt(dts[2],10) &&
dateTest.getMonth()===(parseInt(dts[0],10)-1) &&
dateTest.getDate()===parseInt(dts[1],10)
}
Add this in your code, it working perfectly fine it here.
click here http://jsfiddle.net/Shef/5Sfq6/
function isGoodDate(dt){
var reGoodDate = /^(?:(0[1-9]|1[012])[\/.](0[1-9]|[12][0-9]|3[01])[\/.](19|20)[0-9]{2})$/;
return reGoodDate.test(dt);
}
I don't think you need a regular expression for this. Try this:
function isGoodDate(dt){
var dts = dt.split('/').reverse()
,dateTest = new Date(dts.join('/'));
return isNaN(dateTest) ? false : true;
}
//explained
var dts = dt.split('/').reverse()
// ^ split input and reverse the result
// ('01/11/2010' becomes [2010,11,01]
// this way you can make a 'universal'
// datestring out of it
,dateTest = new Date(dts.join('/'));
// ^ try converting to a date from the
// array just produced, joined by '/'
return isNaN(dateTest) ? false : true;
// ^ if the date is invalid, it returns NaN
// so, if that's the case, return false
Validate (DD-MM-YYYY) format :)
function isGoodDate(dt) {
var reGoodDate = /^(?:(0[1-9]|[12][0-9]|3[01])[\-.](0[1-9]|1[012])[\-.](19|20)[0-9]{2})$/;
return reGoodDate.test(dt);
}
Try the below code which accepts following date formats:
MM-DD-YYYY, MM-DD-YY, DD-MM-YYYY, DD-MM-YY, MM/DD/YYYY, MM/DD/YY,
DD/MM/YYYY, DD/MM/YY, MM\DD\YYYY, MM\DD\YY, DD\MM\YYYY, DD\MM\YY
function isGoodDate(dt) {
var reGoodDate = /(?:((0\d|[12]\d|3[01])|(0\d|1[012]))[\-|\\|\/]((0\d|1[012])|(0\d|[12]\d|3[01]))[\-|\\|\/](((19|20)\d{2})|\d\d))/;
return reGoodDate.test(dt);
}
(/^(0[1-9]|1[012])- /.- /.\d\d$/)
You can use this will work definitely and this is for MM/DD/YYYY