Javascript regex for plain numbers or numbers ending in percent - javascript

I am in need of a regex that validates only plain numbers, or numbers ending in a percent. I have tried the following:
/(?!\%$)(\D)/
Which I believe looks for any non-digit excluding an ending percent sign. When I test it, it always returns the same result no matter what though:
http://jsfiddle.net/zow37wLq/1/

This regex should work:
/^\d+%?$/
ohaal figured out the problem, but why are you searching for everything that doesn't match instead of searching for what does?

The error is with your code, not with your regex. See line 9 in your code:
// Set New Image Width
$('#photo-width').on('input', function () {
var newWidth = $('#photo-width').attr('value'),
// attempted regex to find any non-digits excluding an ending percent.
reg = /(?!\%$)(\D)/,
charTest = reg.test(newWidth);
// if formatting is incorrect
if (charTest = true) { // <-------------------------- THIS
$('.debug').html('<b>Result</b> Please enter only numbers or percents.');
// if formatting is OK
} else {
$('.debug').html('<b>Result</b> Looks OK');
}
});
The line needs to be needs to be if (charTest == true) {
See updated jsfiddle

Try this:
[0-9]+((px{1}|%{1}))
i usually test my regexp in the following site:
https://www.debuggex.com/

Related

Combine whitelist and blacklist in javascript regex expression

I am having problems constructing a regex that will allow the full range of UTF-8 characters with the exception of 2 characters: _ and ?
So the whitelist is: ^[\u0000-\uFFFF] and the blacklist is: ^[^_%]
I need to combine these into one expression.
I have tried the following code, but does not work the way I had hoped:
var input = "this%";
var patrn = /[^\u0000-\uFFFF&&[^_%]]/g;
if (input.match(patrn) == "" || input.match(patrn) == null) {
return true;
} else {
return false;
}
input: this%
actual output: true
desired output: false
If I understand correctly, one of these should be enough:
/^[^_%]*$/.test(str);
!/[_%]/.test(str);
Use negative lookahead:
(?!_blacklist_)_whitelist_
In this case:
^(?:(?![_%])[\u0000-\uFFFF])*$
Underscore is \u005F and percent is \u0025. You can simply alter the range to exclude these two characters:
^[\u0000-\u0024\u0026-\u005E\u0060-\uFFFF]
This will be just as fast as the original regex.
But I don't think that you are going to get the result you really want this way. JS can only go up to \uFFFF, anything past that will be two characters technically.
According to here, the following code returns false:
/^.$/.test('💩')
You need to have a different way to see if you have characters outside that range. This answer gives the following code:
String.prototype.getCodePointLength= function() {
return this.length-this.split(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g).length+1;
};
Simply put, if the number returned by that is not the same as the number returned by .length() you have a surrogate pair (and thus you should return false).
If your input passes that test, you can run it up against another regex to avoid all the characters between \u0000-\uFFFF that you want to avoid.

syntax error on function to detect non-alphanumeric characters in a value?

I know that there are hundreds( or likely thousands) of questions regarding regex functions in this forum. I have read and consulted several, and by all presumptions, I ought to have the answer, and my function ought to work, but it isn't.
I have tried to build a function, in which one of the checks is for only allowing alpha-numeric characters.
The abridged version of the code is this:
function functionName() {
var x = $("#inputId").val();
//trying to locate any/all non alphanumeric characters & spaces
var regex = /^[^0-9a-zA-Z\s]+$/g
if ( x.indexOf(regex) >= 0 ){
alert("message");
return false;
}
}
Does anyone know where I am going wrong?
Thanks
You shouldn't be using indexOf; you should be using test. That's also a little bit of a funny regex you're using. I've modified it below to match valid strings instead of invalid.
function functionName(){
var x = $("#inputId").val();
var regex = /^[a-zA-Z0-9]+$/g;
if ( x.test(regex) ){
alert("Only contains alphanumeric characters. No punctuation or spaces!");
} else {
return false;
}
}
You regex matches only strings that consist entirely of invalid characters. What you really want is one matching when there is at least one invalid character
var regex = /[^0-9a-zA-Z\s]/;
if (regex.test(x)) ...
Your are missing the final '}'

Javascript regexp using val().match() method

I'm trying to validate a field named phone_number with this rules:
the first digit should be 3 then another 9 digits so in total 10 number example: 3216549874
or can be 7 numbers 1234567
here i have my code:
if (!($("#" + val["htmlId"]).val().match(/^3\d{9}|\d{7}/)))
missing = true;
Why doesnt work :( when i put that into an online regexp checker shows good.
You should be using test instead of match and here's the proper code:
.test(/^(3\d{9}|\d{7})$/)
Match will find all the occurrences, while test will only check to see if at least one is available (thus validating your number).
Don't get confused by pipe. Must end each expression
if (!($("#" + val["htmlId"]).val().match(/^3\d{9}/|/\d{7}/)))
missing = true;
http://jsfiddle.net/alfabravoteam/e6jKs/
I had similar problem and my solution was to write it like:
if (/^(3\d{9}|\d{7})$/.test($("#" + val["htmlId"]).val()) == false) {
missing = true;
}
Try this, it's a little more strict.
.match(/^(3\d{9}|\d{7})$/)

Live control a float input with a regex mask

I've made a function to live control numbers and float numbers.
But it doesn't work properly for float numbers, which have to be like this expression:
// I wish a number like x figures . 3 figures (example : 123456.123)
/^([1-9][0-9]*|0)(\.[0-9]{3})?$/
But this expression makes disappear the dot...
The follow works /(^\d+$)|(^\d+\.\d+$)|[,.]/, but multiple dots can be added:
$('.float_input').live("keypress",function(){inputControl($(this),'double');});
function inputControl(input,format)
{
var value=input.val();
if (format=='int'){expression=/(^\d+$)|(^\d+\.\d+$)/;}
else if (format=='double'){expression=/(^\d+$)|(^\d+\.\d+$)|[,.]/;}
var values=value.split("");
var update="";
for(id in values)
{
if (expression.test(values[id])==true && values[id]!='')
{
// also replace ',' by '.'
update=update+''+values[id].replace(',','.');
}
}
input.val(update);
}
So I have multiple dots or no dot, it makes me nutty because I'm sure to be near the solution.
EDIT > SOLUTION
Ouch, thanks for the help about regex, I've found the solution!
Two tests were necessary:
one for the characters test, tested one by one
another to test the entire input while entering characters
This is the final script, which works like a flower, and I share it just for you:
$('.numeric_input').live("keyup",function(){inputControl($(this),'int');});
$('.float_input').live("keyup",function(){inputControl($(this),'float');});
function inputControl(input,format)
{
var value=input.val();
var values=value.split("");
var update="";
var transition="";
if (format=='int'){
expression=/^([0-9])$/;
finalExpression=/^([1-9][0-9]*)$/;
}
else if (format=='float')
{
var expression=/(^\d+$)|(^\d+\.\d+$)|[,\.]/;
var finalExpression=/^([1-9][0-9]*[,\.]?\d{0,3})$/;
}
for(id in values)
{
if (expression.test(values[id])==true && values[id]!='')
{
transition+=''+values[id].replace(',','.');
if(finalExpression.test(transition)==true)
{
update+=''+values[id].replace(',','.');
}
}
}
input.val(update);
}
This regex
(/(^\d+$)|(^\d+.\d+$)|[,.]/)
should match
1111111 per the (^\d+$)
or 111111.11111 per the (^\d+.\d+$)
or the comma followed by any character, and it could be anywhere in the expression.
I'm suspecting your regex should be
Note that I've escaped the final period. That would match a comma or a period
/(^\d+[,\.]{0,1}\d{3})/
may be exactly what you want based on clarifications in the comments
[-+]?[0-9]*\.?[0-9]+
would also work
NOTE: You can simplify your regex life tremendously by using Roy Osherove's Regulazy or the tool Regex Buddy.
You want arbitrary amount of digits behind the decimal point (comma or period)?
What's wrong with:
/^([1-9][0-9]*|0)([\.,][0-9]+)?$/
I switched out the {3} for + and \. for [\.,]

Using Regular Expressions with Javascript replace method

Friends,
I'm new to both Javascript and Regular Expressions and hope you can help!
Within a Javascript function I need to check to see if a comma(,) appears 1 or more times. If it does then there should be one or more numbers either side of it.
e.g.
1,000.00 is ok
1,000,00 is ok
,000.00 is not ok
1,,000.00 is not ok
If these conditions are met I want the comma to be removed so 1,000.00 becomes 1000.00
What I have tried so is:
var x = '1,000.00';
var regex = new RegExp("[0-9]+,[0-9]+", "g");
var y = x.replace(regex,"");
alert(y);
When run the alert shows ".00" Which is not what I was expecting or want!
Thanks in advance for any help provided.
strong text
Edit
strong text
Thanks all for the input so far and the 3 answers given. Unfortunately I don't think I explained my question well enough.
What I am trying to achieve is:
If there is a comma in the text and there are one or more numbers either side of it then remove the comma but leave the rest of the string as is.
If there is a comma in the text and there is not at least one number either side of it then do nothing.
So using my examples from above:
1,000.00 becomes 1000.00
1,000,00 becomes 100000
,000.00 is left as ,000.00
1,,000.00 is left as 1,,000.00
Apologies for the confusion!
Your regex isn't going to be very flexible with higher orders than 1000 and it has a problem with inputs which don't have the comma. More problematically you're also matching and replacing the part of the data you're interested in!
Better to have a regex which matches the forms which are a problem and remove them.
The following matches (in order) commas at the beginning of the input, at the end of the input, preceded by a number of non digits, or followed by a number of non digits.
var y = x.replace(/^,|,$|[^0-9]+,|,[^0-9]+/g,'');
As an aside, all of this is much easier if you happen to be able to do lookbehind but almost every JS implementation doesn't.
Edit based on question update:
Ok, I won't attempt to understand why your rules are as they are, but the regex gets simpler to solve it:
var y = x.replace(/(\d),(\d)/g, '$1$2');
I would use something like the following:
^[0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)$
[0-9]{1,3}: 1 to 3 digits
(,[0-9]{3})*: [Optional] More digit triplets seperated by a comma
(\.[0-9]+): [Optional] Dot + more digits
If this regex matches, you know that your number is valid. Just replace all commas with the empty string afterwards.
It seems to me you have three error conditions
",1000"
"1000,"
"1,,000"
If any one of these is true then you should reject the field, If they are all false then you can strip the commas in the normal way and move on. This can be a simple alternation:
^,|,,|,$
I would just remove anything except digits and the decimal separator ([^0-9.]) and send the output through parseFloat():
var y = parseFloat(x.replace(/[^0-9.]+/g, ""));
// invalid cases:
// - standalone comma at the beginning of the string
// - comma next to another comma
// - standalone comma at the end of the string
var i,
inputs = ['1,000.00', '1,000,00', ',000.00', '1,,000.00'],
invalid_cases = /(^,)|(,,)|(,$)/;
for (i = 0; i < inputs.length; i++) {
if (inputs[i].match(invalid_cases) === null) {
// wipe out everything but decimal and dot
inputs[i] = inputs[i].replace(/[^\d.]+/g, '');
}
}
console.log(inputs); // ["1000.00", "100000", ",000.00", "1,,000.00"]

Categories

Resources