RegEx in Javascript to allow negative decimal input to a text field - javascript

I have a requirement wherein i need to allow plus/minus sign in the beginning followed by a decimal number which allows only one dot in it in a text field input in html.
Bascially the text field should allow normal integer numbers and decimal numbers and also negative integer and negative decimal numbers. The plus and minus sign should be allowed only in the beginning (first character) and it's optional. Also should allow any number of decimal places (ex: -12.12345 etc) but only one decimal (dot) in the entry.
Digits allowed are: 1, + 1, -1, .1, +1.1, -1.1, -.12, +.12, 123.4456, -123.345, +123.345 etc
Any help is highly appreciated.
I'm using below regex for the above requirement.
var integerOnly = /[\+\-0-9\.]/g;
and below script (which i obtained from some other thread with slight modification) to validate it .
function restrictInput(myfield, e, restrictionType, checkdot){
if (!e) var e = window.event
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var character = String.fromCharCode(code);
alert("1 " + character);
// if user pressed esc... remove focus from field...
if (code==27) { this.blur(); return false; }
//alert("2");
// ignore if the user presses other keys
// strange because code: 39 is the down key AND ' key...
// and DEL also equals .
if (!e.ctrlKey && code!=9 && code!=8 && code!=36 && code!=37 && code!=38 && (code!=39 || (code==39 && character=="'")) && code!=40) {
alert("3");
if (character.match(restrictionType)) {
alert("4");
if(checkdot == "checkdot" & '-' != character & '+' != character){
alert("5");
return !isNaN((myfield.value.toString()==''? '0':myfield.value.toString())+character );
} else {
return true;
}
} else {
return false;
}
}
}
Here is how the script is called.
<input type="text" id="db" width="3" value="" onkeypress="return restrictInput(this, event, integerOnly, 'checkdot');"/>
It works fine except for few cases like:
It allows +/- any place any number of times. My requirement is to allow only at the beginning.
I tried to modify the regex as below.
var integerOnly = /[\+\-]?[0-9\.]/g;
In that case, it doesn't match the expression. It doesn't reach alert 4.
One thing is it allows only one decimal places and not more than one.
Can someone help me to modify my regular expression so as to allow only +/- in the beginning and only once.
Thank you.

Instead of playing with regex, validate your text using isNumber function as follows
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}

I think that you want something like this:
^[-+]?(\d+\.?|\d*\.\d+)$
As the digits before the decimal separator or the digits after are optional (e.g. 1. or .1) but noth both, you need to handle the cases separately.

var test_ary = ['1', '+1', '-1', '.1', '+1.1', '-1.1', '-.12', '+.12', '123.4456', '-123.345', '+123.345'];
var reg = /^[\+\-]?(?:\.?\d+|\d+\.?\d+)$/;
var i;
for ( i = 0; i < test_ary.length; i = i + 1) {
console.log(reg.test(test_ary[i]));
}
you can also try this, with test case :)

I took 'niksvp' script and modified a bit to meet my requirement.
The below script works for all types of +/- decimal numbers. ex: 1.1, +1.1, -1.1, .1, -.1, +.1, 1, -1, +1, 123.345, +123.345, -123.345 etc
function isNumber(myfield, e) {
if (!e) var e = window.event
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var character = String.fromCharCode(code);
var n = myfield.value.toString()==''? '0':myfield.value.toString();
// this is required to allow numbers of this format
// -1.1, + 1.1, .1, -.1, +.1 etc
if(n == '-' | n == '+' | n== '.') {
n +=0;
}
if(n.length > 1) {
n = n.toString() + character;
}
return !isNaN(parseFloat(n)) && isFinite(n);
}
Thanks to all for your help.

Related

How to create mask for a float type input in ES6?

