I am trying to format the <input>
text to fit this format (example): 1050-5562-31AB-ABCD-123E-25DA-1A35-FADC
. I have tried it with onchange="isHardwareIDValid()"
, onchange="isHardwareIDValid(hid)"
, onkeydown="isHardwareIDValid()"
, and onkeydown="isHardwareIDValid(hid)"
with no luck.
I have an input
:
<input type="text" class="extrainfofield" id="ORDERPARAMETERS" name="ORDERPARAMETERS" value="##$LBL_HARDWAREID##" size="39" placeholder="Enter Hardware ID">
I was sent this javascript
code and haven't been able to get it to work:
function isHardwareIDValid (hid) {
return ((hid.length == 39) && (hid != "0000-0000-0000-0000-0000-0000-0000-0000") &&
isStringLimitedToHex (hid.substr (0, 4)) &&(hid.charAt (4) == "-") &&
isStringLimitedToHex (hid.substr (5, 4)) && (hid.charAt (9) == "-") &&
isStringLimitedToHex (hid.substr (10, 4)) && (hid.charAt (14) == "-") &&
isStringLimitedToHex (hid.substr (15, 4)) && (hid.charAt (19) == "-") &&
isStringLimitedToHex (hid.substr (20, 4)) && (hid.charAt (24) == "-") &&
isStringLimitedToHex (hid.substr (25, 4)) && (hid.charAt (29) == "-") &&
isStringLimitedToHex (hid.substr (30, 4)) && (hid.charAt (34) == "-") &&
isStringLimitedToHex (hid.substr (35, 4)) );
}
I have also used:
function isHardwareIDValid () {
var hid = document.getElementById("ORDERPARAMETERS");
return ((hid.length == 39) && (hid != "0000-0000-0000-0000-0000-0000-0000-0000") &&
isStringLimitedToHex (hid.substr (0, 4)) && (hid.charAt (4) == "-") &&
isStringLimitedToHex (hid.substr (5, 4)) && (hid.charAt (9) == "-") &&
isStringLimitedToHex (hid.substr (10, 4)) && (hid.charAt (14) == "-") &&
isStringLimitedToHex (hid.substr (15, 4)) && (hid.charAt (19) == "-") &&
isStringLimitedToHex (hid.substr (20, 4)) && (hid.charAt (24) == "-") &&
isStringLimitedToHex (hid.substr (25, 4)) && (hid.charAt (29) == "-") &&
isStringLimitedToHex (hid.substr (30, 4)) && (hid.charAt (34) == "-") &&
isStringLimitedToHex (hid.substr (35, 4)) );
}
This is inside of a shopping cart, so jQuery might not be an option.
CodePudding user response:
why not use a regex like: https://regex101.com/r/ifuMJP/1
const regex = /^([0-9A-Z]{4}-){7}[0-9A-Z]{4}$/gm;
const str = `1050-5562-31AB-ABCD-123E-25DA-1A35-FADC
1AA0-5562-31AB-ABCD-123E-25DA-1A35-FADC-ACBC
!050-5562-31AB-ABCD-123E-25DA-1A35-FADC
XXXX-XXXX-1234-XXXX-1234-12XX-1234-XXXX`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex ;
}
console.log(`Found match: ${m[0]}`);
}
where: [0-9]{4}-
means 4 digits (from 0-9) numbers followed by a -
and : [0-9A-Z]{4}
means 4 digits (0-9) or charactes (A-Z)
CodePudding user response:
what about using the "pattern" of the input element?
<input id="text" type="text" pattern="[0-9A-Z]{4}-[0-9A-Z]{4}- etc"/>
you could verify at any time using
element.checkValidity() and element.reportValidity() resp.