Validate a time string (up to one hour) with javascript - javascript

I am looking for a regex pattern to validate a string and see if this is an valid time. It can only be up to one hour. I want to check if a string is a valid time or return false.
It needs to be in mm:ss format
Good = 00:00
Good = 60:00
Bad = 60:01
Bad = 89:09
Bad = 3445

Using regex to validate number ranges is not an optimal solution. You need to create a quite long pattern to evaluate easy conditions. You'd be probably better of checking only if it's a number:number pattern then split it and check if the parts are consistent with your requirements or not:
function checkTime(time) {
if (time.match("^[0-9]{2}:[0-9]{2}$") === null) {
return false;
}
var parts = time.split(':');
if (parts[0] > 60) {
return false;
}
if (parts[0] == 60 && parts[1] > 0) {
return false;
}
return true;
}
That being said you can create a regex for this if you really want:
function checkTime(time) {
return time.match("^(60:00|[0-5][0-9]:[0-5][0-9])$") !== null;
}
It's just much harder to maintain and read this kind of code later on.

My shot at it:
function validate(input){
var split = input.split(':'), // split the input
part1 = +split[0], part2 = +split[1]; // try to parse parts to numbers
if(!part1 || !part2) return false; // didn't get 2 valid numbers
return (part1*60 + part2) < 3600; // check if they're less then 1 hour
}
console.log(validate('55:09')); // true
console.log(validate('61:09')); // false
console.log(validate('6155')); // false
http://jsfiddle.net/LGheT/

Related

My code should be detecting if a string has currency symbols, but it will not detect £

My code is supposed to detect currency symbols, and execute code based on the result, but the code will not detect the '£' under any circumstances. Here is the relevant code:
let requirements = [ "£", "$" ];
let mcontent = "$£50";
let y = 0;
for (let p = 0; p < requirements.length; ++p) {
if (mcontent.includes(requirements[p])) {
++y;
}
}
if (y == 1) {
//this is considered success, only ONE currency symbol was detected. If mcontent = '$50' or '£50', we should be here.
} else {
//this is considered failure, TWO or ZERO currency symbols were detected. In this scenario, I want the code to fail.
}
I'm aware this may not be the best way to code a function to accomplish what I'm trying to accomplish, so I'm open for better ideas/fixes for what I already have.
The most concise way to do this is to check with RegExp like this:
if (mcontent.match(/£|\$/g)?.length == 1) { // the question mark is so we don't encounter an error if no matches were found
// success
} else {
// failure
}
Here's a live example:
const mcontent1 = '$£50';
const mcontent2 = '£50';
const mcontent3 = '$50';
const regex = /£|\$/g; // slash to escape $ because it has special meaning in regex
console.log(mcontent1.match(regex).length == 1); // false
console.log(mcontent2.match(regex).length == 1); // true
console.log(mcontent3.match(regex).length == 1); // true
If you don't want to use regex, just check if the string includes a symbol, increment a counter, and return whether or not there was exactly 1 match:
let testA = "$£50",
testB = "£50",
testC = "$50";
function checkString(str) {
const symbols = ["£", "$"];
let matches = 0;
for (const symbol of symbols)
if (str.includes(symbol)) matches++;
return matches == 1;
}
console.log(
checkString(testA),
checkString(testB),
checkString(testC)
);
Use RegExp it will return true or flase based on value entred
this example will give you an idea of how to use it
const elementTwo = document.getElementById('elementTwo');
elementTwo.addEventListener("input", function(event) {
pattern = /^[£|$]{1}(\d+)/
if (pattern.test(this.value)) {
console.log("found")
} else console.log("not found")
});
<p>Enter value</p>
<input id="elementTwo" type="text" />

Javascript Form validation with substr

This is part of a javascript to validate a form. This checks to see if it is empty.
if (form.redoarr.value == "") {
alert("Has to be higher");
form.redoarr.focus();
return false;
}
I want to make sure that the 4 digit number entered begins with a 2 digit number under 75. It also has to end in a 2 digit number under 40. How can I use substr to extract the first two digits and make sure they are under 75 and the last two digits and make sure they are under 40. I don't need anything complicated as it's for a single in house user on a private form. I can't just use < 7641 as 1849 is not okay (for instance).
Notwithstanding the usual caveats about never validating a form only in JavaScript (rather than using a server-side language), REGEX is a good fit for this:
let
err,
val = form.redoarr.value
;
if (!val)
err = 'No value entered';
else if (!/^([0-6][0-9]|7[0-4])([0-3][0-9])$/.test(val))
err = 'Value must be four digits, with the first two under 75 and the last two under 40';
if (err) {
form.redoarr.focus();
alert(err);
return false;
}
REGEX is cleaner as you don't need to create any variables. However here's how you'd do it via substring:
let
nums_1 = val.substr(0, 2),
nums_2 = val.substr(2)
;
I hope this solution helps
var value = form.redoarr.value;
var re = /^\d{4}$/;
var error = '';
var first_two_digits = '';
var last_two_digits = '';
if ( !re.test(value) ) {
error = 'Value must be four numbers';
}
first_two_digits = value.substr(0, 2);
last_two_digits = value.substr(2);
if (Number(first_two_digits) >= 75 || Number(last_two_digits) >= 40) {
error = 'Invalid number provided';
}
if (error) {
alert(error);
return false;
}

