I want allow only numbers and letters and this special caracters (# ‘ () + - ? ! / & * ») in JavaScript.
For this moment i have only numbers and letters allow but i want a special caracters. ( # ‘ () + - ? ! / & * » )
$("#test").keypress(function(e) {
$("#error").remove();
var k = e.keyCode,
$return = ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 49 && k <= 57));
if(!$return) {
$("<span/>",{
"id" : "error",
"html" : "No special caracters allow !"
}).insertAfter($j(this));
return false;
}
});
Thank you in advance for your fast reply.
It would probably be easier to use e.key instead, which will give you the actual character, and not the character code, and then you can check the character against a regular expression that contains the permitted characters:
const isOk = /[a-z0-9#‘)(+-?!\/&*»]/i.test(e.key);
if (!isOk) {
// handle error
}
You can use a regex:
[a-zA-Z0-9\[#()+-?!&*‘»]*
you can test it on https://regex101.com/r/sxrFqq/2
Simple regex:
/[a-z0-9\#\'\(\)\+\-\/\&\*\»]/gi
Related
I'm stuck doing the Caesar cipher problem. For those of you familiar with the problem, I'm not able to wrap around the alphabet, for example if I want to shift the string 'z' by 1, instead of getting 'a', i'll get '['. I know the reason this happens but I'm not able to come up with the proper code. Any help will be appreciated.
Here's my code:
const caesar = function(word, num) {
let solved = ""
num = num % 26;
for (let i = 0; i < word.length ; i++) {
let ascii = word[i].charCodeAt();
if ((ascii >= 65 && ascii <= 90) || (ascii >= 97 && ascii <= 122)) {
solved += String.fromCharCode(ascii + num) ;
} else {
solved += word[i]
}
}
return solved;
}
You need to take the modulus under 26 after subtracting the char code of the first letter of the alphabet and add it back afterward to allow the cipher to wrap around. You will need to handle capital and lowercase letters separately.
const caesar = function(word, num) {
let solved = ""
num = (num%26 + 26) % 26;
for (let i = 0; i < word.length ; i++) {
let ascii = word[i].charCodeAt();
if ((ascii >= 65 && ascii <= 90)) {
solved += String.fromCharCode((ascii - 'A'.charCodeAt(0) + num)%26
+ 'A'.charCodeAt(0)) ;
} else if(ascii >= 97 && ascii <= 122){
solved += String.fromCharCode((ascii-'a'.charCodeAt(0) + num) % 26
+ 'a'.charCodeAt(0));
} else {
solved += word[i]
}
}
return solved;
}
console.log(caesar("abcdefghijklmnopqrstuvwxyzABCDEFGHI", 7));
Do the modulus when you add num to your ascii value. This way you don't scroll past the end of the range (and loop around if you are through the modulus (remainder)).
solved += String.fromCharCode((ascii + num)%26) ;
Out of interest, the ASCII codes for 'A` and 'a' are 0x41 and 0x61 respectively: upper and lower case letters differ by whether bit 0x20 is set (lower case) or not set (upper case).
Hence a bit-bashing algorithm to circular shift ASCII letters and maintain case would be strip the lower case bit, perform the shift, and re-insert the case bit:
"use strict";
function caesarShiftLetter( letter, num) {
let code = letter.charCodeAt(0);
let lowerCaseBit = code & 0x20; // 0 or 0x20
let upperCaseCode = code - lowerCaseBit;
if( upperCaseCode < 0x41 || upperCaseCode >= 0x41 + 26) {
return letter;
}
num = 26 + num%26; // handle large negative shift values
upperCaseCode = ((upperCaseCode - 0x41) + num) % 26 + 0x41;
return String.fromCharCode( upperCaseCode | lowerCaseBit);
}
// to test:
function caesarShiftString( str, num) {
return Array.from(str).map(char => caesarShiftLetter( char, num)).join('');
}
console.log( caesarShiftString(
"abc ... xyz, ABC ... XYZ, I, II, III, IV, V, VI, VII, VIII, IX, X - 1,3,4,5,6,7,9, 10",-22
)
);
This question already has answers here:
Why does a RegExp with global flag give wrong results?
(7 answers)
Closed 5 years ago.
I'm doing a kata that decodes a caesar cipher string into readable text. I'm using RegEx within a map to find special characters and skip over them, but the output is flaky if I have two or more special characters next to each other ', ' or ' :) '. It seems to skip over some special characters.
Can anyone explain what's going on?
I haven't included the changeCharCode function code because I think the issue is in my map.
function decodeString(string) {
const stringArr = string.toLowerCase().split('');
const specialCharacters = /[ .,\/#!$%\^&\*;:{}=\-_`~()]/g;
const codeOfX = 'x'.charCodeAt(0);
const codeOfLastLetter = stringArr[stringArr.length - 1].charCodeAt(0);
const codeShift = codeOfX - codeOfLastLetter;
return stringArr.map((elem) => {
// Special character treatment
return specialCharacters.test(elem) === true ? elem : changecharCode(elem, codeShift);
}).join('').toUpperCase();
}
function changecharCode (letter, codeShift) {
const currentCode = letter.charCodeAt(0);
// Uppercase letters
if ((currentCode >= 65) && (currentCode <= 90))
return letter = String.fromCharCode(((currentCode - 65 + codeShift) % 26) + 65);
// Lowercase letters
else if ((currentCode >= 97) && (currentCode <= 122))
return letter = String.fromCharCode(((currentCode - 97 + codeShift) % 26) + 97);
}
decodeString(' :) ') => ' ) '
decodeString(', ') => ','
Remove the global flag at the end of regex, you have to proceed one character at a time:
function decodeString(string) {
const stringArr = string.toLowerCase().split('');
const specialCharacters = /[ .,\/#!$%\^&\*;:{}=\-_`~()]/;
// here ___^
const codeOfX = 'x'.charCodeAt(0);
const codeOfLastLetter = stringArr[stringArr.length - 1].charCodeAt(0);
const codeShift = codeOfX - codeOfLastLetter;
return stringArr.map((elem) => {
// Special character treatment
return specialCharacters.test(elem) === true ? elem : changecharCode(elem, codeShift);
}).join('').toUpperCase();
}
function changecharCode (letter, codeShift) {
const currentCode = letter.charCodeAt(0);
// Uppercase letters
if ((currentCode >= 65) && (currentCode <= 90))
return letter = String.fromCharCode(((currentCode - 65 + codeShift) % 26) + 65);
// Lowercase letters
else if ((currentCode >= 97) && (currentCode <= 122))
return letter = String.fromCharCode(((currentCode - 97 + codeShift) % 26) + 97);
}
console.log('>'+decodeString(' :) ')+'<');
console.log('>'+decodeString(', ')+'<');
It's the same issue as why-does-my-javascript-regex-test-give-alternating-results. Let's say that the problem was occurred because of g flag which keeps a global state of matching. The solution in your case is supposed to be removing a g flag, once your function proceeds characters one by one, then the g flag is unnecessary.
The problem is in your changecharCode function: if a character code is not within the two ranges that are tested, then the function returns nothing, i.e. undefined. The join you do later on will produce an empty string for each undefined value, so you don't see anything for that in the output.
If you would add a final to changecharCode:
return ' '; // or whatever character you want here
Then the output will have the same number of characters as the input.
I have feature to add wesbsite option in form.
Here user can write domain /url and this domain/url can be in English as well Japanese language as below.
www.google.com
www.南极星.com
I am using following validation for english domains
for (var j = 0; j < dname.length; j++) {
var dh = dname.charAt(j);
var hh = dh.charCodeAt(0);
/*if(dh!='.'){
var chkip=chkip+dh;
}*/
if ((hh > 47 && hh < 59) || (hh > 64 && hh < 91) || (hh > 96 && hh < 123) || hh == 45 || hh == 46) {
var index2 = dname.indexOf('www.');
if (index2 != -1) {
dname = dname.substring(index2 + 4);
if (dname.charAt(0) == '-') {
error_msg = '\'-\'' + window.gt.gettext('not_allowed_in_beginning');
return error_msg;
}
}
if ((j == 0 || j == dname.length - 1) && hh == 45) {
//if(hh == 45){
error_msg = '\'-\'' + window.gt.gettext('not_allowed_in_beginning');
}
} else {
error_msg = window.gt.gettext('cmnscrpt_domname_inval');
}
}
what can I write to validate Japanese domain ?
I think you should use form validator. For example, I prefer to use this one: http://jqueryvalidation.org/validate. You can write your own validation rules depending on language.
For exanple, this is how you can validate car VIN number:
(function() {
jQuery.validator.addMethod("vin", function(value, element) {
return this.optional(element) || /^[a-z0-9]{17}$/i.test(value);
}, "");
})();
There is a very simple method to apply all you RegEx logic(that one can apply easily in English) for any Language using Unicode.
For matching a range of Unicode Characters like all Alphabets [A-Za-z] we can use
[\u0041-\u005A] where \u0041 is Hex-Code for A and \u005A is Hex Code for Z
'matchCAPS leTTer'.match(/[\u0041-\u005A]+/g)
//output ["CAPS", "TT"]
In the same way we can use other Unicode characters or their equivalent Hex-Code according to their Hexadecimal Order (eg: \u0A10 to \u0A1F) provided by unicode.org
Below is a regEx for url validation
url.match(/^(ht|f)tps?:\/\/[a-z0-9-\.]+\.[a-z]{2,4}\/?([^\s<>\#%"\,\{\}\\|\\\^\[\]`]+)?$/)
you just replace a-z, A-Z, 0-9 with the similar characters from Japanese Unicode set and it will work fine. I don't know Japanese :)
I'm working on some validations and can't seem to wrap my head around checking for special chars, none should be used. Currently I grab the value, make an array and check for uppercase and numbers. I need a way to check for special chars as well. Another small issue I found is that it passes an uppercase when a number is entered. Just looking for some direction on how to tackle this.
$('.tooltip').on({
focusin: function(){ //make
var top = $(this).offset().top
var left = $(this).offset().left + $(this).outerWidth()
$('.tip').remove()
$('body').append("<div class='tip' style='top:"+ top +"px;left:"+left+"px;'><div class='arrow'></div></div>")
$('.tip').animate({width: 'show', opacity: 'show'})
$(tipContent).appendTo('.tip')
},
focusout: function(){ //remove
$('.tip').fadeOut(function(){$(this).remove()})
},
keyup: function(){ if (event.keyCode == 16) return //validate
var val = $(this).val()
validate(val.split(""), val);
},
})
function validate(letters, val){
for (var i = 0; i < letters.length; i++){
if( letters[i] === letters[i].toUpperCase() ) { //uppercase check
console.log(letters[i] + ": " + 'Uppercase Passed');
}else{console.log('Uppercase Failed');
}
if( letters.length >= 9 ) { //min limit
console.log(letters[i] + ": " + 'Minimum Limit Passed');
}else{console.log('Minimum Limit Failed');
}
if( parseInt(letters[i]) > 0 ) { //number check
console.log(parseInt(letters[i]) + ' passed');
}else{console.log('at least 1 char failed');
}
}
}
An option might be to use regular expressions, which make your requirements easy to formulate:
function validate(value) {
var regex = /^[A-Z0-9]*$/; // consist only of uppercase letters and digits
var digit = /\d/; // contains a digit
if (regex.test(value) && digit.test(value) && value.length >= 9)
console.log("Test passed");
else
console.log("Test failed");
}
You even could combine them to one regex:
function validate(value) {
return /^(?=.*\d)[A-Z0-9]{9,}$/.test(value);
// | | | |
// string / | consists \ string end
// beginning | of only
// / upper alphabet letters and numbers,
// somewhere ahead at least 9 of them
// comes a digit
}
OK, if you need these steps separately, we should be able to do that. To recognice uppercase letters we just could use the regex [A-Z], but then umlauts etc wouldn't be recognized. If you handled them as special chars, we can easily use this regex:
/^(?=.*\d)(?=.*[A-Z])(?=.*[^A-Za-z0-9]).{9,}$/
| | |
digit uppercase special char
If you don't want that (or the same regexes applied as single-steps), we can test for special characters with the following condition: It is not upper- or lower-caseable, and it is not a digit.
function validation(value) {
var uc = false,
lc = false,
sc = false,
di = false,
len = value.length;
for (var i=0; i<len; i++) {
var letter = value.charAt(i),
isUpper = letter.toUppercase() == letter,
isLower = letter.toLowercase() == letter;
if (isUpper && !isLower)
uc = true;
else if (isLower && !isUpper)
uc = true;
else // isLower && isUpper - no alphabetic character
if (/\d/.test(letter))
di = true;
else
sc = true;
}
return {
someUppercase: uc,
someLowercase: lc,
someSpecial: sc,
someDigit: di,
length: len,
longEnough: len >= 9
};
}
What is the best way to perform an alphanumeric check on an INPUT field in JSP? I have attached my current code
function validateCode() {
var TCode = document.getElementById("TCode").value;
for (var i = 0; i < TCode.length; i++) {
var char1 = TCode.charAt(i);
var cc = char1.charCodeAt(0);
if ((cc > 47 && cc < 58) || (cc > 64 && cc < 91) || (cc > 96 && cc < 123)) {
} else {
alert("Input is not alphanumeric");
return false;
}
}
return true;
}
The asker's original inclination to use str.charCodeAt(i) appears to be faster than the regular expression alternative. In my test on jsPerf the RegExp option performs 66% slower in Chrome 36 (and slightly slower in Firefox 31).
Here's a cleaned-up version of the original validation code that receives a string and returns true or false:
function isAlphaNumeric(str) {
var code, i, len;
for (i = 0, len = str.length; i < len; i++) {
code = str.charCodeAt(i);
if (!(code > 47 && code < 58) && // numeric (0-9)
!(code > 64 && code < 91) && // upper alpha (A-Z)
!(code > 96 && code < 123)) { // lower alpha (a-z)
return false;
}
}
return true;
};
Of course, there may be other considerations, such as readability. A one-line regular expression is definitely prettier to look at. But if you're strictly concerned with speed, you may want to consider this alternative.
You can use this regex /^[a-z0-9]+$/i
Check it with a regex.
Javascript regexen don't have POSIX character classes, so you have to write character ranges manually:
if (!input_string.match(/^[0-9a-z]+$/))
show_error_or_something()
Here ^ means beginning of string and $ means end of string, and [0-9a-z]+ means one or more of character from 0 to 9 OR from a to z.
More information on Javascript regexen here:
https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions
You don't need to do it one at a time. Just do a test for any that are not alpha-numeric. If one is found, the validation fails.
function validateCode(){
var TCode = document.getElementById('TCode').value;
if( /[^a-zA-Z0-9]/.test( TCode ) ) {
alert('Input is not alphanumeric');
return false;
}
return true;
}
If there's at least one match of a non alpha numeric, it will return false.
To match all Unicode letters and numbers you can use a Unicode regex:
const alphanumeric = /^[\p{L}\p{N}]*$/u;
const valid = "Jòhn꠵Çoe日本語3rd"; // <- these are all letters and numbers
const invalid = "JohnDoe3rd!";
console.log(valid.match(alphanumeric));
console.log(invalid.match(alphanumeric));
In the above regex the u flag enables Unicode mode. \p{L} is short for \p{Letter} and \p{N} is short for \p{Number}. The square brackets [] surrounding them is a normal character class, meaning that a character must be either a letter or a number (in this context). The * is "zero or more", you can change this into + (one or more) if you don't want to allow empty strings .^/$ matches the start/end of the string.
The above will suffice most cases, but might match more than you want. You might not want to match Latin, Arabic, Cyrillic, etc. You might only want to match Latin letters and decimal numbers.
const alphanumeric = /^[\p{sc=Latn}\p{Nd}]*$/u;
const valid = "JòhnÇoe3rd";
const invalid = "Jòhn꠵Çoe日本語3rd";
console.log(valid.match(alphanumeric));
console.log(invalid.match(alphanumeric));
\p{sc=Latn} is short for \p{Script=Latin}. \p{Nd} is short for \p{Decimal_Number} and matches decimals. The difference with \d is that \p{Nd} does not only match 5, but also 𝟓, 5 and possibly more.
Checkout the regex Unicode documentation for details, available \p options are linked on the documentation page.
Note that the u flag is not supported by Internet Explorer.
I would create a String prototype method:
String.prototype.isAlphaNumeric = function() {
var regExp = /^[A-Za-z0-9]+$/;
return (this.match(regExp));
};
Then, the usage would be:
var TCode = document.getElementById('TCode').value;
return TCode.isAlphaNumeric()
Here are some notes: The real alphanumeric string is like "0a0a0a0b0c0d" and not like "000000" or "qwertyuio".
All the answers I read here, returned true in both cases. This is not right.
If I want to check if my "00000" string is alphanumeric, my intuition is unquestionably FALSE.
Why? Simple. I cannot find any letter char. So, is a simple numeric string [0-9].
On the other hand, if I wanted to check my "abcdefg" string, my intuition
is still FALSE. I don't see numbers, so it's not alphanumeric. Just alpha [a-zA-Z].
The Michael Martin-Smucker's answer has been illuminating.
However he was aimed at achieving better performance instead of regex. This is true, using a low level way there's a better perfomance. But results it's the same.
The strings "0123456789" (only numeric), "qwertyuiop" (only alpha) and "0a1b2c3d4f4g" (alphanumeric) returns TRUE as alphanumeric. Same regex /^[a-z0-9]+$/i way.
The reason why the regex does not work is as simple as obvious. The syntax [] indicates or, not and.
So, if is it only numeric or if is it only letters, regex returns true.
But, the Michael Martin-Smucker's answer was nevertheless illuminating. For me.
It allowed me to think at "low level", to create a real function that unambiguously
processes an alphanumeric string. I called it like PHP relative function ctype_alnum (edit 2020-02-18: Where, however, this checks OR and not AND).
Here's the code:
function ctype_alnum(str) {
var code, i, len;
var isNumeric = false, isAlpha = false; // I assume that it is all non-alphanumeric
for (i = 0, len = str.length; i < len; i++) {
code = str.charCodeAt(i);
switch (true) {
case code > 47 && code < 58: // check if 0-9
isNumeric = true;
break;
case (code > 64 && code < 91) || (code > 96 && code < 123): // check if A-Z or a-z
isAlpha = true;
break;
default:
// not 0-9, not A-Z or a-z
return false; // stop function with false result, no more checks
}
}
return isNumeric && isAlpha; // return the loop results, if both are true, the string is certainly alphanumeric
}
And here is a demo:
function ctype_alnum(str) {
var code, i, len;
var isNumeric = false, isAlpha = false; //I assume that it is all non-alphanumeric
loop1:
for (i = 0, len = str.length; i < len; i++) {
code = str.charCodeAt(i);
switch (true){
case code > 47 && code < 58: // check if 0-9
isNumeric = true;
break;
case (code > 64 && code < 91) || (code > 96 && code < 123): //check if A-Z or a-z
isAlpha = true;
break;
default: // not 0-9, not A-Z or a-z
return false; //stop function with false result, no more checks
}
}
return isNumeric && isAlpha; //return the loop results, if both are true, the string is certainly alphanumeric
};
$("#input").on("keyup", function(){
if ($(this).val().length === 0) {$("#results").html(""); return false};
var isAlphaNumeric = ctype_alnum ($(this).val());
$("#results").html(
(isAlphaNumeric) ? 'Yes' : 'No'
)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="input">
<div> is Alphanumeric?
<span id="results"></span>
</div>
This is an implementation of Michael Martin-Smucker's method in JavaScript.
// On keypress event call the following method
function AlphaNumCheck(e) {
var charCode = (e.which) ? e.which : e.keyCode;
if (charCode == 8) return true;
var keynum;
var keychar;
var charcheck = /[a-zA-Z0-9]/;
if (window.event) // IE
{
keynum = e.keyCode;
}
else {
if (e.which) // Netscape/Firefox/Opera
{
keynum = e.which;
}
else return true;
}
keychar = String.fromCharCode(keynum);
return charcheck.test(keychar);
}
Further, this article also helps to understand JavaScript alphanumeric validation.
In a tight loop, it's probably better to avoid regex and hardcode your characters:
const CHARS = new Set("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
function isAlphanumeric(char) {
return CHARS.has(char);
}
To check whether input_string is alphanumeric, simply use:
input_string.match(/[^\w]|_/) == null
If you want a simplest one-liner solution, then go for the accepted answer that uses regex.
However, if you want a faster solution then here's a function you can have.
console.log(isAlphaNumeric('a')); // true
console.log(isAlphaNumericString('HelloWorld96')); // true
console.log(isAlphaNumericString('Hello World!')); // false
/**
* Function to check if a character is alpha-numeric.
*
* #param {string} c
* #return {boolean}
*/
function isAlphaNumeric(c) {
const CHAR_CODE_A = 65;
const CHAR_CODE_Z = 90;
const CHAR_CODE_AS = 97;
const CHAR_CODE_ZS = 122;
const CHAR_CODE_0 = 48;
const CHAR_CODE_9 = 57;
let code = c.charCodeAt(0);
if (
(code >= CHAR_CODE_A && code <= CHAR_CODE_Z) ||
(code >= CHAR_CODE_AS && code <= CHAR_CODE_ZS) ||
(code >= CHAR_CODE_0 && code <= CHAR_CODE_9)
) {
return true;
}
return false;
}
/**
* Function to check if a string is fully alpha-numeric.
*
* #param {string} s
* #returns {boolean}
*/
function isAlphaNumericString(s) {
for (let i = 0; i < s.length; i++) {
if (!isAlphaNumeric(s[i])) {
return false;
}
}
return true;
}
const isAlphaNumeric = (str) => {
let n1 = false,
n2 = false;
const myBigBrainString =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
const myHackyNumbers = "0123456789";
for (let i = 0; i < str.length; i++) {
if (myBigBrainString.indexOf(str.charAt(i)) >= 0) {
n1 = true;
}
if (myHackyNumbers.indexOf(str.charAt(i)) >= 0) {
n2 = true;
}
if (n1 && n2) {
return true;
}
}
return n1 && n2;
};
Works till eternity..
Removed NOT operation in alpha-numeric validation. Moved variables to block level scope. Some comments here and there. Derived from the best Micheal
function isAlphaNumeric ( str ) {
/* Iterating character by character to get ASCII code for each character */
for ( let i = 0, len = str.length, code = 0; i < len; ++i ) {
/* Collecting charCode from i index value in a string */
code = str.charCodeAt( i );
/* Validating charCode falls into anyone category */
if (
( code > 47 && code < 58) // numeric (0-9)
|| ( code > 64 && code < 91) // upper alpha (A-Z)
|| ( code > 96 && code < 123 ) // lower alpha (a-z)
) {
continue;
}
/* If nothing satisfies then returning false */
return false
}
/* After validating all the characters and we returning success message*/
return true;
};
console.log(isAlphaNumeric("oye"));
console.log(isAlphaNumeric("oye123"));
console.log(isAlphaNumeric("oye%123"));
(/[^0-9a-zA-Z]/.test( "abcdeFGh123456" ));
Convert string to alphanumeric (Usefull in case of files names)
function stringToAlphanumeric(str = ``) {
return str
.split('')
.map((e) => (/^[a-z0-9]+$/i.test(e) ? e : '_'))
.join('')
}
const fileName = stringToAlphanumeric(`correct-('"é'è-///*$##~~*\\\"filename`)
console.log(fileName)
// expected output "correct_filename"