regex to match date in a string - javascript

i try to allow only number 01 (1) to 53) after / and after 2000 and over....
so i create a regex but it don't seem to work
on this web page: http://www.regular-expressions.info/javascriptexample.html
i tried it and it work well... but when i test in on a web page
10/2010 , 23/2000
function isValidDate(value, format){
var isValid = true;
try{
var inputVal = $(this).val();
var dateWWYYYYRegex = '^(0[1-9]|[1234][0-9]|5[0-3])[-/.](20)\d\d$';
var reg=new RegExp(dateWWYYYYRegex);
if(!reg.test(value)){
isValid = false;
alert("Invalid");
}
}
catch(error){
isValid = false;
}
return isValid;
}

You have to escape backslashes if you're going to make a regex from a string. I'd just use regex syntax, since it's a constant anyway:
var reg = /^(0[1-9]|[1234][0-9]|5[0-3])[-/.](20)\d\d$/;
The regular expression doesn't really make any sense, however. It's not clear what it should be, because your description is also confusing.
edit — OK now that I see what you're doing, that regex should work, I guess.

Why use regex for this task? I think it's the wrong tool for this task
Simply split the string by the slash delimiter, and then use numerical functions to check if the values are in the range you want.
function isValidWeekOfYear(value){
var bits = value.split('/');
if(parseInt(bits[1]) < 2000) { return false; } /* probably also want to do a maximum value here? */
if(parseInt(bits[0]) < 1 || parseInt(bits[0]) > 53) { return false; }
return true;
}
It might need a bit more validation than that, but that should be a good starting point for you. Much less processing overhead than a regex just to parse a couple of numbers (and easier to read too).

Related

Regex for password, I am getting error

Regex left for
(Must not contain sequences of letters or numbers) and
(Do not repeat a number or letter more than 5 times).
I know its repeated question but I was not able to find combination of my requirement. When I tried to combine I was getting errors
Other than that I was able to do it
I was trying for not repeating more than 5 but this one is not working
`^(?=.*?[a-zA-Z])(?=.*?[0-9])((.)\2{0,4}(?!\2)).{6,15}$`
Partially working one is ^(?=.*?[a-zA-Z])(?=.*?[0-9]).{6,15}$ I need to both conditions in it.
As suggested, have a RegExp that checks the string for allowed characters first. That should be simple and easy to read.
Then if that passes, split the string into an array of each character, loop over it, and check counts for each character. Something like Lodash would help with the latter, but you could write it in plain javascript too.
if (/^[a-zA-Z][0-9]$/.test(password)) {
const chars = password.split('');
const counts = {};
chars.forEach(char => {
if (counts[char] && counts[char] > 5) {
isValid = false;
} else {
counts[char] = counts[char] ? counts[char] + 1 : 1;
}
});
return isValid;
}

Why won't my JS code filter out this "_" element from string?

I'm working on the FreeCodeCamp Front End Development Certification and have arrived at the Basic Algorithm Scripting part. One of the exercises is to write a code that tests for palindromes. I understand everything (well almost) that is to be done, have quickly written my code but cannot understand why it doesn't give the correct result for strings containting underscores (_). Here is my code:
function palindrome(str) {
str = str.replace(/\W/g,'');
if ((((str.toLowerCase()).split("")).reverse()).join("") == str.toLowerCase()){
return true;
}
else {
return false;
}
}
palindrome("_eye");
The \W in regex is basically a short way to write "every chat that is not any of the [a-zA-Z0-9_] chars".
As you you can see - digits and underscore are also part of that.
If you to remove every char that is not [a-zA-Z] you can use /[^a-zA-Z]/ instead:
function palindrome(str) {
str = str.replace(/[^a-zA-Z]/g,'');
if ((((str.toLowerCase()).split("")).reverse()).join("") == str.toLowerCase()){
return true;
}
else {
return false;
}
}
console.log(palindrome("_eye"))
Just change yout regex to str.replace(/[\W_]/g,'');

