regex validation for age group - javascript

Am looking for a regex validator to validate age between 18 and 65 so far i have this:
^(1[90]|[2-6][0-9])$

I'm not sure why you would want to use regex for checking number ranges.
Below I've got a demo that checks the range the standard way, with greater than and less than but also I've included a regex way.
The regex way requires you to convert the number to a string first which is what the toString() bit is.
const numbers = [1, 20, 55, 67];
for (let num of numbers) {
if (num >= 18 && num <= 65)
console.log(`standard: ${num} is in range`)
}
for (let num of numbers) {
if (num.toString().match(/^([1][8-9]|[2-5][0-9]|[6][0-5])$/))
console.log(`regex: ${num} is in range`)
}
Here is a diagram to explain how the regex works.
^([1][8-9]|[2-5][0-9]|[6][0-5])$
Hope this is helpful.

Related

convert integer to 4 digit decimal in hour format

I need to write a function where i got one input parameter that can be a number from 1 to 9999. I need that output always be in a 4 digits format with a point between the numbers. For example, if the input is 1, the output must be 00,01. Input 157, ouput 01,57, and so on. Thanks
Consider utilizing padStart and slice:
const formatNum = num => {
if (!Number.isInteger(num)) throw "num must be an integer!";
if (num < 1 || num > 9999) throw "num must be between 1 and 9999 inclusive!";
const paddedNum = String(num).padStart(4, '0');
// TODO(#marcelo-teixeira-modesti): Add check to see if valid time as per train software requirements...
return `${paddedNum.slice(0, 2)},${paddedNum.slice(2)}`;
}
console.log(formatNum(1));
console.log(formatNum(157));
console.log(formatNum(2356));

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.

Regex to match numbers between 0 to 25 both inclusive which can be doubles with 1 precision

I want to use Regex to match numbers between 0 to 25 both inclusive which can be doubles with 1 precision.
For ex.- 2, 2.5, 23.0, 8, 24.3, 25
I created following regex-
^(\\s*|0?[0-9]|[0-9]|1[0-9]|2[0-5])$
But it works only for numbers between 0 to 25 both inclusive.
This is the regex pattern I would use here:
^(?:(?:[0-9]|1[0-9]|2[0-4])(?:\.[0-9])?|25(?:\.0)?)$
Demo
The pattern is similar to what you used, except that we only match 2[0-4] with any single decimal point. The end point 25 is a special case, which can only take 25.0 at most for its decimal component.
But in general it would easier in JavaScript to just parse the text number, and then use an inequality to check the range. E.g.
var number = '24.3'
if (number >= 0 && number <= 25.0) {
console.log('within range');
}
To verify the validity, use the >= and <= operators. To meet the regex requirement, just add a garbage regex expression.
let isMatch = number => {
'must use regex'.match(/x/);
return number >= 0 && number <= 25;
};

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.

Categories

Resources