I am trying to validate credit card number which may contain four tests of alphanumeric characters, separated by hyphens (-) or without hyphens. Not using regExp.
I have tried different ways but I can't figure out how to do it properly.
That's what I have done so far:
function isCredit(input) {
var i, code;
//if input.length > 19, stop execution
if(input.length > 19) return false;
for(i = 0; i < input.length; i++) {
code = input.charCodeAt(i);
//Matches to only numbers and Capital letters
if((code > 47 && code < 58) && (code > 64 && code < 91)) {
//if every 5th character is "-"
if((input.slice(4, 5) === "-") && (input.slice(9, 10) === "-") &&(input.slice(14, 15) === "-")) {
return true;
}
}
return false;
}
}
isCredit("12A4-56H8-43K6-36U3"); // returns true;
isCredit("4427A693CF324D14"); // returns true;
isCredit("----------------"); // returns false;
Any help and guidance appreciated!
I'm not exactly clear on your requirements. Here I'm assuming "12A556H8-43K636U3" is a valid card number if you allow hyphen omissions.
function isAlphaNum(ch) {
var code = ch.charCodeAt(0);
return ((code > 47 && code < 58) || (code > 64 && code < 91));
}
function isCard(str) {
var char, i = 0, x = [1,1,1,1,0,1,1,1,1,0,1,1,1,1,0,1,1,1,1];
while (char = str[i++]) {
if (x[0] == undefined) {
return false;
}
if (isAlphaNum(char)) {
if (x[0]) {
x.shift();
} else {
x.splice(0,2);
}
} else if (char == '-') {
if (!x[0]) {
x.shift();
} else {
return false;
}
} else {
return false;
}
}
return x[0] == undefined;
}
Related
I am new to javascript I'm trying to check user entered the alphabet or a number.
if the user enters "A" it shows Alphabet it's ok but if the user enters "1" I want to show Number but its show alphabet.
where i done wrong.
Thanks Advance
function CHECKCHARATCTER(Letter) {
if (Letter.length <= 1) {
if ((64 < Letter.charCodeAt(0) < 91) || (96 < Letter.charCodeAt(0) < 123)) {
return "Alphabhate";
}
else if (47 < Letter.charCodeAt(0) < 58) {
return "NUMBER";
}
else { return "Its NOt a NUMBER or Alphabets"; }
}
else { return ("Please enter the single character"); }
}
a = prompt("enter the number or Alphabhate");
alert(typeof (a));
b = CHECKCHARATCTER(a);
alert(b);
Here:
if (64 < Letter.charCodeAt(0) < 91) //...
JS isn't Python. You can't simply do a < b < c, you need to explicitly use the logical && operator: (a < b) && (b < c).
You can use regular expressions. Please have a look at regular expressions. It will be very helpful.
function checkAlphaNum(char) {
let alphaReg = new RegExp(/^[a-z]/i);
let numReg = new RegExp(/^[0-9]/);
if(alphaReg.test(char)) {
return "ALPHABET";
} else if(numReg.test(char)) {
return "NUMBER";
} else {
return "OTHER";
}
}
console.log("Output : ", checkAlphaNum('A'));
console.log("Output : ", checkAlphaNum(1));
I modified you conditions as it's shown in the following code. Also you can check it out here
function CHECKCHARATCTER(Letter){
if (Letter.length <= 1)
{
if (Letter.toUpperCase() != Letter.toLowerCase()) {
return "Alphabet";
}
else if (!isNaN( Letter)) {
return "Number";
} else{
return "Its Not a Number or Alphabet";
}
}
else {
return("Please enter the single character");
}
}
input = prompt("enter the Number or Alphabet");
output = CHECKCHARATCTER(input);
alert(output);
I have my own function to check phone number:
function isPhoneNumber(phone) {
var regexForPhoneWithCountryCode = /^[0-9+]*$/;
var regexForPhoneWithOutCountryCode = /^[0-9]*$/;
var tajikPhone = phone.substring(0,4);
if(tajikPhone == "+161" && phone.length !== 13) {
return false;
}
if(phone.length == 9 && phone.match(regexForPhoneWithOutCountryCode)) {
return true;
} else if(phone.length > 12 && phone.length < 16 && phone.match(regexForPhoneWithCountryCode)) {
return true;
} else return false;
}
My function also work, but not completely correct.
Rules for validate phone number:
Max length: 13
Min length: 9
When max length == 13:
Contain only: 0-9+
First charackter match: +
3 charackters after "+" must be: 161
When max length == 9:
Contain only: 0-9
Example valid numbers:
+161674773312
674773312
A really simple method you could use is:
function isPhoneNumber(phone) {
if (phone.match(/^(?:\+161)?\d{9}$/) {
return true;
} else {
return false;
}
}
I am figuring out how to validate hexadecimal color ("#1234a6" and "#1cf") without using regExp. Can anyone please tell me why my code is not working properly
function checkHex(input)
{
var i, code, len;
// If first letter isn't "#" stop executing
if(input.charAt(0) !== "#") return false;
code = input.charCodeAt(i);
for(i = 1; len = input.length, i < len; i++) {
if(len == 3 || len == 6 ) {
if((code > 47 && code < 58) && (code > 96 && code < 103)) {
return true;
}
}
return false;
}
}
checkHex("#1234a6"); // returns false; which should be true;
Thank you.
No loop or charcodeat required
function checkHex(input) {
var check, code, len;
if(typeof input == 'string') { // check it's a string
if(input[0] === "#") { // and it starts with #
len = input.length;
// if (len === 4 || len === 7 || len == 5 || len == 9) { // 5 and 9 for #RGBA and #RRGGBBAA
if (len === 4 || len === 7) { // and it's 4 or 7 characters
input = input.toLowerCase(); // convert to lower case
// parse it as hex and output as hex with # prefix
check = '#' + ('00000000' + parseInt(input.substr(1), 16).toString(16)).substr(1 - len);
// check it's the same number
return check === input;
}
}
}
// all other conditions fall thru to here
return false;
}
console.log(checkHex("#1234a6")); // true
console.log(checkHex("1234a6")); // false
console.log(checkHex("#1234")); // false
console.log(checkHex("#12345t")); // false
console.log(checkHex("#aBc")); // true
console.log(checkHex("#000")); // true
console.log(checkHex("#00001")); // false
console.log(checkHex("#000001")); // true
Let me break down the check = line into it's constituent parts
check = '#' + // start with a '#'
('00000000' + // some leading zeros for profit
parseInt(input.substr(1), 16) // parse the text as a HEX integer - that's the 16 argument
.toString(16) // now, back to a string, in HEX, again 16 argument does that
).substr(1 - len); // we take the last (len-1) characters to match the input length less 1 (the # is the first line)
To break down where your code went wrong
function checkHex(input) {
var i, code, len;
// If first letter isn't "#" stop executing
if(input.charAt(0) !== "#") return false;
// next line should be inside the loop
code = input.charCodeAt(i);
for(i = 1; len = input.length, i < len; i++) {
// you should check for length being 4 or 7, and this check should be outside the loop
if(len == 3 || len == 6 ) {
// a value can not be between 47 and 48 AND between 96 and 103 - so this is never true
if((code > 47 && code < 58) && (code > 96 && code < 103)) {
// returning in a for loop exits the function, so even fixing all of the above this would return true if the first digit was valid
return true;
}
}
return false;
}
}
to do the above loop correctly
function checkHex(input) {
var i, code, len;
if (input[0] === "#") {
len = input.length
if (len == 4 || len == 7 ) {
input = input.toLowerCase(); // rgb hex values are valid in either upper or lower case
for(i = 1; i < len; i++) {
code = input.charCodeAt(i);
// note the ! and the || in the next line
// we want to check that the digit is NOT in 0123456789 OR abcdef
if (!((code > 47 && code < 58) || (code > 96 && code < 103))) {
return false; // not a hex digit, so return false
}
}
//loop has made it all the way through, so it's correct
return true;
}
}
return false;
}
console.log(checkHex("#1234a6")); // true
console.log(checkHex("1234a6")); // false
console.log(checkHex("#1234")); // false
console.log(checkHex("#12345t")); // false
console.log(checkHex("#aBc")); // true
console.log(checkHex("#000")); // true
console.log(checkHex("#00001")); // false
console.log(checkHex("#000001")); // true
Okay so here's a simple code snippet that does that correctly without loops etc.
You'll notice that I created a lambda function in there to deal with s starting with a #
This is to allow you to expand the notion to deal with specifications like rgb(1,2,3) and rgba(4, 5, 6, 1) etc.
isRGB = function(s) {
if(typeof(s) !== "string")
return false;
if(s[0] === '#')
return (function(hexStr) {
if(hexStr.length != 3 && hexStr.length != 6)
return false;
return !isNaN(Number("0x" + hexStr));
})(s.substr(1));
return false;
}
console.log(isRGB('#01a5'));
console.log(isRGB('#0a5'));
console.log(isRGB('#0a5029'));
You may directly parse the value to number and check against the base 10 integer value:
function checkHex(input) {
/*
1193126 = 0x1234a6
463 = 0x1cf
1166591 = 0x11ccff
*/
if(input.charAt(0) == '#') {
var intNumber = Number(input.replace("#","0x"));
return isNaN(intNumber) ? false : (intNumber == 1193126 || intNumber == 463 || intNumber == 1166591);
} else {
return false;
}
}
I am trying to solve a JavaScript coding exercise and my code is wrong and I can't see why.
The task is:
take a string and if every letter in the string is surrounded by a '+' sign, return true, otherwise return false.
It works for most cases but doesn't work for '=a+' for example and I don't understand why. Could someone explain?
function SimpleSymbols(str) {
for (var i = 0; i < str.length; i++) {
if (str[0].match(/[a-z]/i) || str[str.length - 1].match(/[a-z]/i)) {
return false;
} else {
if (str[i].match(/[a-z]/i) && (str[i - 1] !== "+" || str[i + 1] !== "+")) {
return false;
} else {
return true;
}
}
}
}
SimpleSymbols(readline());
The issue is the inner else clause. It should be elimninated, and instead, the function should return true after the for block.
function SimpleSymbols(str) {
for (var i = 0; i < str.length; i++) {
if (str[0].match(/[a-z]/i) || str[str.length - 1].match(/[a-z]/i)) {
return false;
} else {
if (str[i].match(/[a-z]/i) && (str[i - 1] !== "+" || str[i + 1] !== "+")) {
return false;
}
}
}
return true;
}
Could you match against this and return the result:
^\+(?:[a-z]\+)*$
https://regex101.com/r/1zXUJD/1
looks for strings that start with a '+' and then any number of [a-z]+ after that until the end of the string.
I need to check if test contains at least 2 letters, like SC.
var test='SC129h';
if (test.containsalphabets atleast 2) {
alert('success');
}
else {
alert('condition not satisfied for alphabets');
}
Create a regular expression to match all characters in the string that are in the alphabet, and count them.
var test = "SC129h";
if((test.match(/[A-Za-z]/g).length || 0) >= 2) {
alert("success");
}
Alternatively, to be more efficient, do a linear search and check the ASCII code. This can avoid scanning the whole string.
var test = "SC129h";
var matches = 0;
for(var i = 0; i < test.length; i++) {
if((test[i] >= 'a' && test[i] <= 'z') || (test[i] >= 'A' && test[i] <= 'Z')) {
matches++;
if(matches > 2) break;
}
}
if(matches >= 2) {
// Do something here
}
You should be using the RegEx pattern:
/([A-Za-z])/g
And check for the length of the test to be more than 2.
var test = 'SC129h';
var match = test.match(/([A-Za-z])/g);
if (match && match.length >= 2) {
alert('success');
}
else {
alert('condition not satisfied for alphabets');
}
Better Version
var test = 'SC129h';
var match = test.match(/([A-Za-z])/g);
if (match && match[1]) {
alert('success');
}
else {
alert('condition not satisfied for alphabets');
}
You can also remove all non alphabetic characters then checking for the length of the result.
'SC129h'.replace(/[^a-z]/gi,'').length > 1
you could do var match = /[a-z]{2,}/gi.test(test) with would return a Boolean