remove decimal in javascript

I want to remove decimal from number in javascript:
Something like this:
12 => 12
12.00 => 1200
12.12 => 1212
12.12.12 => error: please enter valid number.
I can not use Math.round(number). Because, it'll give me different result. How can I achieve this? Thanks.
The simplest way to handle the first three examples is:
function removeDecimal(num) {
return parseInt(num.toString().replace(".", ""), 10);
}
This assumes that the argument is a number already, in which case your second and fourth examples are impossible.
If that's not the case, you'll need to count the number of dots in the string, using something like (trick taken from this question):
(str.match(/\./g) || []).length
Combining the two and throwing, you can:
function removeDecimal(num) {
if ((num.toString().match(/\./g) || []).length > 1) throw new Error("Too many periods!");
return parseInt(num.toString().replace(".", ""), 10);
}
This will work for most numbers, but may run into rounding errors for particularly large or precise values (for example, removeDecimal("1398080348.12341234") will return 139808034812341230).
If you know the input will always be a number and you want to get really tricky, you can also do something like:
function removeDecimal(num) {
var numStr = num.toString();
if (numStr.indexOf(".") === -1) return num;
return num * Math.pow(10, numStr.length - numStr.indexOf(".") - 1);
}
You can use the replace method to remove the first period in the string, then you can check if there is another period left:
str = str.replace('.', '');
if (str.indexOf('.') != -1) {
// invalid input
}
Demo:
function reformat(str) {
str = str.replace('.', '');
if (str.indexOf('.') != -1) {
return "invalid input";
}
return str;
}
// show in Stackoverflow snippet
function show(str) {
document.write(str + '<br>');
}
show(reformat("12"));
show(reformat("12.00"));
show(reformat("12.12"));
show(reformat("12.12.12"));
How about number = number.replace(".", ""); ?

textbox must contain number or letter validation on javascript without regex

Hi guys i got a problem here, how i can validate a password box that must contain at least one numeric character. i'm not allowed using regular expression / regex. i have tried searching over the web, but the solution is always end with regex.
here's my code that i try
function validateIn()
{
var pass=document.getElementById('password').value;
for(var i=0;i<pass.length;i++)
{
if(isNaN(pass.charAt(i))==false)
{
return true;
break;
}
else
{
return false;
}
}
}
i have tried that way but i fail, can u help me guys? thanks before
One possible approach:
function validateIn() {
var pass = document.getElementById('password').value,
p = pass.length,
ch = '';
while (p--) {
ch = pass.charAt(p);
if (ch >= '0' && ch <= '9') {
return true; // we have found a digit here
}
}
return false; // the loop is done, yet we didn't find any digit
}
The point is, you don't have to return immediately after you have found a normal character (as you're basically looking for a single digit) - you just have to move on with your checking.
Note that I have gone without isNaN, as it's a bit inefficient: the only thing required is a range check.

Round the value in Javascript

I have scenario where if user enters for example 000.03, I want to show the user it as .03 instead of 000.03. How can I do this with Javascript?
You can use a regular expression:
"000.03".replace(/^0+\./, ".");
Adjust it to your liking.
This actually is trickier than it first seems. Removing leading zero's is not something that is standard Javascript. I found this elegant solution online and edited it a bit.
function removeLeadingZeros(strNumber)
{
while (strNumber.substr(0,1) == '0' && strNumber.length>1)
{
strNumber = strNumber.substr(1);
}
return strNumber;
}
userInput = "000.03";
alert(removeLeadingZeros(userInput));
How about:
function showRounded(val) {
var zero = parseInt(val.split('.')[0],10) === 0;
return zero ? val.substring(val.indexOf('.')) : val.replace(/^0+/,'') );
}
console.log(showRounded('000.03')); //=> ".03"
console.log(showRounded('900.03')); //=> "900.03"
console.log(showRounded('009.03')); //=> "9.03"
Or adjust Álvaro G. Vicario's solution to get rid of leading zero's into:
String(parseFloat("090.03")).replace(/^0+\./, ".")
This function will take any string and try to parse it as a number, then format it the way you described:
function makePretty(userInput) {
var num,
str;
num = parseFloat(userInput); // e.g. 0.03
str = userInput.toString();
if (!isNaN(num) && str.substring(0, 1) === '0') {
str = str.substring(1); // e.g. .03
} else if (isNaN(num)) {
str = userInput; // it’s not a number, so just return the input
}
return str;
}
makePretty('000.03'); // '.03'
makePretty('020.03'); // '20.03'
It you feed it something it cannot parse as a number, it will just return it back.
Update: Oh, I see If the single leading zero needs to be removed as well. Updated the code.
Assuming your input's all the same format, and you want to display the .
user = "000.03";
user = user.substring(3);
You can convert a string into a number and back into a string to format it as "0.03":
var input = "000.03";
var output = (+input).toString(); // "0.03"
To get rid of any leading zeroes (e.g. ".03"), you can do:
var input = "000.03";
var output = input.substr(input.indexOf(".")); // ".03"
However, this improperly strips "20.30" to ".30". You can combine the first two methods to get around this:
var input = "000.03";
var output = Math.abs(+input) < 1 ?
input.substr(input.indexOf(".")) :
(+"000.03").toString();

Categories