JavaScript : return maximum possible `HH:MM` - javascript

Leetcode problem:
You are given a string that represents time in the format hh:mm. Some of the digits are blank (represented by ?). Fill in ? such that the time represented by this string is the maximum possible. Maximum time: 23:59, minimum time: 00:00. You can assume that input string is always valid.

You can use the replace function ability of String.replace. The second parameter passed in is the position of the ?, so use that to look up the max value for that position in an array.
const maxValues = ["2", "3", ":", "5", "9"];
const maxTime = (time) => time.replace(/\?/g, (s, p, str) => {
if (p === 1 && str[0] !== '2' && str[0] !== '?' ) {
return '9';
}
return maxValues[p];
});
console.log(maxTime("?1:1?"))
console.log(maxTime("??:??"))
console.log(maxTime("11:11"))
console.log(maxTime("1?:?1"))

This is not a very elegant solution but it addresses the problem I pointed out in my reply to James, where the send H in HH can be either 9 or 3 depending on the time. This also is just different but also valid.
maxTime = (strTime) => {
let [...str] = strTime;
if (str[0] == "?") { str[0] = "2"; }
if (str[1] == "?" && str[0] < "2") { str[1] = "9"; } else { str[1] = "3"; }
if (str[3] == "?") { str[3] = "5"; }
if (str[4] == "?") { str[4] = "9"; }
return str.join('');
}
console.log(maxTime("?2:22")); // 22:22
console.log(maxTime("2?:22")); // 23:22
console.log(maxTime("22:?2")); // 22:52
console.log(maxTime("22:2?")); // 22:29
console.log(maxTime("0?:??")); // 09:59
console.log(maxTime("1?:??")); // 19:59
console.log(maxTime("??:??")); // 23:59
or a loop
const max = "29:59";
maxTime = (strTime) => {
let [...str] = strTime;
for (x = 0; x < 5; x++) { if (strTime[x] == "?") { str[x] = max[x]; }}
if (str[0] == "2" && strTime[1] == "?") { str[1] = "3"; }
return str.join('');
}
console.log(maxTime("?2:22")); // 22:22
console.log(maxTime("2?:22")); // 23:22
console.log(maxTime("22:?2")); // 22:52
console.log(maxTime("22:2?")); // 22:29
console.log(maxTime("0?:??")); // 09:59
console.log(maxTime("1?:??")); // 19:59
console.log(maxTime("??:??")); // 23:59

maxTime = (time) => {
const timeArr = time.split(":");
let hr = timeArr[0];
let mn = String(timeArr[1]);
if (mn.includes("?")) {
const mnArr = mn.split("");
if (mnArr[0] === "?" && mnArr[1] === "?") {
mn = "59";
} else if (mnArr[0] === "?") {
mn = "5" + mnArr[1];
} else if (mnArr[1] === "?") {
const temp = mnArr[0] === "5" ? "9" : "0";
mn = mnArr[0] + temp;
}
}
if (hr.includes("?")) {
const hrArr = hr.split("");
if (hrArr[0] === "?" && hrArr[1] === "?") {
hr = "23";
} else if (hrArr[0] === "?") {
hr = "2" + hrArr[1];
hr = Number(hr) <= 24 ? "1" + hrArr[1] : hr;
} else if (hrArr[1] === "?") {
const temp = hrArr[0] === "2" ? "3" : "9";
hr = hrArr[0] + temp;
}
}
return `(${time}) => ${hr}:${mn}`;
}

Related

Date Evaluation in JS

I need to validate a credit card expiry date, I have the javascript code but I don't know how to customize it for my need.
this is my code, I only need the date in a mm/yy format but this code has the date format in mm/dd/yyyy.
var date = document.getElementById('date');
function checkValue(str, max) {
if (str.charAt(0) !== '0' || str == '00') {
var num = parseInt(str);
if (isNaN(num) || num <= 0 || num > max) num = 1;
str = num > parseInt(max.toString().charAt(0))
&& num.toString().length == 1 ? '0' + num : num.toString();
};
return str;
};
date.addEventListener('input', function(e) {
this.type = 'text';
var input = this.value;
if (/\D\/$/.test(input)) input = input.substr(0, input.length - 3);
var values = input.split('/').map(function(v) {
return v.replace(/\D/g, '')
});
if (values[0]) values[0] = checkValue(values[0], 12);
if (values[1]) values[1] = checkValue(values[1], 31);
var output = values.map(function(v, i) {
return v.length == 2 && i < 2 ? v + ' / ' : v;
});
this.value = output.join('').substr(0, 14);
});

