javascript regular expression test for 6 digit numbers only. comma seperated - javascript

and so this must pass:
454555, 939999 , 019999 ,727663
its for a user entering 6 digit invoice numbers. it should fail if a number is 5 or 7 digit and not 6. so 1234567, 123456 should fail, as one set is more than 6 numbers.
So far I have :
[0-9]{6}(\s*,*,\s*[0-9]{6})*
which only draw back is that it accepts 7 or more digit numbers. cant figure out if its even possible at this point to do both, test for 6 digits separated by a comma and one or more space, and all the digits have to be only 6 digits and fail if one is not.
any help appreciated. regular expressions are not my forte.
thanks
Norman

You can write it using regex like the function below.
const isPassword = (password: string) => /^\d{6}$/gm.test(password);
And here is an example test file below.
test('should recognize a valid password', () => {
expect(isPassword('123456')).toBe(true);
expect(isPassword('000000')).toBe(true);
});
test('should recognize an invalid password', () => {
expect(isPassword('asdasda1234')).toBe(false);
expect(isPassword('1234567')).toBe(false);
expect(isPassword('a123456a')).toBe(false);
expect(isPassword('11.11.11')).toBe(false);
expect(isPassword('aaaaaa')).toBe(false);
expect(isPassword('eeeeee')).toBe(false);
expect(isPassword('......')).toBe(false);
expect(isPassword('werwerwerwr')).toBe(false);
});

In order to validate the full string you can use this regex.
^(\s*\d{6}\s*)(,\s*\d{6}\s*)*,?\s*$
It works with six digits only, and you have to enter at least one 6 digit number.
It also works if you have a trailing comma with whitespaces.

It's accepting more than six digit numbers because you're not anchoring the text, and for some odd reason you're optionally repeating the comma. Try something like this:
^[0-9]{6}(?:\s*,\s*[0-9]{6})*$
Also note that [0-9] is equivalent to \d, so this can be rewritten more concisely as:
^\d{6}(?:\s*,\s*\d{6})*$

Your regex does not match 7 digits in a row, but it also doesn't enforce that it matches the whole string. It just has to match some substring in the string, so it would also match each of these:
"1234512345612345612345"
"NaNaNaN 123456, 123456 BOOO!"
"!##$%^&*({123456})*&^%$##!"
Just add the start of string (^) and end of string ($) anchors to enforce that the whole string matches and it will work correctly:
^[0-9]{6}(\s*,*,\s*[0-9]{6})*$
Also note that ,*, could be shortened to ,+, and if you only want one comma in a row, just use ,, not ,* or ,+.
You can also replace [0-9] with \d:
^\d{6}(\s*,\s*\d{6})*$

Using only regex:
var commaSeparatedSixDigits = /^(?:\d{6}\s*,\s*)*\d{6}$/;
if (myInput.test(commaSeparatedSixDigits)) console.log( "Is good!" );
This says:
^ - Starting at the beginning of the string
(?:…)* - Find zero or more of the following:
\d{6} - six digits
\s* - maybe some whitespace
, - a literal comma
\s* - maybe some whitespace
\d{6} - Followed by six digits
$ - Followed by the end of the string
Alternatively:
var commaSeparatedSixDigits = /^\s*\d{6}(?:\s*,\s*\d{6})*\s*$/;
I leave it as an exercise to you to decipher what's different about this.
Using JavaScript + regex:
function isOnlyCommaSeparatedSixDigitNumbers( str ){
var parts = srt.split(/\s*,\s*/);
for (var i=parts.length;i--;){
// Ensure that each part is exactly six digit characters
if (! /^\d{6}$/.test(parts[i])) return false;
}
return true;
}

I see a lot of complication here. Sounds to me like what you want is pretty simple:
/^(\d{6},)*\d{6}$/
Then we account for whitespace:
/^\s*(\d{6}\s*,\s*)*\d{6}\s*$/
But as others have noted, this is actually quite simple in JavaScript without using regex:
function check(input) {
var parts = input.split(',');
for (var i = 0, n = parts.length; i < n; i++) {
if (isNaN(+parts[i].trim())) {
return false;
}
}
return true;
}
Tested in the Chrome JavaScript console.

