What would the regular expression for this situation be? - javascript

I'm pretty new to JavaScript, and I've been trying to figure out the regular expression for this for a while.
I need to validate a user entry in the form of "mm/yy".
The 1st digit of the month must be 0 or 1. If it is 0 then the 2nd digit can be from 1 to 9. If it is 1, then the second digit can be 0 to 2. The year can be 14 to 19. It must have the slash.
This is what I have so far:
var reExp = /^0(?=\d)|1(?=1)|2\/14$/; //RegExp for expiry
if ($('expiry').value.search(reExp)==-1){
$('expiry').value = '';
$('expiryMsg').style.fontSize="10px";
$('expiryMsg').innerHTML = "Invalid Entry: Must be a valid expiry date.";
}
else {
$('expiryMsg').innerHTML = "*";
$('expiryMsg').style.fontSize="16px";
}
I want to do all the validation in one expression, is this possible?
Thanks!

You can use this pattern:
/^(?:0[1-9]|1[0-2])\/1[4-9]$/

Related

build a regex password 6 letters, 2 digits, and 1 punctuation

I am trying to build a regex that matches for the following
6 letters
digits
1 punctuation
my special characters from my backend to support js special_characters = "[~\!##\$%\^&\*\(\)_\+{}\":;,'\[\]]"
and a minimum of a length of at least 8 or longer.
my password javascript client-side is the following, but however, how can I build a regex with the following data?
if (password === '') {
addErrorTo('password', data['message']['password1']);
} else if(password){
addErrorTo('password', data['message']['password1']);
}else {
removeErrorFrom('password');
}
First check if password.length >= 6
Then I would do it like this:
Set up a letterCount, numCount, puncCount
Loop through the string and earch time you encounter a letter, increase the letterCount (letterCount++), each time you encounter a number increase numCount and so on.
Then validate your password using the counter variables.
This is a good approach because you can tell the user what went wrong. For example, if they only entered 1 number, you can see that from the numCount and tell them specifically that they need at least 2 numbers. You can't do that with just one Regex.
EDIT: Heres the code:
for (let i = 0; i < password.length; i++) {
const currentChar = password[i];
if (checkIfLetter(currentChar)) {
letterCount++;
}
if (checkIfNumber(currentChar)) {
numCount++;
}
if (checkIfPunc(currentChar)) {
puncCount++;
}
}
Then check if the numCount > 2 and so on. I would write the actual regexs but I don't know them myself. It should be pretty easy, just return true if the provided char is a letter for the first function, a number for the second one and so on.
You can use multiple REGEXes to check for each requirement.
let containsAtLeastSixChars = /(\w[^\w]*){6}/.test(password);
let containsAtLeastTwoDigits = /(\d[^\d]*){2}/.test(password);
let containsAtLeastOnePunct = new RegExp(special_characters).test(password);
let isAtLeast8Digits = password.length >= 8;
Then if any of these booleans are false, you can inform the user. A well designed site will show which one is wrong, and display what the user needs to fix.
^(?=.*[0-9]).{2}(?=.*[a-zA-Z]).{6}(?=.*[!##$%^&*(),.?":{}|<>]).{1}$
6Letters, 2digits, and 1 special character.

time limit on regular expression in format MM:SS:HH

I need to validate a user input for minutes, seconds, and hundredths in the format MM:SS:HH. However, user's input can not go over 10 minutes. I'm not sure how to limit that and still keep for example 01:01:01 valid.
/^[0-1][0-0]:[0-5][0-9]:[0-9][0-9]$/
This is the expression I had, but my example of 01:01:01 would not have worked.
Brief
I would definitely split the time string on : and then test each part. That's the simplest solution. Alternatively, you can do this relatively easily using regex.
Code
Method 1 - No regex
const str = ["00:00:00", "05:05:05", "10:00:00", "10:00:01", "10:59:59", "20:20:20"];
str.forEach(function(s) {
var a = s.split(":").map(Number);
if(a[0] < 10 || (a[0] === 10 && a[1] === 0 && a[2] === 0)) {
console.log(`Valid: ${s}`);
} else {
console.log(`Invalid: ${s}`);
}
});
Method 2 - Regex
const regex = /^(?:0\d(?::[0-5]\d){2}|10:00:00)$/;
const str = ["00:00:00", "05:05:05", "10:00:00", "10:00:01", "10:59:59", "20:20:20"];
str.forEach(function(s) {
if(regex.exec(s) !== null) {
console.log(`Valid: ${s}`);
} else {
console.log(`Invalid: ${s}`);
}
});
Explanation
I'll only explain the regex in Method 2 as the rest is fairly simple. If you need an explanation about any other parts, however, feel free to ask!
^ Assert position at the start of the line
(?:0\d(?::[0-5]\d){2}|10:00:00) Match either of the following
0\d(?::[0-5]\d){2} Match the following
0 Match this literally
\d Match any digit
(?::[0-5]\d){2} Match the following exactly twice
: Match this literally
[0-5] Match a number in the range between 0 and 5
\d Match any digit
10:00:00 Match this literally
$ Assert position at the end of the line
/(10:00:00|^0[0-9]:[0-5][0-9]:[0-5][0-9]$)/
['10:00:01', '10:00:00', '09:59:59', '05:05:05']
.forEach(t => console.log(t.match(/(10:00:00|^0[0-9]:[0-5][0-9]:[0-5][0-9]$)/)))
Your regex is close. Simply change your regex to:
/^(10:00:00|0[0-9]:[0-5][0-9]:[0-9][0-9])$/

RexExp min and max

I am trying to validate min 1 and max 59 with the following regexp but not working as expected.
^[1-5]?[1-9]$
What is wrong with the expression?
It's work: ^([1-5][0-9]|[1-9])$ (#Tushar)
if (/^([1-5][0-9]|[1-9])$/.test(number)) {
// Successful match
} else {
// Match attempt failed
}
The better/faster way (without regex):
function validate(number) {
number = parseInt(number);
return number > 0 && number < 60;
}
for (var i = 0; i < 65; i++) {
console.log(validate(i));
}
Tested:
Everyone busy trying to provide a solution missed the real question OP asked.
What is wrong with the expression?
Well here is your regex: ^[1-5]?[1-9]$
What you are trying to do is match a number having first digit (optional) in range 1 to 5 and second digit in range 1-9. And since you want to match number from 1 to 59, you will be missing is numbers like 10,20,30,40,50 as pointed out in one comment.

Year of date validation is failing

I need to do a date validation to accept it in dd/mm/yyyy format. However all conditions are working fine except that if I enter year of 6 digits it is also accepting it, like -
12/12/200000
as per my code is valid. Below is my code:
function validate(value) {
if(!value.match(/\d\d\/\d\d\/\d\d\d\d/))
return false;
return checkdate(value);
}
function checkdate(val)
{
var dates = val.split(/\D/);
if(dates[0] <= 0 || dates[0] > 31)
return false;
if(dates[1] <= 0 || dates[1] > 12)
return false;
var now = new Date(dates[2],dates[1]-1,dates[0]);
if (isNaN(now))
return false;
now.setHours(0,0,0,0);
if (now.getFullYear() == dates[2] && now.getMonth() + 1 == dates[1] && now.getDate() == dates[0])
return true;
return false;
}
I am not sure why it allowing year as 6 digits valid input?
The problem is in validate function, regular expression it matches against allows input values you don't want to pass as valid. Besides obvious dd/mm/yyyy format, it allows found text to be anywhere in string. Basically, you said for it to check "if there's said expression inside string", when it should have been "if the whole string matches this expression".
To fix the issue, add ^ at the beginning and $ at the end. ^ stands for string start and $ for string end:
/^\d\d\/\d\d\/\d\d\d\d$/
I think you would benefit from reading documentation on regular expression syntax used by JavaScript.
While at at, humans tend to have issues reading long repeating sequences of similar characters, like in your regexp. This expression is easer to understand and does exactly the same thing:
/^\d{2}\/\d{2}\/\d{4}$/
You're not limiting the regex with start and stop delimiters, so 12/12/200000 is a match as it matched the regex, and then some
if (!value.match(/^\d\d\/\d\d\/\d\d\d\d$/) )
As a sidenote, you don't have to type \d four times, you can do \d{4} to match four instances of \d
If you want to validate a date string by creating a Date object, you don't need to check the entire pattern, just create and Date and check the result. Do you really need two digits for day and month number?
If you want a 4 digit year, that must be checked separately as the constructor will happily convert two digit years to 20th century. If you really need two digit day and month, that can be checked at the same time as the year:
function validateDMY(s) {
var b = s.split(/\D/);
var d = new Date(b[2], --b[1], b[0]);
return d && /^\d{4}$/.test(b[2]) && b[1] == d.getMonth();
}
console.log(validateDMY('30/02/2015')); // false
console.log(validateDMY('30/22/2015')); // false
console.log(validateDMY('02/02/15')); // false
console.log(validateDMY('30/01/2015')); // true

Checking for uppercase/lowercase/numbers with Jquery

Either I'm being really retarded here or its just the lack of sleep but why doesn't this work? If I use the "or" operator it works for each separate test but as soon as it change it to the "and" operator it stops working.
I'm trying to test the password input of a form to see if its contains lowercase, uppercase and at least 1 number of symbol. I'm having a lot of trouble with this so help would be lovely, here is the code I have.
var upperCase= new RegExp('[^A-Z]');
var lowerCase= new RegExp('[^a-z]');
var numbers = new RegExp('[^0-9]');
if(!$(this).val().match(upperCase) && !$(this).val().match(lowerCase) && !$(this).val().match(numbers))
{
$("#passwordErrorMsg").html("Your password must be between 6 and 20 characters. It must contain a mixture of upper and lower case letters, and at least one number or symbol.");
}
else
{
$("#passwordErrorMsg").html("OK")
}
All of your regular expressions are searching for anything except the ranges that you have provided. So, [^A-Z] looks for anything but A-Z.
You are also negating each match.
You might try modifying your regular expression definitions by removing the ^, and then reversing your logic. So,
var upperCase= new RegExp('[A-Z]');
var lowerCase= new RegExp('[a-z]');
var numbers = new RegExp('[0-9]');
if($(this).val().match(upperCase) && $(this).val().match(lowerCase) && $(this).val().match(numbers))
{
$("#passwordErrorMsg").html("OK")
}
else
{
$("#passwordErrorMsg").html("Your password must be between 6 and 20 characters. It must contain a mixture of upper and lower case letters, and at least one number or symbol.");
}
This might even be a bit more intuitive to read?
var upperCase= new RegExp('[A-Z]');
var lowerCase= new RegExp('[a-z]');
var numbers = new RegExp('[0-9]');
if($(this).val().match(upperCase) && $(this).val().match(lowerCase) && $(this).val().match(numbers) && $(this).val().lenght>=6 && $(this).val()<=20)
{
$("#passwordErrorMsg").html("OK")
}
else
{
$("#passwordErrorMsg").html("Your password must be between 6 and 20 characters. It must contain a mixture of upper and lower case letters, and at least one number or symbol.");
}

Categories

Resources