How to convert lowercase uppercase?(with if conditions on different digits.)

Hi This is my first time using this website, I did do some research about how to convert lowercase letter to uppercase letter but still filles. The requirement is to check if "even", covert the even digit letter to different type(lower to upper or upper to lower). below is my code:
function question4(str,pos)
{ var newLetter;
var kkk=str;
if (pos='even')
{
for (var i=0;i<str.length;i=i+2)
{
if (str[i].toString()==str[i].toString().toUpperCase())
{
newLetter=str[i].toString().toLowerCase();
kkk[i]=newLetter;
}else
{
newLetter=str[i].toUpperCase();
kkk[i]=newLetter;
}
}
}else if (pos='odd')
for ( i=0;i<str.length;i=i+2)
{
if (str[i]===str[i].toLowerCase())
{
alert('3');
}else if (str[i]===str[i].toUpperCase())
{
alert('4');
}
}
return kkk;
}
the requirement is: Write a function to change the case of all the characters in string based on their position which matches the value of the pos parameter function. function (str, pos [even|odd]). Example ( (‘abCd’, ‘odd’) return Abcd)
Update: now I have make "odd" condition working, but "even "still is not working, can any one take a look why?
function question4(strr,pos) {
var result ;
var sum="";
var aaa;
for (var i = 0; i <= strr.length - 1; i = i + 1)
{
if (pos == "odd"&&i%2==0)
{ aaa=strr.charCodeAt(i);
if (aaa >= 65 && aaa <= 90 )
{
result = String.fromCharCode(aaa + 32);
} else
result = String.fromCharCode(aaa - 32);
}
else if (pos == "even"&&i%2==1)
{
if (aaa >= 65 && aaa <= 90 )
{
result= String.fromCharCode(aaa + 32);
} else
result = String.fromCharCode(aaa - 32);
}else result=strr[i];
sum+=result;
}
return sum;
}
To achieve this, you can construct a string by concating char by char:
function question4(strInput, pos) {
let str = ""; // The string to construct
if (!pos || (pos !== "even" && pos !== "odd")) { // Validating pos
throw "invalid pos";
}
for (var i=0;i<strInput.length;i++) // Looping on strInput
{
let huPos = i + 1;
if ((pos === "even" && huPos%2 == 1) ||
(pos === "odd" && huPos%2 == 0)) {
/* If we want switch odd and we are on even position or if we want switch even and we are on odd position, then we add the original char
*/
str += strInput[i];
}
else {
// In others case, we switch lower to upper and upper to lower
let char = strInput[i];
str += char == char.toUpperCase() ? char.toLowerCase() : char.toUpperCase();
}
}
return str;
}
console.log(question4('abCdef', "odd")); // Return "AbcdEf"
Associated bin
EDIT:
After seeing edit, i can see you want to do it without using toLower/UpperCase. As stated in comment i think it is a bad idea in js, but to experiment you can achieve this:
const reverser = {
"a": "a".charCodeAt(0),
"z": "z".charCodeAt(0),
"A": "A".charCodeAt(0),
"Z": "Z".charCodeAt(0),
};
const conversionValueToLower = reverser.a - reverser.A;
const conversionValueToUpper = reverser.A - reverser.a;
function reverseChar(char) {
var code = char.charCodeAt(0);
// If you want to go from upper to lower
if (code >= reverser.A && code <= reverser.Z) {
// Simply add the difference between lower and upper
return String.fromCharCode(code + conversionValueToLower);
} // Same logic here
else if (code >= reverser.a && code <= reverser.z) {
return String.fromCharCode(code + conversionValueToUpper);
}
/**
Or use if you want full digit
if (code <= 90 && code >= 65) {
return String.fromCharCode(code + 32);
}
else if (code >= 97 && code <= 122) {
return String.fromCharCode(code - 32);
}
**/
return char; // Other case return original char
}
function question4(strInput, pos) {
let str = "";
if (!pos || (pos !== "even" && pos !== "odd")) {
throw "invalid pos";
}
for (var i=0;i<strInput.length;i++)
{
let huPos = i + 1;
if ((pos === "even" && huPos%2 == 1) ||
(pos === "odd" && huPos%2 == 0)) {
str += strInput[i];
}
else {
str += reverseChar(strInput[i]);
}
}
return str;
}
console.log(question4('abCdef', "odd")); // return "AbcdEf"
Associated bin
Another way could be to code utils functions imitating toLower/UpperCase
I corrected your code in your answer aswell, without changing original logic
function question4(strr,pos) {
var result ;
var sum="";
var aaa;
for (var i = 0; i <= strr.length - 1; i = i + 1)
{
if (pos == "odd"&&i%2==0)
{ aaa=strr.charCodeAt(i);
if (aaa >= 65 && aaa <= 90 )
{
result = String.fromCharCode(aaa + 32);
} else if(aaa >=97&&aaa <=122)
{ result = String.fromCharCode(aaa - 32);}
else {result=strr[i];}
}
else if (pos == "even"&&i%2==1)
{ aaa=strr.charCodeAt(i);
if (aaa >= 65 && aaa <= 90 )
{
result= String.fromCharCode(aaa + 32);
} else if(aaa >=97&&aaa <=122)
{ result = String.fromCharCode(aaa - 32);}
else {result=strr[i];}
}else {result=strr[i];}
sum+=result;
}
return sum;
}
console.log(question4("abCd", "odd")) // return Abcd;
A simple solution for this question
// Function used to invert the letter case
const changeCase = c => {
if (c === c.toUpperCase()) return c.toLowerCase()
return c.toUpperCase()
}
const swapCaseConditional = (str, pos) => {
// Use split method to convert string into array and map the array
return str.split('').map((c, index) => {
if (pos === 'even') {
// if pos and index are even, change the letter case
if (index % 2) return changeCase(c)
return c
}
else {
// if pos and index are odd, change the letter case
if (!(index%2)) return changeCase(c)
return c
}
// Convert to string
}).join('')
}
console.log(swapCaseConditional('abCd', 'odd'))
I worked two nights and finally got it working. although not fully cover all the situations, but almost there.
function question4(strr,pos) {
var result ;
var sum="";
var aaa;
for (var i = 0; i <= strr.length - 1; i = i + 1)
{
if (pos == "odd"&&i%2==0)
{ aaa=strr.charCodeAt(i);
if (aaa >= 65 && aaa <= 90 )
{
result = String.fromCharCode(aaa + 32);
} else
result = String.fromCharCode(aaa - 32);
}
else if (pos == "even"&&i%2==1)
{ aaa=strr.charCodeAt(i);
if (aaa >= 65 && aaa <= 90 )
{
result= String.fromCharCode(aaa + 32);
} else if(aaa >=97&&aaa <=122)
{ result = String.fromCharCode(aaa - 32);}
else {result=strr[i];}
}else {result=strr[i];}
sum+=result;
}
return sum;
}

