There is an input field on the JSP where users can enter numbers(negative and positive both).
I've a JS function that checks on each key up event on the input field is not a number, it should replace it with blank.
var txt = $(elem).val();
if(!(txt.match(/^-?[0-9]*$/))) {
$(elem).val(txt.replace(/^-?[0-9]+/g, ''));
}
My if condition is working fine, but I'm not able to create a regex for replacing.
Edit: question was clarified that only numeric values should be accepted
You could just check that the number is < 0 after removing all non-numeric characters:
// remove all non-numeric characters
var txt = $(elem).val().replace(/[^\-0-9]/g, '');
if(parseInt(txt) < 0)){
// negative number
}
To check if a number do this
var txt = $(elem).val();
if (!isNAN(txt) && parseInt(txt) >=0) {
//validate
} else {
// Invalidate
}
Related
I'm trying to use a regular expression to validate the input on a textbox
The expression should allow only numbers, maxmium two decimals, max one comma (,) and one minus symbol in front of the number (optional).
Valid:
0,25
10,2
-7000
-175,33
15555555555555,99
invalid:
9,999
15.03
77,77,77
etc
I'm using ^[-+]?[\d ]+(,\d{0,2})?$
The regex is used in a Jquery code to prevent the user from entering invalid numbers (event.preventDefault()):
$("input[name*='TB_mytbx']").on('keypress', function (event) {
var regex = new RegExp("^[-+]?[\d ]+(,\d{0,2})?$", "g");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
Only a part of the regular expression seems to work.
It works with numbers (It does not allow me to enter letters) but it also won't allow commas (,) and the minus (-).
What am I doing wrong?
Edit
Before I used:
if (focused.val().indexOf(',') != -1) {
var number = (focused.val().split(','));
if (number[1] && number[1].length >= 2) {
event.preventDefault();
return;
}
But this gives annoying behavior. As soon as you enter a number with two digits you can't make edits anymore. For example: you can't change 200,50 to 300,50 or 100 300,50. (You get the point). I hoped that a regex could change that somehow.
I think you're massively over-complicating the regex. This should be plenty:
^-?\d+(,\d\d)?$
^ Start of line,
-? Optional minus sign,
\d+ Followed by a bunch of digits,
(,\d\d)? Followed by a comma and 2 digits, which are all 3 optional.
(alternative: (,\d{2})?)
$ End of line.
var regex = /^-?\d+(,\d\d)?$/;
console.log(regex.test('0,25'));
console.log(regex.test('-175,33'));
console.log(regex.test('15555555555555,99'));
console.log(regex.test('9,999'));
console.log(regex.test('15.03'));
console.log(regex.test('77,77,77'));
There you have a regex to validate the input value.
Now, that block of code can be replaced with this:
$("input[name*='TB_mytbx']").on('keypress', function (event) {
var regex = /^-?\d+(,\d\d)?$/;
var value = $(this).val(); // Use the field's value, instead of the pressed key.
if (!regex.test(value)) {
event.preventDefault();
return false;
}
});
For those of you who wanna know, I solved it using this code
$("input[name*='mythingy']").on('keypress', function (event) {
var theEvent = event || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var value = this.value;
var value = value.replace(value.substring(theEvent.currentTarget.selectionStart, theEvent.currentTarget.selectionEnd), "");
value = [value.slice(0, theEvent.currentTarget.selectionStart), key, value.slice(theEvent.currentTarget.selectionStart)].join('');
var regex = /^[-+]?([\d ]+(,\d{0,2})?)?$/;
if (!regex.test(value)) {
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
});
I can input
0 but not 0123. How do I prevent users not to input 0 at the first position of the input text field?
Let them input it, just trim it when focus changes:
inputElement.onblur = function() {
this.value = this.value.replace(/^0+(?=\d)/,'');
}
Fiddle
Note that it's specifically looking for a digit (\d) after the 0's that it's nuking, so it won't touch the zero in something like 0.123. If you want to get rid of those, too, just change the \d to ., which matches any character whatsoever.
One way to do this is to check the first character in the input using charAt().
Demo
JS:
function check(){
var number = document.getElementById('input').value;
if(number.charAt(0) === 0)
alert('Leading zero in the input.')
else
alert('No leading zero in the input.')
}
EASIER SOLUTION:
For the input, just check the first character like an array:
if(number[0] === '0')
// do something
Demo
Trying to validate if the user has entered a name starting with a letter, is at least 8 characters long, and has at least one number in it. See the code below:-
The first two conditions I have been able to make work, its validating whether or not there's a number within. I have tried to run a function all by itself with just the number validation in it but I cant seem to get it to work. this is my latest attempt to make it work, any help would be greatly appreciated, keep in mind I am a first year student :)
function nameVerify() {
var char1;
var char2;
var index;
var NL = "\n";
var valid = false;
char1 = useNam.substr(0, 1);
char1 = char1.toUpperCase();
char2 = useNam.substr(1);
for (index = 1; index <=useNam.length; index++){
while (!valid) {
if ((char1 <"A" || char1 >"Z") || (useNam.length <8) && (char2 >=0 || char2 <=9)){
alert("alert 1");
useNam = prompt("prompt 2");
char1 = useNam.substr(0, 1);
char1 = char1.toUpperCase();
char2 = useNam.substr(1);
}
else {
valid = true;
alert("Congragulations, you entered it correctly");
}
}
}}
var useNam;
useNam = prompt("prompt 1");
result = nameVerify(useNam);
/**
* #param {string} str name to test
* #return {boolean} true if str is valid
*/
function isValidName(str) {
return /^[a-zA-Z][a-zA-Z0-9]{7,}$/.test(str) && /\d/.test(str)
}
/^[a-zA-Z][a-zA-Z0-9]{7,}$/ tests that it starts with a letter, is at least 8 characters long, and all characters are letters or numbers. /\d/ tests that it contains at least 1 number. See MDN's RegExp documentation for reference in particular about the special characters and the x{n,} syntax described there. If you allow underscores too then you could use /^[a-zA-Z]\w{7,}$/ for the first test.
Try this
valid = myString.match(/\d/).length > 0
This is a regex and will return the first number it matches or an empty array otherwise
I have a very basic RegEx problem. I'm trying to sanitize an input field with a whitelist. I'm trying to only allow numbers and a decimal into my field. If a user types an invalid character, I want to strip it out of the input and replace the input with a clean string.
I can get it working with only numbers, but I can't get the decimal into the allowed pool of characters:
var sanitize = function(inputValue) {
var clean = "",
numbersOnly = /[^0-9]/g; // only numbers & a decimal place
if (inputValue) {
if (numbersOnly.test(inputValue)) {
// if test passes, there are bad characters
for (var i = 0; i < inputValue.length; i++) {
clean += (!numbersOnly.test(inputValue.charAt(i))) ? inputValue.charAt(i) : "";
}
if (clean != inputValue) {
makeInputBe(clean);
}
}
}
};
Working fiddle
Rather than looping your input character by character and validating each character you can do this for basic sanitizing operation:
var s = '123abc.48##'
s = s.replace(/[^\d.]+/g, '');
//=> 123.48
PS: This will not check if there are more than 1 decimal points in the input (not sure if that is the requirement.
I need to add validation to textbox and textarea to validate them against the following rules upon submit (ampersand and apostrophes are allowed). //,./,/.,/*,*.,~,\\
I tried the following code
alert("is valid "+ isValid("mhse sn hs ~"));
function isValid(value)
{
return !/[~//./*././*\\]/i.test(value);
}
the above code will return false because ~ is in this code but if i try / this will return false so i think problem in grouping characters.
1) write one javascript function which eliminates special charactors
function isValid(str){
var iChars = "#$%&"; // type your excepting keys here
var flag = true;
for (var i = 0; i < str.length; i++) {
if (iChars.indexOf(str.charAt(i)) != -1) {
flag = false;
}
}
return flag;
}
2) check your entered value with isValid() function like below
isValid("hye!##~%^&*)");
Answer: if you entered special chars is there, then flag will returns false.
when you escape, you do it carefully :D
for matching * or . literally, you need to escape them
the corrected version will be
/[~/\/\.\/\*\./\.\/\*\\]/.test(".");