The rule of input is simple:
Calculation of student grade ...
The inserted notes must go from 0.0 to 10.0 ...
The user can also enter the "f" character to say that the student was missing ...
I was able to block the characters and use the regex to generate the "POINT".
What are the problems:
Input is not generating the regex correctly, I need to enter 3 characters instead of two for it to insert the point
When entering the character f it should block the digit of numbers and vice versa if it enters a number first
It is letting you enter more than 3 characters in the input, I know this is in the input attribute, however I left it as 3 to be able to insert the point.
Functions:
blockCharactersTwo(_event){
let keyPressed = _event.charCode;
(keyPressed >= 48 && keyPressed <= 57 || keyPressed === 46 || keyPressed === 102) ? null : _event.preventDefault();
}
convertToDecimal(_element){
_element.value = _element.value.replace(/(\d{1})(\d{1,2})$/,"$1.$2") // Insere o PONTO ANTES dos ĂšLTIMOS 2 digitos
}
input and output sample:
1) 80 => 8.0
2) 01 => 0.1
3) number => block caracter "F"
4) "f" => block number
5) "f" => if you type "f" do not enter any more characters and not even "f".
I would do this with a handler for the keydown event, and a separate one for reformatting, to make it easier. The regex /^([fF]{1}|\d{1}\.\d{1}|10\.00?)$/ on regex101.com shows how it works. The allNumbersRe expression just looks for the correct pattern for three numbers.
The trick here is that there is no way to prevent them from entering a value > 10.0, if you want to be able to allow them to enter 100 and format it as 10.0, since the number 100 > 10.0. So, I split the formatting out of the keydown handler and added a blur handler to do the formatting. It also validates that the formatted number is less than or equal to 10.0. Here I'm using HTML5 constraint validation for ease of implementation.
Another thing of note is that I'm using KeyboardEvent.key, which is a relatively new addition to the standard. It will return strings like "Delete" and "Backspace" for keys that produce non-printable characters. In this case, I'm assuming that any keys that do that are okay to allow (you presumably want to be able to delete the value).
document.querySelector('.grade').addEventListener('keydown', function (e) {
const char = e.key;
let newValue = e.target.value;
if (char.length > 1) {
return true;
} else {
newValue += char;
}
const perfectRegex = /^([fF]{1}|\d{1}\.\d{1,2}|10\.00?)$/;
const allNumbersRe = /^(\d{1})(\d{1,2})$/;
const numbersAndDecRe = /^[\d\.]{1,4}$/;
if (!perfectRegex.test(newValue) &&
!allNumbersRe.test(newValue) &&
!numbersAndDecRe.test(newValue) &&
newValue.length > 0) {
e.preventDefault();
}
});
document.querySelector('.grade').addEventListener('blur', function (e) {
const tenRe = /^100$/;
const allNumbersRe = /^(\d{1})(\d{1,2})$/;
const newValue = e.target.value;
e.target.setCustomValidity("");
if (tenRe.test(newValue)) {
e.target.value = "10.0";
} else if (allNumbersRe.test(newValue)) {
e.target.value = newValue.replace(allNumbersRe, "$1.$2");
}
if (parseFloat(e.target.value) > 10.0) {
e.target.setCustomValidity("The value cannot be more than 10.0");
e.preventDefault();
}
});
input:invalid { border-color: red; }
<input type="text" class="grade" maxlength="4">

Using JQuery, how do I check that a string is a letter character followed by eight digits?