type conversion not working javascript

I created a rather large function that takes in an argument, and based on the number's size, properly formats it. It works as expected for any values with the typeof number, however there are a few instances where I need to convert a string to a numeric value. I am trying to do that by using parseInt if its type is not number. When I console.log after the first if-statement, it says its typeof is now number. However when any string is passed through, say, "10000", it just shows up as 10000, and not the expected output of 10,000 with the proper formatting. Below is my code...are there any glaring ways that I might be going about it wrong?
function formatNumber(number) {
if (typeof number !== 'number') {
number = parseInt(number);
return number;
}
let decimals = 2;
const isNegative = number < 0;
const rounded = (number >= 1e+6) ? Math.round(number) : number;
const isInteger = () => parseInt(number, 10) === parseFloat(number);
const abs = Math.abs(rounded);
if (abs < 1e+6) {
decimals = isInteger(abs) ? 0 : decimals;
}
const formatter = val => {
const string = Math.abs(val).toString();
let formatted = '';
for (let i = string.length - 1, d = 1; i >= 0; i--, d++) {
formatted = string[i] + formatted;
if (i > 0 && d % 3 === 0) {
formatted = `,${formatted}`;
}
}
return formatted;
};
const formatLargeNumbers = (value, decimalPlaces) => {
let adjustedValue;
if (value >= 1e+12) {
adjustedValue = parseFloat((value / 1e+12).toFixed(decimals));
return `<span title=${formatter(value)}>${adjustedValue}T</span>`;
}
if (value >= 1e+9) {
adjustedValue = parseFloat((value / 1e+9).toFixed(decimals));
return `<span title=${formatter(value)}>${adjustedValue}B</span>`;
}
if (value >= 1e+6) {
adjustedValue = parseFloat((value / 1e+6).toFixed(decimals));
return `<span title=${formatter(value)}>${adjustedValue}M</span>`;
}
if (value >= 1e+3 && value < 1e+6) {
return value.toLocaleString('en-EN', {
minimumFractionDigits: decimalPlaces,
maximumFractionDigits: decimalPlaces,
});
}
return value.toFixed(decimals);
};
if (isNegative) {
let negativeNumber = Math.abs(rounded);
if (negativeNumber >= 1e+3) {
negativeNumber = formatLargeNumbers(negativeNumber);
}
return `<span class="negative-value">(${negativeNumber})</span>`;
}
return formatLargeNumbers(rounded, decimals);
}

