Can anybody advise me how to make a validation rule for Dutch bank accounts?
So far i could only found this on web:
regex = /[0-9]{2}[\\s]{1}[0-9]{2}[\\s]{1}[0-9]{2}[\\s]{1}[0-9]{3}/;
This is my JavaScript:
function dutchBankAccount(input) {
var regex = /[0-9]{2}[\\s]{1}[0-9]{2}[\\s]{1}[0-9]{2}[\\s]{1}[0-9]{3}/;
if(input.value.toString().match(regex) && !(input.value == "")) {
return true;
} else {
input.click();
input.style.border = '2px solid #F20056';
return false;
}
}
And here is my HTML code:
<li><input type="text" id="anum" placeholder="Account Number" autocomplete="off" onkeypress="return isNumberKey(event)" onBlur="isValidAnum()" onFocus="emptyAnum('anum')"/></li>
Later on when I enter a dutch bank account I get error which I'm not supposed to get. So if you know how to solve this please help me.
The regex syntax is incorrect. Try something more like this:
var regex = /[0-9]{2}\s[0-9]{2}\s[0-9]{2}\s[0-9]{3}/;
That matches strings like
32 01 28 192
Two digits followed by a space three times, then three digits. Whether that's what all Dutch bank accounts look like I don't know, though that seems like a small namespace for something like that.
(It occurs to me that /(?:\d{2}\s){3}\d{3}/ should match the same strings and it's a little shorter.)
edit — To elaborate, the regex in the original code has some problems:
The backslashe before each of the "\s" (space) characters is doubled, but it should not be. (That's assuming that Dutch bank account numbers don't actually look like "92\s31\28s\120")
Putting a single character class shortcut ("\s") in square brackets is needlessly redundant
Suffixing a regex element with "{1}" is needlessly redundant too
The real problem was the extra backslash. Also, speaking of needlessly redundant, there's no need to call ".toString()" on the value of an input element "value" attribute, and there's no need to make sure the value isn't the empty string if it has matched the pattern. In this case, an empty string cannot match the pattern, so that test is not necessary. Finally (promise), if you're just testing a regex against a string, the ".test()" method on the RegExp prototype is a little more efficient:
if (regex.test(input.value)) { // matched
// ...
}
Related
Anybody can help me with regular expression which will only accept alphabetical letters from English alphabet and numbers without whitespaces ( ÖÜÕÖ and similar characters + whitespaces will break the HTML link this thing is creating )?
I currently have :
/[A-Za-z ]\S+$/
but this will allow whitespaces and ÖÜÄ and similar at the beggining.
function validatenumber(el) {
var regex = /[A-Za-z ]\S+$/;
if( !regex.test(el.value) ) {
alert('invalid value');
}else{
alert('correct value');
}
}
http://jsfiddle.net/qd7BL/1375/
Here's a fiddle.
Try
/^\w+$/
It'll allow only a non empty string, containing english alphabet letter, both cases, underscore and digits in a string.
/^[A-Za-z0-9]+$/
Solved the problem, although I should probably think is more through as much more elements are allowed in link.
Also, the best solution was to use Slugify, a plugin for jQuery which will make the input correct format.
First of all, I checked possible solutions but couldn't find something that helps to solve my problem.
In short, I have existing logic that gets email from user and tests for few conditions, like make sure it doesn't have apostrophe, double # sign and consecutive dots and etc. The logic is not implemented using regex.
Now, I have new requirement, we need to restrict user from entering non English characters, by restrict I mean try to catch it while user is entering non english character or catch it while value is passed to javascript function that is verifying other conditions above.
So I found some answers here and tried them: here
Here is my code:
<input type="text" id="ctEmailAddress" name="ctEmailAddress" autocomplete="off"
size="40" maxlength="255" value="${userinfo.emailAddress}" oncopy="return false;" onpaste="return false;" onkeypress="suppressNonEng(event)">
And script:
function suppressNonEng(event){
var englishAlphabetAndWhiteSpace = /[A-Za-z ]/g;
var key = String.fromCharCode(event.which);
if (englishAlphabetAndWhiteSpace.test(key)) {
return true;
}
alert ("this is not in English");
return false;
}
So I used js function from link, it is separate from current logic. The problem is, it still allows to pass non english characters, for example french.
The same applies to this function:
function suppressNonEng(event){
var key = event.which;
if(key > 128){
alert("Email address can be entered only in English. Please try again.");
}
}
Again, French letters have no problem going through it.
My question is, how I can make sure that value is english characters only? Should I use regex for that or there is better solution? Please advice. Thanks.
Description
[^\x00-\x7F]+
This regular expression will match any character that is outside ascii 0-127
Example
Live Demo
https://regex101.com/r/qN7eP6/1
Sample text
Here are some sample non-english characters: ü, ö, ß, and ñ.
Sample Matches
[0][0] = ü
[1][0] = ö
[2][0] = ß
[3][0] = ñ
Explanation
NODE EXPLANATION
----------------------------------------------------------------------
[^\x00-\x7F]+ any character except: ascii 0-127 also known as
'\x00' to '\x7F' (1 or more times
(matching the most amount possible))
----------------------------------------------------------------------
I'm writing an application that requires color manipulation, and I want to know when the user has entered a valid hex value. This includes both '#ffffff' and '#fff', but not the ones in between, like 4 or 5 Fs. My question is, can I write a regex that determines if a character is present a set amount of times or another exact amount of times?
What I tried was mutating the:
/#(\d|\w){3}{6}/
Regular expression to this:
/#(\d|\w){3|6}/
Obviously this didn't work. I realize I could write:
/(#(\d|\w){3})|(#(\d|\w){6})/
However I'm hoping for something that looks better.
The shortest I could come up with:
/#([\da-f]{3}){1,2}/i
I.e. # followed by one or two groups of three hexadecimal digits.
You can use this regex:
/#[a-f\d]{3}(?:[a-f\d]{3})?\b/i
This will allow #<3 hex-digits> or #<6 hex-digits> inputs. \b in the end is for word boundary.
RegEx Demo
I had to find a pattern for this myself today but I also needed to include the extra flag for transparency (i.e. #FFF5 / #FFFFFF55). Which made things a little more complicated as the valid combinations goes up a little.
In case it's of any use, here's what I came up with:
var inputs = [
"#12", // Invalid
"#123", // Valid
"#1234", // Valid
"#12345", // Invalid
"#123456", // Valid
"#1234567", // Invalid
"#12345678", // Valid
"#123456789" // Invalid
];
var regex = /(^\#(([\da-f]){3}){1,2}$)|(^\#(([\da-f]){4}){1,2}$)/i;
inputs.forEach((itm, ind, arr) => console.log(itm, (regex.test(itm) ? "valid" : "-")));
Which should return:
#123 valid
#1234 valid
#12345 -
#123456 valid
#1234567 -
#12345678 valid
#123456789 -
Looking for a regex/replace function to take a user inputted string say, "John Smith's Cool Page" and return a filename/url safe string like "john_smith_s_cool_page.html", or something to that extent.
Well, here's one that replaces anything that's not a letter or a number, and makes it all lower case, like your example.
var s = "John Smith's Cool Page";
var filename = s.replace(/[^a-z0-9]/gi, '_').toLowerCase();
Explanation:
The regular expression is /[^a-z0-9]/gi. Well, actually the gi at the end is just a set of options that are used when the expression is used.
i means "ignore upper/lower case differences"
g means "global", which really means that every match should be replaced, not just the first one.
So what we're looking as is really just [^a-z0-9]. Let's read it step-by-step:
The [ and ] define a "character class", which is a list of single-characters. If you'd write [one], then that would match either 'o' or 'n' or 'e'.
However, there's a ^ at the start of the list of characters. That means it should match only characters not in the list.
Finally, the list of characters is a-z0-9. Read this as "a through z and 0 through 9". It's a short way of writing abcdefghijklmnopqrstuvwxyz0123456789.
So basically, what the regular expression says is: "Find every letter that is not between 'a' and 'z' or between '0' and '9'".
I know the original poster asked for a simple Regular Expression, however, there is more involved in sanitizing filenames, including filename length, reserved filenames, and, of course reserved characters.
Take a look at the code in node-sanitize-filename for a more robust solution.
For more flexible and robust handling of unicode characters etc, you could use the slugify in conjunction with some regex to remove unsafe URL characters
const urlSafeFilename = slugify(filename, { remove: /"<>#%\{\}\|\\\^~\[\]`;\?:#=&/g });
This produces nice kebab-case filenemas in your url and allows for more characters outside the a-z0-9 range.
Here's what I did. It works to convert full sentences into a decently clean URL.
First it trims the string, then it converts spaces to dashes (-), then it gets rid of anything that's not a letter/number/dash
function slugify(title) {
return title
.trim()
.replace(/ +/g, '-')
.toLowerCase()
.replace(/[^a-z0-9-]/g, '')
}
slug.value = slugify(text.value);
text.oninput = () => { slug.value = slugify(text.value); };
<input id="text" value="Foo: the old #Foobîdoo!! " style="font-size:1.2em">
<input id="slug" readonly style="font-size:1.2em">
I think your requirement is to replaces white spaces and aphostophy `s with _ and append the .html at the end try to find such regex.
refer
http://www.regular-expressions.info/javascriptexample.html
I have strings which contains thousand separators, however no string-to-number function wants to consume it correctly (using JavaScript). I'm thinking about "preparing" the string by stripping all thousand separators, leaving anything else untoched and letting Number/parseInt/parseFloat functions (I'm satisfied with their behavious otherwise) to decide the rest. But it seems what i have no idea which RegExp can do that!
Better ideas are welcome too!
UPDATE:
Sorry, answers enlightened me how badly formulated question it is. What i'm triyng to achieve is: 1) to strip thousand separators only if any, but 2) to not disturb original string much so i will get NaNs in the cases of invalid numerals.
MORE UPDATE:
JavaScript is limited to English locale for parsing, so lets assume thousand separator is ',' for simplicity (naturally, it never matches decimal separator in any locale, so changing to any other locale should not pose a problem)
Now, on parsing functions:
parseFloat('1023.95BARGAIN BYTES!') // parseXXX functions just "gives up" on invalid chars and returns 1023.95
Number('1023.95BARGAIN BYTES!') // while Number constructor behaves "strictly" and will return NaN
Sometimes I use rhw loose one, sometimes strict. I want to figure out the best approach for preparing string for both functions.
On validity of numerals:
'1,023.99' is perfectly well-formed English number, and stripping all commas will lead to correct result.
'1,0,2,3.99' is broken, however generic comma stripping will give '1023.99' which is unlikely to be a correct result.
welp, I'll venture to throw my suggestion into the pot:
Note: Revised
stringWithNumbers = stringwithNumbers.replace(/(\d+),(?=\d{3}(\D|$))/g, "$1");
should turn
1,234,567.12
1,023.99
1,0,2,3.99
the dang thing costs $1,205!!
95,5,0,432
12345,0000
1,2345
into:
1234567.12
1023.99
1,0,2,3.99
the dang thing costs $1205!!
95,5,0432
12345,0000
1,2345
I hope that's useful!
EDIT:
There is an additional alteration that may be necessary, but is not without side effects:
(\b\d{1,3}),(?=\d{3}(\D|$))
This changes the "one or more" quantifier (+) for the first set of digits into a "one to three" quantifier ({1,3}) and adds a "word-boundary" assertion before it. It will prevent replacements like 1234,123 ==> 1234123. However, it will also prevent a replacement that might be desired (if it is preceded by a letter or underscore), such as A123,789 or _1,555 (which will remain unchanged).
A simple num.replace(/,/g, '') should be sufficient I think.
Depends on what your thousand separator is
myString = myString.replace(/[ ,]/g, "");
would remove spaces and commas.
This should work for you
var decimalCharacter = ".",
regex = new RegExp("[\\d" + decimalCharacter + "]+", "g"),
num = "10,0000,000,000.999";
+num.match(regex).join("");
To confirm that a numeral-string is well-formed, use:
/^(\d*|\d{1,3}(,\d{3})+)($|[^\d])/.test(numeral_string)
which will return true if the numeral-string is either (1) just a sequence of zero or more digits, or (2) a sequence of digits with a comma before each set of three digits, or (3) either of the above followed by a non-digit character and who knows what else. (Case #3 is for floats, as well as your "BARGAIN BYTES!" examples.)
Once you've confirmed that, use:
numeral_string.replace(/,/g, '')
which will return a copy of the numeral-string with all commas excised.
You can use s.replaceAll("(\\W)(?=\\d{3})","");
This regex gets all alpha-numeric character with 3 characters after it.
Strings like 4.444.444.444,00 € will be 4444444444,00 €
I have used the following in a commercial setting, and it has worked often:
numberStr = numberStr.replace(/[. ,](\d\d\d\D|\d\d\d$)/g,'$1');
In the above example, thousands can be marked with a decimal, a comma, or a space.
In some cases ( like a price of 1000,5 Euros) the above doesn't work. If you need something more robust, this should work 100% of the time:
//convert a comma or space used as the cent placeholder to a decimal
$priceStr = $priceStr.replace(/[, ](\d\d$)/,'.$1');
$priceStr = $priceStr.replace(/[, ](\d$)/,'.$1');
//capture cents
var $hasCentsRegex = /[.]\d\d?$/;
if($hasCentsRegex.test($priceStr)) {
var $matchArray = $priceStr.match(/(.*)([.]\d\d?$)/);
var $priceBeforeCents = $matchArray[1];
var $cents = $matchArray[2];
} else{
var $priceBeforeCents = $priceStr;
var $cents = "";
}
//remove decimals, commas and whitespace from the pre-cent portion
$priceBeforeCents = $priceBeforeCents.replace(/[.\s,]/g,'');
//re-create the price by adding back the cents
$priceStr = $priceBeforeCents + $cents;