I'm a beginner writing JQuery to add to a customization form website. Most of the options are drag and drop, but I have to write custom jquery in some cases.
For this, I've been able to figure out to validate a nine-character string so that an error message is presented if the string is NOT 9 characters long, and if it starts with anything other than "B", "E", or "N."
However, it also needs to check and make sure that all other characters after the first is a digit. For instance, an acceptable user input would be e00012345.
What is the simplest way to do this?
// this validation will check to make sure that an accepted value is entered into a field.
// currently, the validation is not perfect. Ideally, the value would start with a specific character (n, b or e) and 8 digits. Right now it just must start with n, b or e and be 9 characters long.
$(function() {
// for the Missouri Business Number -- on blur, if the value is 9 characters long and starts with b, e, or n (uppoer or lower case), then the input is valid. Otherwise, error messages appear.
$("input#id_wrT4duNEOW").blur(function() {
if (
(($("#id_wrT4duNEOW").val().startsWith("b")) &&
($("#id_wrT4duNEOW").val().length == 9)) ||
(($("#id_wrT4duNEOW").val().startsWith("e")) &&
($("#id_wrT4duNEOW").val().length == 9)) ||
(($("#id_wrT4duNEOW").val().startsWith("n")) &&
($("#id_wrT4duNEOW").val().length == 9)) ||
(($("#id_wrT4duNEOW").val().startsWith("B")) &&
($("#id_wrT4duNEOW").val().length == 9)) ||
(($("#id_wrT4duNEOW").val().startsWith("E")) &&
($("#id_wrT4duNEOW").val().length == 9)) ||
(($("#id_wrT4duNEOW").val().startsWith("N")) &&
($("#id_wrT4duNEOW").val().length == 9))
)
{
// good things happen
}
else {
// error message
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
EDIT
Okay, I tried adding in the regex line, but I'm not getting the result. What am I missing?
$(function() {
$("input#id_wrT4duNEOW").blur(function() {
const regex = /^[bBeEnN]{1}[0-9]{8}$/
var mobiz = $("#id_wrT4duNEOW").val();
if (console.log(regex.test(mobiz)))
{
// good things happen
}
else {
// error message
}
});
});
Regex to the rescue. It's pretty straightforward to do using a regex and its associated .test method. The following regex ensures the string starts with one of the characters b, e, or n (not case sensitive), followed by exactly 8 digits:
test1 = "B12345678";
test2 = "N123456789";
test3 = "x12345678";
const regex = /^[bBeEnN]{1}[0-9]{8}$/
console.log(regex.test(test1))
console.log(regex.test(test2))
console.log(regex.test(test3))
So, for your snippet, you could adapt it like this:
$(function() {
$("input#id_wrT4duNEOW").blur(function() {
var val = $("#id_wrT4duNEOW").val();
if (/^[ben]{1}\d{8}$/i.test(val)) {
// good things happen
} else {
// error message
}
});
});
//1) must be 9 characters
//2) first character must be B, E, or N
//3) 8 characters past the first must be digits
var pattern = /^(B|E|N)\d{8}$/
console.log(pattern.test("weee"));
console.log(pattern.test("B12345678"));
console.log(pattern.test("A12345678"));
console.log(pattern.test("B123456789"));

Regex for negative decimal values client and server side c# jquery

I have a keypress function bound to an element, this element needs to only allow positive and negative decimal characters. i.e. 0-9, '.' , '-'
any other characters I need to prevent the character being inputted
Is there any way to achieve this in the current keypress function
$('.test').keyup(function (event) {
//if character is NOT ok i.e. 0-9, '.' , '-'
//STOP
..ELSE
//continue to do something
});
P.s. I am using jquery
One other way is to replace all illegal characters when typing:
$("selector").keyup(function (e) {
this.value = this.value.replace(/[^0-9\.-]/g, '');
});
May be useful, when user not typing text, but pasting it.
The key is inserted on keydown, so you should use that event instead. Then this should work:
$('.test').on('keyup', function(e){
e.preventDefault();
if(e.keyCode >= 48 && e.keyCode <= 57 // regular numbers
|| e.keyCode >= 96 && e.keyCode <= 106 // Numpad
|| e.keyCode === 189 // Minus
){
try{
parseInt($(this).val());
// Continue, this is a valid numeric value.
}catch(ex){
// Stop
}
}else {
// Stop
}
});
Hope this helps:
var string = '-10.56',
illegal = /[^0-9.-]/.test(string); // return true if illegal character found

Validation for integer number

I have created one form.In that form,it put one textbox.That text box should take only integer not character or float.So I applied validation like this.Does it right?
var a = document.getElementById('textbox1').value;
var b = /^\d+$/;
If (a.search(b) == -1)
{
alert(Must be Interger);
return false;
}
Yes, that will work, unless it's allowed to take a negative integer, in which case you need to add -? (optional negative sign) before the \d
You can use this script for Integer validation .
var value = Number(intfield.value);
if (Math.floor(value) == value) {
// value is integer, do something based on that
} else {
// value is not an Integer, show validation alerts
}
This should work:
var textboxValue = document.getElementById('textbox1').value;
if (!textboxValue.test(/^\d+$/)){
alert('Must be Interger');
return false;
}
Its a good practice to put easy names to vars or you will be lost months later whan you review your code :D
Hi I think below answer will be the better so that you can implement multiple TextBoxes
<script>
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 45 || charCode > 57)) {
return false;
return true;
}
}
</script>
Thanks
Bhanu Prakash

jquery plugin for preventing entering any input not matching a regexp

does jquery have any plugin that prevents entering any input to a textbox that doesnt match a regexp pattern. for example , i have a textbox for entering payment amount, i want user t be able to enter only numebers and . in the textbox, all other input wont have any effect on the textbox..
thanks
Masked Input Plugin
jQuery(function($){
$("#paymentAmount").mask("9999.99");
});
jquery-keyfilter plugin - does what is needed.
I don't think there is any such plugin readily available. The problem is a little tricky, because you have to allow the user to type some input before applying your regex. That is, you can't just match against each char as it is typed, unless your regex simply defines a set of characters.
To illustrate, if they are entering a payment amount, and you want to allow numbers and decimals on a single-character basis, what prevents them from entering 99.99.23.42492?
On the other hand, if you supply a complete regex like /\d+\.\d{2}/, then it won't match at all on a single character, you'll have to allow them to type some number of characters before trying to apply the regex and wiping out their input if it doesn't match. That could be frustrating.
If you really want to filter the input as they type, then you want to allow a digit for the first character, then digits or a decimal for subsequent characters until the decimal is entered, and then two more digits, and then no more input. It's not a general-purpose filter.
For example, here's some code that will do that, but it's very ugly.
myInput.keydown(function() {
var text = this.val
if(!/^\d/.test(text)) {
return '';
} else {
done = text.match(/^(\d+\.\d\d)/);
if (done) { return done[0]; }
last_char = text.substr(text.length-1,1);
decimal_count = text.replace(/[^\.]/g,'').length;
if (decimal_count < 1) {
if (!/[\d\.]/.test(last_char)) {
return text.substr(0,text.length-1);
}
} else if (decimal_count == 1 && last_char == '.') {
return text;
} else {
if (!/[\d]/.test(last_char)) {
return text.substr(0,text.length-1);
}
}
return text;
}
});
And of course, this won't work if they happen to paste in certain values without doing "real" typing.
Maybe some other approach would work better for you? Like highlighting the field and indicating to the user if they enter a non-digit, non-decimal, or if they enter more than one decimal, rather than filtering the input itself, because that seems messy.
Keyboard events are a bit tricky as suggested on the jQuery docs.
http://unixpapa.com/js/key.html
http://yehudakatz.com/2007/07/03/event-normalization-in-jquery-113/
The difficulty that concerns you is this:Identifying Keys
When you catch a keyboard event, you may wish to know which key was pressed. If so, you may be asking too much. This is a very big mess of browser incompatibilities and bugs.
From the first link above
All the same, in jQuery I'd do this:
textBoxElement.keydown( function( e ) {
var chr = String.fromCharCode( e.which );
if( !/[0-9.]/.test( chr ) ) {
e.preventDefault();
}
}
This will also disable other important keys like enter, tab, delete, so they need to be added into the conditional. Not all the other keys are printable and so can't be regexed, so you'll have to check for their e.keyCode. 13, 8 etc.
If you're not too bothered about the regex you could do something like
textBoxElement.keydown( function( e ) {
switch( e.keyCode ) {
case 48: //0
case 49: //1
case 50: //2
case 51: //3
case 52: //4
case 53: //5
case 54: //6
case 55: //7
case 56: //8
case 57: //9
case 48: //10
case 37: //left
case 39: //right
case 8: //tab
case 13: //return
case 46: //del
case 190: //.
return;
}
e.preventDefault();
});
Here is a simple jquery extension I use:
jQuery.fn.DecimalMask = function () {
return this.each(function () {
$(this).keypress(function (e) {
var keynum;
if (window.event) // IE
{
keynum = e.keyCode;
}
else if (e.which) // Netscape/Firefox/Opera
{
keynum = e.which;
}
if (typeof keynum == 'undefined') return true;
else if (keynum == 46 && $(this).val().indexOf(".") > -1) return false; //already has a decimal point
else return ((keynum > 47 && keynum < 58) || keynum == 13 || keynum == 8 || keynum == 9 || keynum == 46 || keynum == 45); //allow ony number keys or keypad number keys
});
});
};
//implementation
$("#mytxtbox").DecimalMask();

Categories

Resources