Check SSL certificate Expiration Date

I need to check local computer's SSl certificate expiry DATE and compare it with current date and notify user that his/her certificate is going to expire in X days. All this I need to do in JavaScript.
Your certificate should look like this:
-----BEGIN CERTIFICATE-----
MIIGoDCCBIigAwIBAgIJAICRY3cWdgK1MA0GCSqGSIb3DQEBCwUAMIGeMQswCQYD
VQQGEwJCRzERMA8GA1UECAwIQnVsZ2FyaWExDjAMBgNVBAcMBVNvZmlhMQ8wDQYD
..
ud5Nja8+xycA/Jk7bSvB1jJjpc3oL0G9j0HOcxqQKd4e1IQXuss5V7FnQxSOVCq4
GVK0r3LkAxtl/EGmQC1DRlHAUWg=
-----END CERTIFICATE-----
You need to strip the -----BEGIN CERTIFICATE----- header and the -----END CERTIFICATE----- trailer from the certificate data, the rest is a Base64 encoded byte array.
You need to decode it to an array of bytes (in this example represented as array of number, where each number represents a byte - number between 0 and 255 inclusive).
That byte array is a DER encoded ASN.1 structure as defined in RFC-5280.
The below example will parse the content of the certificate after the -----BEGIN CERTIFICATE----- and -----END CERTIFICATE----- traile has already been stripped.
Usage:
var pem =
"MIIGijCCBXKgAwIBAgIQEpI/gkvDS6idH2m2Zwn7ZzANBgkqhkiG9w0BAQsFADCB\n"
...
+"VQ+o34uWo7z19I8eXWSXN6P+Uj1OvHn8zNM1G/ddjQXBwMvzwwJEdVBhdK1uQw==\n";
var bytes = fromBase64(pem);
var validity = getValidity(bytes);
var notBefore = validity.notBefore;
var notAfter = validity.notAfter;
var now = new Date();
if ( notBefore.getTime() < now.getTime()
&& now.getTime() < notAfter.getTime())
{
// Certificate is withing its validity days
} else {
// Certificate is either not yet valid or has already expired.
}
Parsing:
var TYPE_INTEGER = 0x02;
var TYPE_SEQUENCE = 0x10;
var TYPE_UTC_TIME = 0x17;
var TYPE_GENERALIZED_TIME = 0x18;
function subArray(original, start, end) {
var subArr = [];
var index = 0;
for (var i = start; i < end; i++) {
subArr[index++] = original[i];
}
return subArr;
}
function getDigit(d) {
switch (d) {
default:
case 0x30: case '0': return 0;
case 0x31: case '1': return 1;
case 0x32: case '2': return 2;
case 0x33: case '3': return 3;
case 0x34: case '4': return 4;
case 0x35: case '5': return 5;
case 0x36: case '6': return 6;
case 0x37: case '7': return 7;
case 0x38: case '8': return 8;
case 0x39: case '9': return 9;
}
}
function enterTag(bytes, start, requiredTypes, name) {
if (start + 1 > bytes.length) {
throw new Error("Too short certificate input");
}
var typeByte = bytes[start ] & 0x0FF;
var lenByte = bytes[start +1] & 0x0FF;
var type = typeByte & 0x1F;
var len = lenByte;
var index = start + 2;
if (requiredTypes.length > 0 && requiredTypes.indexOf(type) == -1) {
throw new Error("Invalid type");
}
var lengthOfLength = 0;
if (len > 0x07F) {
lengthOfLength = len & 0x7F;
len = 0;
for (var i =0; i < lengthOfLength && index < bytes.length; i++) {
len = (len << 8 ) | (bytes[index] & 0x00FF);
index++;
}
}
if (index >= bytes.length) {
throw new Error("Too short certificate input");
}
return {index: index, type: type, length: len}
}
function processTag(bytes, start, requiredTypes, name) {
var result = enterTag(bytes, start, requiredTypes, name);
var index = result.index + result.length;
if (index >= bytes.length) {
throw new Error("Too short certificate input");
}
var valueStart = result.index;
var valueEnd = result.index + result.length;
var value = subArray(bytes, valueStart, valueEnd);
return { index: index, type: result.type, value: value};
}
function readDate(bytes, start, name) {
var date = new Date();
var result = processTag(bytes, start,
[TYPE_UTC_TIME, TYPE_GENERALIZED_TIME], name);
var index, year;
if (result.type == 0x17) { // UTCTime
if (result.value.length < 12) {
throw new Error("Invalid type");
}
var yearHigh = getDigit(result.value[0]);
var yearLow = getDigit(result.value[1]);
var year2Digits = (yearHigh * 10 ) + (yearLow)
if (year2Digits >= 50) {
year = 1900 + year2Digits;
} else {
year = 2000 + year2Digits;
}
index = 2;
} else if (result.type = 0x18) { // GeneralizedTime
if (result.value.length < 14) {
throw new Error("Invalid type");
}
var year1 = getDigit(result.value[0]);
var year2 = getDigit(result.value[1]);
var year3 = getDigit(result.value[2]);
var year4 = getDigit(result.value[3]);
year = (year1 * 1000) + (year2 * 100) + (year3*10) + year4;
index = 4;
}
var monthHigh = getDigit(result.value[index++]);
var monthLow = getDigit(result.value[index++]);
var dayHigh = getDigit(result.value[index++]);
var dayhLow = getDigit(result.value[index++]);
var hourHigh = getDigit(result.value[index++]);
var hourLow = getDigit(result.value[index++]);
var minuteHigh = getDigit(result.value[index++]);
var minuteLow = getDigit(result.value[index++]);
var secondHigh = getDigit(result.value[index++]);
var secondLow = getDigit(result.value[index]);
var month = (monthHigh * 10) + monthLow;
var day = (dayHigh * 10) + dayhLow;
var hour = (hourHigh * 10) + hourLow;
var minute = (minuteHigh * 10) + minuteLow;
var second = (secondHigh * 10) + secondLow;
if (month < 1 || month > 12) {
throw new Error("Invalid month");
}
if (day < 1 || day > 31) {
throw new Error("Invalid day");
}
if (hour < 0 || hour > 24) {
throw new Error("Invalid hour");
}
if (minute < 0 || minute > 59) {
throw new Error("Invalid minute");
}
if (second < 0 || second > 59) {
throw new Error("Invalid second ");
}
date.setUTCFullYear(year);
date.setUTCMonth(month-1);
date.setUTCDate(day);
date.setUTCHours(hour);
date.setUTCMinutes(minute);
date.setUTCSeconds(second);
return {
index: result.index,
type: result.type,
length: result.length,
value: result.value,
date: date
};
}
function getValidity(bytes) {
if (bytes == null || bytes.length <= 0) {
return null;
}
var index = 0;
index = enterTag(bytes, index, [TYPE_SEQUENCE], "Certificate").index;
index = enterTag(bytes, index, [TYPE_SEQUENCE], "TBSCertificate").index;
var result = processTag(bytes, index, [0x00, 0x02],
"Version or SerialNumber");
if (result.type == 0) {
index = result.index;
result = processTag(bytes, index, [TYPE_INTEGER], "SerialNumber")
}
index = result.index;
result = processTag(bytes, index, [TYPE_SEQUENCE],
"Signature AlgorithmIdentifier");
index = result.index;
result = processTag(bytes, index, [], "Issuer Name");
index = result.index;
index = enterTag(bytes, index, [TYPE_SEQUENCE], "Validity").index;
result = readDate(bytes, index, "Not Before");
var notBefore = result.date;
index = result.index;
result = readDate(bytes, index, "Not After");
var notAfter = result.date;
return {notBefore: notBefore, notAfter: notAfter};
}
function getNextBase64Chr(str, index, equalSignReceived, alpha) {
var chr = null;
var code = 0;
var padding = equalSignReceived;
while (index < str.length) {
chr = str.charAt(index);
if (chr == " " || chr == "\r" || chr == "\n" || chr == "\t") {
index++;
continue;
}
if (chr == "=") {
padding = true;
} else {
if (equalSignReceived) {
throw new Error("Invalid Base64 Endcoding.");
}
code = alpha.indexOf(chr);
if (code == -1) {
throw new Error("Invalid Base64 Encoding .");
}
}
break;
}
return { character: chr, code: code, padding: padding, nextIndex: ++index};
}
function fromBase64(str) {
var alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var value = [];
var index = 0;
var destIndex = 0;
var padding = false;
while (true) {
var first = getNextBase64Chr(str, index, padding, alpha);
var second = getNextBase64Chr(str, first .nextIndex, first .padding, alpha);
var third = getNextBase64Chr(str, second.nextIndex, second.padding, alpha);
var fourth = getNextBase64Chr(str, third .nextIndex, third .padding, alpha);
index = fourth.nextIndex;
padding = fourth.padding;
// ffffffss sssstttt ttffffff
var base64_first = first.code == null ? 0 : first.code;
var base64_second = second.code == null ? 0 : second.code;
var base64_third = third.code == null ? 0 : third.code;
var base64_fourth = fourth.code == null ? 0 : fourth.code;
var a = (( base64_first << 2 ) & 0xFC ) | ((base64_second >> 4) & 0x03);
var b = (( base64_second << 4 ) & 0xF0 ) | ((base64_third >> 2) & 0x0F);
var c = (( base64_third << 6 ) & 0xC0 ) | ((base64_fourth >> 0) & 0x3F);
value [destIndex++] = a;
if (!third.padding) {
value [destIndex++] = b;
} else {
break;
}
if (!fourth.padding) {
value [destIndex++] = c;
} else {
break;
}
if (index >= str.length) {
break;
}
}
return value;
}
Used resources:
A Layman's Guide to a Subset of ASN.1, BER, and DER
Encoding of ASN.1 UTC Time and GeneralizedTime
RFC-5280
The only available option so far is forge - https://github.com/digitalbazaar/forge/blob/master/README.md or some sort of custom extension for the client.
Client side does not know nothing about other than DOM elements thus it cannot inspect SSL layer.
More on this Within a web browser, is it possible for JavaScript to obtain information about the SSL Certificate being used for the current page?
This is not possible from the client, but you could do something like this with node / shell combo.
Assuming you have access to the server the cert is running on you could do something like this on the host:
var execSync = require('child_process').execSync
var cmd = "echo | openssl s_client -connect 127.0.0.1:443 2>/dev/null | openssl x509 -noout -dates"
var stdout = execSync(cmd).toString()
// "notBefore=Feb 16 15:33:00 2017 GMT\nnotAfter=May 17 15:33:00 2017 GMT"
From there you could parse the dates reported by stdout and write them to a public resource or json file so they are readable from the client, and from there do your date comparison.

