I need to write a function to validate the time of user input from console. The format of the time is HH:mm in 24 hours time.
function isValidTime(timeString) {
var regex_time = /^\d{2}\:\d{2}$/;
if(!regex_time.test(timeString))
{
return false;
}
var hour = timeString.getHour();
var minute = timeString.getMinutes();
if ((hour > 0 && hour <= 23) && (minute > 0 && minute <= 59)) {
return true;
}
}
This is the code I have so far. When I input 5:01, the output is invalid format. When I input 17:01, it shows
node:internal/readline/emitKeypressEvents:71
throw err;
^
TypeError: timeString.getHour is not a function
Could you please help with this function, I am reading user input with readline.
CodePudding user response:
I suggest you use capture groups in the regular expression... And the match method.
Match will return null
if no match at all
or an array containing the full match at position 0 followed by all capture group results.
function isValidTime(timeString) {
const regex_time = /^(\d{2})\:(\d{2})$/; // Use capture groups
const timeMatches = timeString.match(regex_time)
if(!timeMatches){
return false
}
const hour = parseInt(timeMatches[1])
const minute = parseInt(timeMatches[2])
if ((hour >= 0 && hour <= 23) && (minute >= 0 && minute <= 59)) {
return true;
}
return false
}
console.log(isValidTime("5:01")) // false
console.log(isValidTime("17:05")) // true
CodePudding user response:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div>
<input type="text" placeholder="MM" id="month">
<input type="text" placeholder="DD" id="date">
<input type="text" placeholder="YYYY" id="year">
<button>Check</button>
<h1>Result</h1>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="script.js"></script>
</body>
</html>
let btnCheck = document.querySelector('button');
let inputMonth = document.querySelector('#month');
let inputDate = document.querySelector('#date');
let inputYear = document.querySelector('#year');
let result = document.querySelector('h1');
btnCheck.addEventListener('click', (event) => {
let month = inputMonth.value;
let year = inputYear.value;
let date = inputDate.value;
// true in the end, so that our date string and date format should match exactly - in moment js it is called Strict Parsing
result.innerText = moment(`${month}/${date}/${year}`, 'MM/DD/YYYY', true).isValid();
});
CodePudding user response:
Solution : My solution
Another Tip : My Tip If you Get A Another Error you can write