Javascript issue: regex issue finding matches

I'm sure it's simple and I just don't see it. I've been searching for examples and as short and simple as they are, I can't seem to find my issue.
I wish to validate a Postal Code field and use the Canadian Postal code format. I found an expression I wish to use and it looks like the following:
var validZIP={
"US":"^\d{5}([\-]?\d{4})?$",
"UK":"^(GIR|[A-Z]\d[A-Z\d]??|[A-Z]{2}\d[A-Z\d]??)[ ]??(\d[A-Z]{2})$",
"CA":"^([ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ])\ {0,1}(\d[ABCEGHJKLMNPRSTVWXYZ]\d)$"
}
Please note the CA which stands for CAnada in this case.
My onChange function calls the following method (onchange class checkValidPostal(this) from the input):
function checkValidPostal(input)
{
var re = new RegExp(validZIP["CA"]);
var value = input.value.toUpperCase();
if (value.match(re))
{
input.value = value;
return true;
}
input.value = "";
return false;
}
I have checked the RegEx line using:
http://www.regular-expressions.info/javascriptexample.html and it works great on that page, but for some reason I can't get it to work on mine!
Please help.
There's a problem : as you use strings instead of regex literals, you lack some escapements.
Besides, you probably want to use test instead of match.
You could fix that like this :
var validZIP={
"US": /^\d{5}([\-]?\d{4})?$/,
"UK": /^(GIR|[A-Z]\d[A-Z\d]??|[A-Z]{2}\d[A-Z\d]??)[ ]??(\d[A-Z]{2})$/,
"CA": /^([ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ])\ {0,1}(\d[ABCEGHJKLMNPRSTVWXYZ]\d)$/
}
function checkValidPostal(input) {
var re = validZIP["CA"];
var value = input.value.toUpperCase();
if (re.test(value)) {
input.value = value;
return true;
}
input.value = "";
return false;
}
Inside a string you'll need to double-escape your backslashes, else they are already escaped by the string and there are no backslashes remaining by the time the RegEx constructor gets the string.
Try putting pattern instead of strings in validZIP:
var validZIP={
"US":/^\d{5}([\-]?\d{4})?$/,
"UK":/^(GIR|[A-Z]\d[A-Z\d]??|[A-Z]{2}\d[A-Z\d]??)[ ]??(\d[A-Z]{2})$/,
"CA":/^([ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ])\ {0,1}(\d[ABCEGHJKLMNPRSTVWXYZ]\d)$/
}

Javascript IndexOf with integers in string not working