There isn;t any real need for a regexp. Limit the input to only 6 characters, only accept numbers and ensure that the input has 6 digits (not show here). So you would need:
HTML
<input type='text' name='invoice' size='10' maxlength='6' value='' onkeypress='evNumersOnly(event);'>
JavaScript
<script>
function evNumbersOnly( evt ) {
//--- only accepts numbers
//--- this handles incompatabilities between browsers
var theEvent = evt || window.event;
//--- this handles incompatabilities between browsers
var key = theEvent.keyCode || theEvent.which;
//--- convert key number to a letter
key = String.fromCharCode( key );
var regex = /[0-9]/; // Allowable characters 0-9.+-,
if( !regex.test(key) ) {
theEvent.returnValue = false;
//--- this prevents the character from being displayed
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
</script>

Related

Regex for getting only the last N numbers in javascript

I've being trying to generate a regex for this string:
case1: test-123456789 should get 56789
case2: test-1234-123456789 should get 56789
case3: test-12345 should fail or not giving anything
what I need is a way to get only the last 5 numbers from only 9 numbers
so far I did this:
case.match(/\d{5}$/)
it works for the first 2 cases but not for the last one
You may use
/\b\d{4}(\d{5})$/
See the regex demo. Get Group 1 value.
Details
\b - word boundary (to make sure the digit chunks are 9 digit long) - if your digit chunks at the end of the string can contain more, remove \b
\d{4} - four digits
(\d{5}) - Group 1: five digits
$ - end of string.
JS demo:
var strs = ['test-123456789','test-1234-123456789','test-12345'];
var rx = /\b\d{4}(\d{5})$/;
for (var s of strs) {
var m = s.match(rx);
if (m) {
console.log(s, "=>", m[1]);
} else {
console.log("Fail for ", s);
}
}
You can try this:
var test="test-123456789";
console.log((test.match(/[^\d]\d{4}(\d{5})$/)||{1: null/*default value if not found*/})[1]);
This way supports default value for when not found any matching (look at inserted comment inline above code.).
You can use a positive lookbehind (?<= ) to assert that your group of 5 digits is preceeded by a group of 4 digits without including them in the result.
/(?<=\d{4})\d{5}$/
var inputs = [
"test-123456789", // 56789
"test-1234-123456789", // 56789
"test-12345", //fail or not giving anything
]
var rgx = /(?<=\d{4})\d{5}$/
inputs.forEach(str => {
console.log(rgx.exec(str))
})

JavaScript Regex: How to let only 2 decimal floating number through oninput pattern match?

I have an input type="text" with an input event handler attached to it, which i would like to use to overwrite the input.value with a "filtered" result of the users' key presses.
Basically i want to write a regular expression that only allows floating numbers (positive or negative) with (optionally) 2 decimal positions.
Here's a scripted example of what i'm looking for.
If you hit any key while focusing the input in the example above, the input value will be filtered using a combination of regex and JavaScript.
My test input currently looks like this:
<input type="text" id="test" value="-3c.fvbnj23.79.8fbak-cfb436.sdafosd8r32798s.hdf-5kasjfds-gf..">
The input event handler looks like this:
document.getElementById('test').oninput = function(){
var foundDot = false,
str = '';
this.value.replace(/^-|\.(?=\d)|\d*/g, function(match){
if (match === '.' && foundDot === true) {
return;
}
if (match === '.' && foundDot === false) foundDot = true;
str += match;
});
this.value = parseFloat(str).toFixed(2);
}
Is it possible to obtain the same result with a regular expressions only?
Even better, it can be done without regex at all.
Well, okay, one regex. I misunderstood that you wanted to preserve digits within non-numeric strings.
All right, fiiiiine, two regexes. ¯\_(ツ)_/¯
//oninput is too aggressive, it runs on every keystroke making it difficult to type in longer values.
document.getElementById('test').onchange = function(){
// strip non-numeric characters.
// First char can be -, 0-9, or .
// Others can only be 0-9 or .
var val = this.value.replace(/(?!^[\-\d\.])[^\d\.]/g,'');
// strip out extra dots. Here I admit regex defeat and resort to slice-and-dice:
var firstDot = this.value.indexOf('.');
if (firstDot > -1) {
val = val.substr(0,firstDot+1) + val.substring(firstDot+1).replace(/\./g,'')
}
console.log(val);
// Finally the easy part: set the precision
this.value = parseFloat(val).toFixed(2);
}
<input id="test">
I don't know why you can't just use a find/replace on each keystroke.
Find ^([-+]?(?:\d+(?:\.\d{0,2})?|\.\d{0,2})?)
Replace $1
Expanded
^
( # (1 start)
[-+]?
(?:
\d+
(?:
\. \d{0,2}
)?
|
\. \d{0,2}
)?
) # (1 end)

Assistance with a regular expression Javascript

I'm trying to achieve this regular expression check. (1 integer, 3 digits)
Valid:
0.236
0.21
1.231
1.01
Invalid:
12.23
12321
0.21323
I would like to have only 1 digit follow by a decimal with only 0-3 decimal places.
Any help would be great. I have tried this:
^(([0-9]{1})?(?=\.)[0-9]{0,3})|([0-9]{1})$
but no lock.
Edit: I should have added that I'm using a JQuery plugin called inputmask. I would like for the inputmask to only accept my requirement.
To do this with jquery-inputmask, use this
<input id="example2" data-inputmask-regex="/^\d{1}\.\d{0,3}$/" />
And then in your JavaScript file, add this
$(document).ready(function(){
$("#example2").inputmask("Regex");
});
Here is the Regex breakdown
^ - Regex must start with this expression
\d{1} - Exactly 1 digit from 0 to 9
\. - Followed by a period. Important to note that periods must be escaped
\d{0,3} - Followed by 0 to 3 digits
$ - Regex must end with this expression
I tested for all of your examples.
I would like to have only 1 whole number follow by a decimal with only 0-3 decimal places.
By "1 whole number" I take it you mean one digit, as 12 is a single whole number. If so:
\d\.\d{0,3}
That matches a single digit followed by a . followed by zero to three digits. If you want to further assert that it matches the entire string, add anchors to either end:
^\d\.\d{0,3}$
Note that the rules you've given allow for 1., which seems like you may not want. If you don't, then we need to do a bit more work:
^\d(?:\.\d{1,3})?$
That says: One digit optionally followed by a . with 1-3 digits. It has the "whole string" anchors, remove them if you don't want them.
Live Example using that last one:
var input = document.querySelector("input");
var rex = [
/\d\.\d{0,3}/,
/^\d\.\d{0,3}$/,
/^\d(?:\.\d{1,3})?$/
];
input.oninput = input.onpaste = input.onkeypress = updateDisplay;
function updateDisplay() {
rex.forEach(function(r, index) {
var display = document.getElementById("r" + index);
if (!input.value) {
display.innerHTML = "--";
} else if (input.value.match(r)) {
display.innerHTML = "valid";
} else {
display.innerHTML = "INVALID";
}
});
}
<input type="text">
<p><code>/\d\.\d{0,3}/</code> says: <span id="r0"></span></p>
<p><code>/^\d\.\d{0,3}$/</code> says: <span id="r1"></span></p>
<p><code>/^\d(?:\.\d{1,3})?$/</code> says: <span id="r2"></span></p>

Check whether text field contains numbers only and has to be 11 digits

I have this function to check whether the text field contains numbers only, if there are letters in this field then an error should show
//Tel Validate
function is_valid_tel() {
$this = $("#inputTel");
var pattern = new RegExp("^[0-9]*$");
if(pattern.test($this.val())){ // valid
if ($this.closest(".control-group").hasClass("error"))
$this.closest(".control-group").removeClass("error");
$this.siblings(".help-inline").css("display", "none");
return true;
} else { // error
if (!$this.closest(".control-group").hasClass("error"))
$this.closest(".control-group").addClass("error");
$this.siblings(".help-inline").css("display", "block");
return false;
}
}
When i enter letters into the text field i get no error thrown. My jquery/javascript is limited but I thought this would at least work? as the reg exp checks for numbers between 0-9. I would also like to check that if a number is entered then it matches 11 digits
Any help appreciated thanks
use this regular expression ^\d{11}$
old regex
^ begin of string
[0-9]* 0 or more digits
$ end of string
new regex
^ begin of string
\d{11} 11 digits (\d == [0-9])
$ end of string
Try the following RegExp
var pattern = new RegExp("^[0-9]{11}$");
Which is a more readable version of :
var pattern = new RegExp("^\d{11}$");
You will find a handy reference about special characters here.

Javascript regex to match only up to 11 digits, one comma, and 2 digits after it

I have a textbox where I want only allowed up to 11 digits, an optional comma, and two more digits after it. Anything else should not be rendered when the key is pressed into the textbox:
$('#txt').keypress(function (e) {
var code = e.which;
var key = String.fromCharCode(code);
// REGEX TO AVOID CHARS & A DOT (.)
var pattern = /[a-zA-Z]|\./g;
var isMatch = pattern.test(key);
if (isMatch) {
// DO NOT RENDER CHARS & dot
e.preventDefault();
}
});
The above code works when an invalid key is pressed, such as a char or a dot, but does not ensure only one comma and only 2 digits afterwards.
This must match:
12314
123123,44
This must not:
12313,6666
Here is a demo.
UPDATE:
Any digit except numbers and comma must be avoided, so the regex I proposed is not valid since only prevents dots (.).
You should test your complete string, not only the current letter.
$('#txt').keypress(function (e) {
var key = String.fromCharCode(e.which);
var pattern=/^[0-9]{1,11}(,[0-9]{0,2})?$/;
// test this
var txt = $(this).val() + key;
if (!pattern.test(txt)) {
e.preventDefault();
}
});
​
jsfiddle example
This regex will match any string containing 1 up to 11 digits optionally followed by a , and exactly 2 more digits: ^[0-9]{1,11}(,[0-9]{2})?$
Explanation:
^ # Match the start of the string
[0-9]{1,11} # Followed by a maximum of 11 digits
(,[0-9]{2})? # Optionally followed by a comma and 2 more digits
$ # Followed by the end of the string
See it in action here.

Categories

Resources