String Time Validations (In javascript)

I have a text box which accepts time(max of 5 characters only), and a drop down which accepts am or pm value.
I need to perform some validations for the string values entered into the text box such as:
If user enters 9 => Should be changed to 0900
9:3 => 0930
09:3 => 0930
93 => alert ('Invalid Hours value)
115 => 0115
12 => 1200
Invalid entries such as !##$%^&*()<>?/~`,;'"[]_-abcdefg.. => alert ('Invalid Time Value') should be displayed.
So far, all I've achieved is replacing the : with ''.
For example, if user enters 09:00 => 0900
I need something like:
if clks is 1 digit, then rightpad clks with 2 zeroes.
if 2 digits: clks > 12 , then alert(Invalid hours value)
if 3 digits: clks < (%59) (i.e checking last 2 chars) , then leftpad with 1 zero
or clks > (%59) , then alert ('Invalid minutes value)
if 4 digits: clks>12% (checking first 2 chars), alert ('invalid hours value')
or (clks>12% and clks>59%) , then alert('invalid clock time')
or (clks<12%) and (clks<59%) , then accept the number as it is.
if 5 digits: (and all are numbers), then alert('invalid clk time')
These validations need to be done within script tag. (The backend language that I've used is jsp.)
Pls help me :(
Here is a part of the code that I have written:
<script type='text/javascript'>
function clocks(){
var clk = document.getElementById('TIME').value;
var clks = clk.replace('/:/g','');
var ampm = document.getElementById('AMPM').value;
var add = 1200;
if (clks=="")
{
alert("You must enter clock time");
}
else
{
if (ampm=='p')
{
clks=parseFloat(clks) + parseFloat(add);
}
}
}
....
</script>
Here's a way to do it in a function:
function validate_time( clks ) {
// Remove any non-digit characters
clks = clks.toString().replace(/\D/g, '');
var is_valid = false;
switch (clks.length) {
case 1:
// This will run if the length is 1 digit.
clks = clks + '00';
// Mark this as a valid time.
is_valid = true;
// stop running the rest
break;
case 2:
if ( parseInt(clks) > 12 ) {
alert("Invalid hours value");
} else {
is_valid = true;
}
break;
case 3:
// Get last two characters
var mins = clks.substr(1,2); // offset 1 character, length of 2 characters
if ( parseInt(mins) <= 59 ) {
clks = '0' + clks;
is_valid = true;
} else {
alert('Invalid minutes value');
}
break;
case 4:
var hours = clks.substr(0,2);
var mins = clks.substr(2,2);
if ( parseInt(hours) > 12 || parseInt(mins) > 59 ) {
alert('Invalid clock time');
} else {
is_valid = true;
}
break;
case 5:
alert("Invalid clock time");
break;
}
var data = { clks: clks, is_valid: is_valid };
return data;
}
To call it, you'd do:
var result = validate_time(clks);
and your result would be an object passed back... result.clks is the padded time, and result.is_valid will either be a true or false value as to whether the input time is valid or not.
function validateTimeNew(obj) {
var timeValue = obj.value;
if (timeValue == "" || timeValue.indexOf(":") < 0) {
alert("Invalid Time format.Valid Format Example 01:56:00 or 23:06:00");
return false;
}
else {
var sHrs = timeValue.split(':')[0];
var smin = timeValue.split(':')[1];
smin = smin.substring(0, 2);
var sAmnPm = timeValue.split(' ')[1] || timeValue.split(':')[2];
if (!isNaN(sAmnPm))
{
sAmnPm = sAmnPm.toUpperCase();
}
var chkAmnPm =timeValue.split(':')[1];
if (chkAmnPm.length == 4)
sAmnPm = chkAmnPm.substring(2, 4);
sAmnPm = sAmnPm.toUpperCase();
if (sHrs == "" || isNaN(sHrs) || parseInt(sHrs) > 23) {
alert("Invalid Time format Hours : "+ sHrs);
return false;
}
else if (parseInt(sHrs) == 0) {
sHrs = "00";
sAmnPm = "AM";
}
else if (sHrs < 10 )
{
sHrs = "0" + parseInt(sHrs);
if (sAmnPm != "PM")
sAmnPm = "AM";
}
else if (sHrs > 13) {
sHrs = parseInt(sHrs) - 12;
if (sHrs < 10)
sHrs = "0" + parseInt(sHrs);
sAmnPm = "PM";
}
else if (sHrs == 10 )
{
sHrs = parseInt(sHrs);
if (sAmnPm != "PM")
sAmnPm = "AM";
}
if (smin == "" || isNaN(smin) || parseInt(smin) > 59) {
alert("Invalid Time format Minutes :" + smin);
return false;
}
else if (parseInt(smin) == 0)
smin = "00";
else if (smin < 10)
smin = "0" + parseInt(smin);
if (sAmnPm == "" || sAmnPm=="undefined")
{
sAmnPm = "AM"
}
else { sAmnPm = sAmnPm.toUpperCase(); }
obj.value = sHrs + ":" + smin + ":" + sAmnPm;
}
}

Categories

Resources