Can anyone tell me why does this not work for integers but works for characters? I really hate reg expressions since they are cryptic but will if I have too. Also I want to include the "-()" as well in the valid characters.
String.prototype.Contains = function (str) {
return this.indexOf(str) != -1;
};
var validChars = '0123456789';
var str = $("#textbox1").val().toString();
if (str.Contains(validChars)) {
alert("found");
} else {
alert("not found");
}
Review
String.prototype.Contains = function (str) {
return this.indexOf(str) != -1;
};
This String "method" returns true if str is contained within itself, e.g. 'hello world'.indexOf('world') != -1would returntrue`.
var validChars = '0123456789';
var str = $("#textbox1").val().toString();
The value of $('#textbox1').val() is already a string, so the .toString() isn't necessary here.
if (str.Contains(validChars)) {
alert("found");
} else {
alert("not found");
}
This is where it goes wrong; effectively, this executes '1234'.indexOf('0123456789') != -1; it will almost always return false unless you have a huge number like 10123456789.
What you could have done is test each character in str whether they're contained inside '0123456789', e.g. '0123456789'.indexOf(c) != -1 where c is a character in str. It can be done a lot easier though.
Solution
I know you don't like regular expressions, but they're pretty useful in these cases:
if ($("#textbox1").val().match(/^[0-9()]+$/)) {
alert("valid");
} else {
alert("not valid");
}
Explanation
[0-9()] is a character class, comprising the range 0-9 which is short for 0123456789 and the parentheses ().
[0-9()]+ matches at least one character that matches the above character class.
^[0-9()]+$ matches strings for which ALL characters match the character class; ^ and $ match the beginning and end of the string, respectively.
In the end, the whole expression is padded on both sides with /, which is the regular expression delimiter. It's short for new RegExp('^[0-9()]+$').
Assuming you are looking for a function to validate your input, considering a validChars parameter:
String.prototype.validate = function (validChars) {
var mychar;
for(var i=0; i < this.length; i++) {
if(validChars.indexOf(this[i]) == -1) { // Loop through all characters of your string.
return false; // Return false if the current character is not found in 'validChars' string.
}
}
return true;
};
var validChars = '0123456789';
var str = $("#textbox1").val().toString();
if (str.validate(validChars)) {
alert("Only valid characters were found! String validates!");
} else {
alert("Invalid Char found! String doesn't validate.");
}
However, This is quite a load of code for a string validation. I'd recommend looking into regexes, instead. (Jack's got a nice answer up here)
You are passing the entire list of validChars to indexOf(). You need to loop through the characters and check them one-by-one.
Demo
String.prototype.Contains = function (str) {
var mychar;
for(var i=0; i<str.length; i++)
{
mychar = this.substr(i, 1);
if(str.indexOf(mychar) == -1)
{
return false;
}
}
return this.length > 0;
};
To use this on integers, you can convert the integer to a string with String(), like this:
var myint = 33; // define integer
var strTest = String(myint); // convert to string
console.log(strTest.Contains("0123456789")); // validate against chars
I'm only guessing, but it looks like you are trying to check a phone number. One of the simple ways to change your function is to check string value with RegExp.
String.prototype.Contains = function(str) {
var reg = new RegExp("^[" + str +"]+$");
return reg.test(this);
};
But it does not check the sequence of symbols in string.
Checking phone number is more complicated, so RegExp is a good way to do this (even if you do not like it). It can look like:
String.prototype.ContainsPhone = function() {
var reg = new RegExp("^\\([0-9]{3}\\)[0-9]{3}-[0-9]{2}-[0-9]{2}$");
return reg.test(this);
};
This variant will check phones like "(123)456-78-90". It not only checks for a list of characters, but also checks their sequence in string.
Thank you all for your answers! Looks like I'll use regular expressions. I've tried all those solutions but really wanted to be able to pass in a string of validChars but instead I'll pass in a regex..
This works for words, letters, but not integers. I wanted to know why it doesn't work for integers. I wanted to be able to mimic the FilteredTextBoxExtender from the ajax control toolkit in MVC by using a custom Attribute on a textBox

JS: regex for numbers and spaces?

I'm using happyJS and use the regex underneath for phone validation
phone: function (val) {
return /^(?:[0-9]+$)/.test(val);
}
However this ONLY allows numbers. I want the user to be able to enter spaces as well like
238 238 45383
Any idea why return /^(?:[0-9 ]+$)/.test(val); is not doing the trick?
This is my suggested solution:
/^(?=.*\d)[\d ]+$/.test(val)
The (?=.*\d) asserts that there is at least one digit in the input. Otherwise, an input with only blank spaces can match.
Note that this doesn't put any constraint on the number of digits (only makes sure there are at least 1 digit), or where the space should appear in the input.
Try
phone: function (val) {
return /^(\s*[0-9]+\s*)+$/.test(val);
}
At least one number must be present for the above to succeed but please have a look at the
regex example here
Try
/^[\d ]*$/.test("238 238 45383")
console.log(/^[\d ]*$/.test("238 238 45383"));
You can try the below regex for checking numbers and spaces.
function isTextAndNumberSpaceOnly(text) {
var regex = /^[0-9 ]+$/;
if (regex.test(text)) {
return true;
} else {
return false;
}
}
Personally I use this code and it works properly:
function validateMobile(mob)
{
var re = /^09[0-9]{9}$/
if(mob.match(re))
return true;
else
return false;
}

Categories