I have the following code in Titanium to check if user input is non-numeric:
textBox.addEventListener('change', function (e) {
var patt = new RegExp('^\d+(\.\d{1,2})?$','gi');
if (e.value.match(patt) != null) {
//insert action here
}
});
I personally would like to delete non-decimal characters when a user tries to input one. However, in order to do so, I would need to use replace(inversePatt, ""). I would like to know, how do I get the inverse of my regular expression?
to delete non-decimal characters, you should be able to match every:
[^\.\d]
group returned.
([^.\d] should work - here a dot needn't be escaped)
The carat inverts inside brackets.
It basically means "not a dot or a number".
Check out:
http://www.scriptular.com
EDIT:
I think this has your answer:
Restricting input to textbox: allowing only numbers and decimal point
EDIT 2:
You could also use this:
var success = /^\d*\.?\d{0,2}$/.test(input);
as per:
Limiting input field to one decimal point and two decimal places
you can also demand a number before the decimal point like so:
var success = /^\d+\.?\d{0,2}$/.test(input); // uses + instead of *
If you want to handle chars in a key event, something like below should work.
As an acceptance validation, use something like \d to make sure a digit is present.
# ^(?:\.|\d*|\d+\.|\d*\.\d+)$
# "^(?:\\.|\\d*|\\d+\\.|\\d*\\.\\d+)$"
^ # BOL
(?:
\. # dot, or
|
\d* # optional digits (if no digits, matches ^$)
|
\d+ \. # digits and dot
|
\d* \. \d+ # optional digits and dot and digits
)
$ # EOL
Related
I am trying to write a regex to allow a user enter a positive number and to 3 decimal places. My regex looks like this, however, it isn't working as I would like.
/\d*[1-9](\.\d{0,3})?/
This allows the user to enter 1.000 as the smallest number, however, it doesn't allow a user to enter 0.001 which should be the smallest number possible to enter into the input.
Does anyone know what the regex should be to solve this?
Your code has another issue where it can not match 10 since you are not allowing the ones place to be 0.
You need to use some or statements
const re = /(^([1-9]|\d{2,})(\.\d{0,3})?|0\.\d{0,2}[1-9])$/
const tests = ["0.001", "0.1", "0","0.0", "0.000","10.001", "10","11","1"]
tests.forEach(n => console.log(n, re.test(n)))
const re = /^(?!0+(?:\.0+)?$)\d+(?:\.\d+)?$/
const tests = ["0.001", "0.1", "0","0.0", "0.000","10.001", "10","11","1","1.22","1.222"]
tests.forEach(n => console.log(n, re.test(n)))
Explanation:
^ # beginning of string
(?! # negative lookahead, make sure we haven't after:
0+ # 1 or more zero
(?: # start non capture group
\. # a dot
0+ # 1 or more zero
)? # end group, optional
$ # end of string
) # end lookahead
\d+ # 1 or more digits
(?: # start non capture group
\. # a dot
\d+ # 1 or more digits
)? # end group, optionnal
$ # end of string
Personally I would just check for 0 and make the regex a lot simpler, but here is a solution, where the required decimal places can be adjusted by changing {1,3}.
The jist of this regex is that we allow any number greater than two digits , then allow only 1-9 for one digit, then optionally require up to 1 decimal with 1-3 digits afterwards.
const r = /^((([0-9]{2,}){1}|[1-9]{1})(\.[0-9]{1,3}){0,1})$/;
const tests = ['1','2','0','1.001','1.001.1','999.001','9.01','9.0100','abc'];
tests.forEach(t=>console.log(t,r.test(t)));
Another option is to use a negative lookahead to assert from the start of the string what is on the right is neither a dot or zero repeated until the end of the string:
^(?![0.]+$)\d+(?:\.\d{1,3})?$
See a Regex demo
Explanation
^ Start of the string
(?![0.]+$) Negative lookahead to assert what is on the right is not what is listed in the character class repeated 1+ times until the end of the string
\d+ Match 1+ times a digit
(?:\.\d{1,3})? Optional non capturing group which matches a dot and 1+ times a digit
$ End of the string
const tests = ["0.001", "0.1", "0","0.0", "0.000","10.001", "10","11","1","1.22","1.222"]
tests.forEach(n => console.log(parseFloat(n) >= 0.001))
I really think this is being overthought.
The answer is here.
([1-9]\.[0-9][0-9][0-9]|[0]\.[1-9][0-9][0-9]|[0]\.[0][1-9][0-9]|[0]\.[0][0][1-9])
This should match 0.001~9.999
I am using jquery validation plugin for validating my input fields.
I have a field that should accept:
a) letters [a-zA-Z]
b) letters with numbers [a-zA-Z0-9]
c) no special characters
So:
ADFad1334 or 43545SFDDFdf454fgf : is correct, since we have letters and numbers
asdadadASD : is correct, since we have only letters
12312342 : NOT correct, since its only numbers
sdff23424#$ : NOT correct, since there are special characters (in this example # and $)
The code i used is the one below:
$.validator.addMethod("atLeastAletter", function(value) {
return /^[a-zA-Z]*$/img.test(value) || /^[a-zA-Z0-9]*$/img.test(value);
},"Must contain at least a letter and/or number(s). No other characters are allowed");
And then:
$('#RegistrationForm').validate({
rules: {
fieldname: {
atLeastAletter: true
},
.....
The problem with this regular expression is that if the input is only numbers (ex. 3434224), it will accept it and pass validation.
What is the problem?
Thanks in advance.
or this pattern
^(?=\S*[a-zA-Z])[a-zA-Z0-9]+$
Demo
^ # Start of string/line
(?= # Look-Ahead
\S # <not a whitespace character>
* # (zero or more)(greedy)
[a-zA-Z] # Character Class [a-zA-Z]
) # End of Look-Ahead
[a-zA-Z0-9] # Character Class [a-zA-Z0-9]
+ # (one or more)(greedy)
$ # End of string/line
/^\w*[a-zA-Z]+\w*$/
That should match any string with only letters and numbers, but it must contain at least one letter.
sadAddsa // Pass
98463298 // Fail
jdsH98sd // Pass
987Fkjd89 // Pass
jfk!jhj // Fail
kjhgh8768!# // Fail
A8 // Pass
8S // Pass
B // Pass
7 // Fail
B_bkfd86jh // Fail (Using the regex in the edit)
Edit: As Alpha Bravo pointed out. This will match underscores too. If you don't want underscores /^[a-zA-Z0-9]*[a-zA-Z]+[a-zA-Z0-9]*$/will only match letters and numbers, only if it contains one letter.
If you want want to go with all HTML5 look at this fiddle: http://jsfiddle.net/bud68oho/2/
This fiddle uses the required and pattern attributes to validate the form. The required attribute does not allow the form to post if the input is not filled in. The pattern attribute allows you to implement regex for matching. If the input does not meet the requirements of the regex then the form will not post.
The only gotcha with this approach is browser compatibility. Make sure to test this method with your target browsers. The above example works in the latest version of IE and Chrome, I am unable to do any further testing.
/^[a-zA-Z0-9]*$/img.test("1") is true, so just take with two regexp for both:
return /^[a-zA-Z]*$/img.test(value) || (/[a-zA-Z]/img.test(value) && /^[a-zA-Z0-9]*$/img.test(value))
or like this:
return /^[a-zA-Z]*$/img.test(value) || (/^[a-zA-Z0-9]*$/img.test(value) && !/^[0-9]*$/img.test(value))
Notice: If you put i after the regexp (img) you just have to put a-z or A-Z, it's not case sensitive.
Ohter notice: you allow empty strings "" with those regexps.
I think you may need to do a positive alphanumeric check and a negative check for the numeric only case.
$.validator.addMethod("atLeastAletter", function(value) {
return /^[a-zA-Z0-9]+$/img.test(value) && ! /^[0-9]+$/img.test(value)
},"Must contain at least a letter and/or number(s). No other characters are allowed");
I have one text input.
I wrote a regex for masking all special characters except . and -. Now if by mistake the user enters two . (dots) in input, then with the current regex
var valueTest='225..36'
valueTest.match(/[^-.\d]/)
I expected that the number will not pass this condition
How to handle this case. I just want one . (dot) in input field since it is a number.
I think you mean this,
^-?\d+(?:\.\d+)?$
DEMO
It allows positive and negative numbers with or without decimal points.
EXplanation:
^ Asserts that we are at the start.
-? Optional - symbol.
\d+ Matches one or more numbers.
(?: start of non-capturing group.
\. Matches a literal dot.
\d+ Matches one or more numbers.
? Makes the whole non-capturing group as optional.
$ Asserts that we are at the end.
if you just want to handle number ,you can try this:
valueTest.match(/^-?\d+(\.\d+)?$/)
You can probably avoid regex altogether with this case.
For instance
String[] input = { "225.36", "225..36","-225.36", "-225..36" };
for (String s : input) {
try {
Double d = Double.parseDouble(s);
System.out.printf("\"%s\" is a number.%n", s);
}
catch (NumberFormatException nfe) {
System.out.printf("\"%s\" is not a valid number.%n", s);
}
}
Output
"225.36" is a number.
"225..36" is not a valid number.
"-225.36" is a number.
"-225..36" is not a valid number.
Use below reg ex it will meet your requirements.
/^\d+(.\d+)?$/
i'd like to make a javascript validation that will accept all numeric and decimal point format.
For example :
1,000,000.00 is OK
1.000.000,00 is OK
1.000,000.00 is not OK
1.000,000,00 is not OK
1,000.000,00 is not OK
1,000.000.00 is not OK
Based on what i got here is :
/^[1-9][0-9]{0,2}(,[0-9]{3})*(\.[0-9]{2})?$/ is only valid for 1,000,000.00 not for 1.000.000,00
How can i validate both format ?
Updated :
What if the thousand points are not compulsory such as :
1000000.00 is OK or
1000000,00 is OK
Assuming that the decimal part and thousands separators are mandatory, not optional, and that 0 is not an allowed value (as suggested by your examples and your regex):
^[1-9]\d{0,2}(?:(?:,\d{3})*\.\d{2}|(?:\.\d{3})*,\d{2})$
As a verbose regex:
^ # Start of string
[1-9]\d{0,2} # 1-3 digits, no leading zero
(?: # Match either...
(?:,\d{3})* # comma-separated triple digits
\.\d{2} # plus dot-separated decimals
| # or...
(?:\.\d{3})* # dot-separated triple digits
,\d{2} # plus comma-separated decimals
) # End of alternation
$ # End of string
Here is the regex that you want..
^(([1-9]\d{0,2}(((\.\d{3})*(,\d{2})?)|((,\d{3})*(\.\d{2})?)))|(0(\.|,)\d{1,2})|([1-9]\d+((\.|,)\d{1,2})?))$
This is the link that proves that it can handles all cases
http://regexr.com?2tves
The best way to look at a regular expression this big is to blow it up to
a very large font and split it on the alternatives (|)
var s='1,000,000.00';// tests
var result= /(^\d+([,.]\d+)?$)/.test(s) || // no thousand separator
/((^\d{1,3}(,\d{3})+(\.\d+)?)$)/.test(s) || // comma thousand separator
/((^\d{1,3}(\.\d{3})+(,\d+)?)$)/.test(s); // dot thousand separator
alert(result)
Put together its a brute-
function validDelimNum2(s){
var rx=/(^\d+([,.]\d+)?$)|((^\d{1,3}(,\d{3})+(\.\d+)?)$)|((^\d{1,3}(\.\d{3})+(,\d+)?)$)/;
return rx.test(s);
}
//tests
var N= [
'10000000',
'1,000,000.00',
'1.000.000,00',
'1000000.00',
'1000000,00',
'1.00.00',
'1,00,00',
'1.000,00',
'1000,000.00'
]
var A= [];
for(var i= 0, L= N.length; i<L; i++){
A.push(N[i]+'='+validDelimNum2(N[i]));
}
A.join('\n')
/* returned values
10000000=true
1,000,000.00=true
1.000.000,00=true
1000000.00=true
1000000,00=true
1.00.00=false
1,00,00=false
1.000,00=true
1000,000.00=false
*/
The simplest (though not most elegant by far) method would be to write analogous RE for another case and join them with 'OR', like this:
/^(([1-9][0-9]{0,2}(,[0-9]{3})*(\.[0-9]{2})?)|([1-9][0-9]{0,2}(\.[0-9]{3})*(,[0-9]{2})?))$/
UPDATE
A little cleaned up version
/^[1-9]\d{0,2}(((,\d{3})*(\.\d{2})?)|((\.\d{3})*(,\d{2})?))$/
You can replace the , and \. with [,.] to accept either in either location. It would also make 1,000.000.00 OK though.
Its harder to make the regexp behave like that in JavaScript because you can't use lookbehinds
/^(0|0[.,]\d{2}|[1-9]\d{0,2}((,(\d{3}))*(\.\d{2})?|(\.(\d{3}))*(,\d{2})?))$/
/^ #anchor to the first char of string
( #start group
0 # 0
| # or
0[.,] # 0 or 0 followed by a . or ,
\d{2} # 2 digits
| # or
[1-9] #match 1-9
\d{0,2} #0-2 additional digits
( #start group
(,(\d{3}))* # match , and 3 digits zero or more times
(\.\d{2})? # match . and 2 digits zero or one
| # or
(\.(\d{3})* # match . and 3 digits zero or more times
(,\d{2})? # match , and 2 digits zero or one time
) #end group
) #end group
$/ #anchor to end of string
http://jsfiddle.net/AC3Bm/
The box should allow:
Uppercase and lowercase letters (case insensitive)
The digits 0 through 9
The characters, ! # $ % & ' * + - / = ? ^ _ ` { | } ~
The character "." provided that it is not the first or last character
Try
^(?!\.)(?!.*\.$)[\w.!#$%&'*+\/=?^`{|}~-]*$
Explanation:
^ # Anchor the match at the start of the string
(?!\.) # Assert that the first characters isn't a dot
(?!.*\.$) # Assert that the last characters isn't a dot
[\w.!#$%&'*+\/=?^`{|}~-]* # Match any number of allowed characters
$ # Anchor the match at the end of the string
Try something like this:
// the '.' is not included in this:
var temp = "\\w,!#$%&'*+/=?^`{|}~-";
var regex = new RegExp("^["+ temp + "]([." + temp + "]*[" + temp + "])?$");
// ^
// |
// +---- the '.' included here
Looking at your comments it's clear you don't know exactly what a character class does. You don't need to separate the characters with comma's. The character class:
[0-9,a-z]
matches a single (ascii) -digit or lower case letter OR a comma. Note that \w is a "short hand class" that equals [a-zA-Z0-9_]
More information on character classes can be found here:
http://www.regular-expressions.info/charclass.html
You can do something like:
^[a-zA-Z0-9,!#$%&'*+-/=?^_`{|}~][a-zA-Z0-9,!#$%&'*+-/=?^_`{|}~.]*[a-zA-Z0-9,!#$%&'*+-/=?^_`{|}~]$
Here's how I would do it:
/^[\w!#$%&'*+\/=?^`{|}~-]+(?:\.[\w!#$%&'*+\/=?^`{|}~-]+)*$/
The first part is required to match at least one non-dot character, but everything else is optional, allowing it to match a string with only one (non-dot) character. Whenever a dot is encountered, at least one non-dot character must follow, so it won't match a string that begins or ends with a dot.
It also won't match a string with two or more consecutive dots in it. You didn't specify that, but it's usually one of the requirements when people ask for patterns like this. If you want to permit consecutive dots, just change the \. to \.+.