UNPKG

validify-string

Version:

Ensure accurate and secure input with our reliable string validation library.

324 lines (323 loc) 12.1 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.generateRandomString = exports.addFullstop = exports.removeNumber = exports.removeUnderscore = exports.removeSpace = exports.addUnderscore = exports.getLeftSubstring = exports.getAlphaNumString = exports.decrypt = exports.encrypt = exports.trimBoth = exports.trimRight = exports.trimLeft = exports.isJWT = exports.isJSON = exports.isHexColor = exports.isASCII = exports.isHexadecimal = exports.isHash = exports.isAlphanumeric = exports.isValidCardNumber = exports.isValidDate = exports.isPalindrome = exports.isLowercase = exports.isUppercase = exports.isIP = exports.isValidPhone = exports.isURL = exports.isPasswordStrong = exports.countOccurrences = exports.isAvailable = exports.countWords = exports.isValidEmail = exports.isAlphaNumeric = exports.isEmpty = exports.isAlpha = exports.isIdentical = void 0; var isIdentical = function (strOne, strTwo) { strOne = strOne.trim(); strTwo = strTwo.trim(); if (strOne.toLowerCase() === strTwo.toLowerCase()) { return true; } return false; }; exports.isIdentical = isIdentical; var isAlpha = function (str) { if (/^[a-zA-Z]+$/.test(str)) { return true; } return false; }; exports.isAlpha = isAlpha; var isEmpty = function (value) { value = value.trim(); return value.length == 0; }; exports.isEmpty = isEmpty; var isAlphaNumeric = function (str) { if (/^[a-zA-Z0-9]+$/.test(str)) { return true; } return false; }; exports.isAlphaNumeric = isAlphaNumeric; var isValidEmail = function (email) { // regular expression to match valid email addresses var pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; // match the pattern against the email string return pattern.test(email); }; exports.isValidEmail = isValidEmail; var countWords = function (str) { // split the string into an array of words var words = str.split(" "); // return the length of the array return words.length; }; exports.countWords = countWords; var isAvailable = function (str, word) { if (str.indexOf(word) !== -1) { return true; } return false; }; exports.isAvailable = isAvailable; var countOccurrences = function (str, word) { // split the string into an array of words var words = str.split(" "); // initialize a counter variable var count = 0; // loop through the array of words for (var i = 0; i < words.length; i++) { // if the current word matches the target word, increment the counter if (words[i] === word) { count++; } } // return the count return count; }; exports.countOccurrences = countOccurrences; var isPasswordStrong = function (password) { // define a regular expression that matches a strong password var strongRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/; // test the password against the regular expression return strongRegex.test(password); }; exports.isPasswordStrong = isPasswordStrong; var isURL = function (str) { // define a regular expression that matches a URL format var urlRegex = /^(?:\w+:)?\/\/([^\s\.]+\.\S{2}|localhost[\:?\d]*)\S*$/; // test the string against the regular expression return urlRegex.test(str); }; exports.isURL = isURL; var isValidPhone = function (num) { var _a; //number should be of 10 digits. if (num[0] == "0") return false; // define a regular expression that matches a numbers var phoneregex = /\d/g; // test the number against the regular expression and then compare its length with original number length return num.length == ((_a = num.match(phoneregex)) === null || _a === void 0 ? void 0 : _a.length); }; exports.isValidPhone = isValidPhone; var isIP = function (ip) { // define a regular expression that matches both IPv4 and IPv6 addresses var ipRegex = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){2}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$|^([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}$|^([0-9a-fA-F]{1,4}:){1,7}:|^([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}$|^([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}$|^([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}$|^([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}$|^([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}$|^[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})$/; // test the input against the regular expression return ipRegex.test(ip); }; exports.isIP = isIP; var isUppercase = function (str) { return str === str.toUpperCase(); }; exports.isUppercase = isUppercase; var isLowercase = function (str) { return str === str.toLowerCase(); }; exports.isLowercase = isLowercase; var isPalindrome = function (str) { var cleanStr = str.toLowerCase().replace(/[^a-zA-Z0-9]/g, ''); var reversedStr = cleanStr.split('').reverse().join(''); return cleanStr === reversedStr; }; exports.isPalindrome = isPalindrome; var isValidDate = function (dateString) { // Assuming the date format is YYYY-MM-DD for simplicity var regex = /^\d{4}-\d{2}-\d{2}$/; if (!regex.test(dateString)) return false; var date = new Date(dateString); return !isNaN(date.getTime()); }; exports.isValidDate = isValidDate; var isValidCardNumber = function (num) { //Check if the num contains only numeric value //and is of between 13 to 19 digits var regex = /^[0-9]{13,19}$/; if (!regex.test(num)) { return false; } // Appling luhn's algorithm var sum = 0; var multiplier = 1; // Starting from last digit for (var i = num.length - 1; i >= 0; i--) { var digit = 0; // Extract the next digit and multiply by 1 or 2 on alternative digits. digit = Number(num.charAt(i)) * multiplier; // If the result is in two digits add 1 to the checksum total if (digit > 9) { digit -= 9; } // Add the units digit to the sum sum += digit; // Switch the value of multiplier to alternate digit if (multiplier == 1) { multiplier = 2; } else { multiplier = 1; } } // Checks divisible by 10 return (sum % 10) == 0; }; exports.isValidCardNumber = isValidCardNumber; //Check alphanumeric string var isAlphanumeric = function (str) { var alphanumericRegex = /^[a-zA-Z0-9]+$/; return alphanumericRegex.test(str); }; exports.isAlphanumeric = isAlphanumeric; //Check Ishash var isHash = function (str) { return /^[a-fA-F0-9]+$/.test(str) && (str.length === 32 || str.length === 40 || str.length === 64); }; exports.isHash = isHash; //Check hexadecimal var isHexadecimal = function (str) { var hexadecimalRegex = /^[0-9a-fA-F]+$/; return hexadecimalRegex.test(str); }; exports.isHexadecimal = isHexadecimal; //Check ASCII Value var isASCII = function (str, extended) { return (extended ? /^[\x00-\xFF]+$/ : /^[\x00-\x7F]+$/).test(str); }; exports.isASCII = isASCII; // Check Hexcolour var isHexColor = function (str) { var hexColorRegex = /^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/; return hexColorRegex.test(str); }; exports.isHexColor = isHexColor; // Check JSON var isJSON = function (str) { try { JSON.parse(str); return true; } catch (e) { return false; } }; exports.isJSON = isJSON; // Check JWT var isJWT = function (str) { var jwtParts = str.split('.'); return jwtParts.length === 3; }; exports.isJWT = isJWT; //trim functions var trimLeft = function (str, chars) { var regex = new RegExp("^[".concat(chars, "]+")); return str.replace(regex, ''); }; exports.trimLeft = trimLeft; var trimRight = function (str, chars) { var regex = new RegExp("[".concat(chars, "]+$")); return str.replace(regex, ''); }; exports.trimRight = trimRight; var trimBoth = function (str, chars) { var leftRegex = new RegExp("^[".concat(chars, "]+")); var rightRegex = new RegExp("[".concat(chars, "]+$")); var trimmedStr = str.replace(leftRegex, ''); trimmedStr = trimmedStr.replace(rightRegex, ''); return trimmedStr; }; exports.trimBoth = trimBoth; // Encode the string using base64 encoding var encrypt = function (str) { var base64Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var result = ''; var i = 0; while (i < str.length) { var char1 = str.charCodeAt(i++); var char2 = i < str.length ? str.charCodeAt(i++) : NaN; var char3 = i < str.length ? str.charCodeAt(i++) : NaN; var byte1 = char1 >> 2; var byte2 = ((char1 & 3) << 4) | (char2 >> 4); var byte3 = ((char2 & 15) << 2) | (char3 >> 6); var byte4 = char3 & 63; var encodedChar3 = isNaN(char2) ? '=' : base64Chars.charAt(byte3); var encodedChar4 = isNaN(char3) ? '=' : base64Chars.charAt(byte4); result += base64Chars.charAt(byte1) + base64Chars.charAt(byte2) + encodedChar3 + encodedChar4; } return result; }; exports.encrypt = encrypt; // Decode the string using base64 decoding var decrypt = function (toDecode) { try { var result = ''; var i = 0; var base64Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var base64Lookup = new Array(256); for (var i_1 = 0; i_1 < base64Chars.length; i_1++) { base64Lookup[base64Chars.charCodeAt(i_1)] = i_1; } while (i < toDecode.length) { var byte1 = base64Lookup[toDecode.charCodeAt(i++)]; var byte2 = base64Lookup[toDecode.charCodeAt(i++)]; var byte3 = base64Lookup[toDecode.charCodeAt(i++)]; var byte4 = base64Lookup[toDecode.charCodeAt(i++)]; var char1 = (byte1 << 2) | (byte2 >> 4); var char2 = ((byte2 & 15) << 4) | (byte3 >> 2); var char3 = ((byte3 & 3) << 6) | byte4; result += String.fromCharCode(char1); if (byte3 !== 64) { result += String.fromCharCode(char2); } if (byte4 !== 64) { result += String.fromCharCode(char3); } } return result; } catch (e) { return "The input is not a valid base64 encoded string"; } }; exports.decrypt = decrypt; // Generate Random Alphanumeric String var getAlphaNumString = function (length) { var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; var result = ''; for (var i = length; i > 0; --i) { result += chars[Math.floor(Math.random() * chars.length)]; } return result; }; exports.getAlphaNumString = getAlphaNumString; // Returns the left substring of the input string var getLeftSubstring = function (inputString, n) { return inputString.slice(0, n); }; exports.getLeftSubstring = getLeftSubstring; //function to replace space to underscore from string function addUnderscore(inputString) { return inputString.replace(/ /g, '_'); } exports.addUnderscore = addUnderscore; //function to remove space from the string function removeSpace(inputString) { return inputString.replace(/\s/g, ''); } exports.removeSpace = removeSpace; //function to remove underscore from string function removeUnderscore(inputString) { return inputString.replace(/_/g, ''); } exports.removeUnderscore = removeUnderscore; // Remove numbers from a string var removeNumber = function (str) { return str.replace(/[0-9]/g, ''); }; exports.removeNumber = removeNumber; // Replace spaces with full stop var addFullstop = function (str) { return str.replace(/\s/g, '.'); }; exports.addFullstop = addFullstop; var generateRandomString = function (length) { var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+'; var result = ''; var charactersLength = characters.length; for (var i = 0; i < length; i++) { result += characters.charAt(Math.floor(Math.random() * charactersLength)); } return result; }; exports.generateRandomString = generateRandomString;