jquery - allow only negative, positive or decimal number validation in field - javascript

I use this code for positive validation of numbers and decimal. Now I would like to allow also negative numbers and decimals but it is not working. Any idea please?
$('.number_only').keypress(function(e){
return isNumbers(e, this);
});
function isNumbers(evt, element)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if (
(charCode != 46 || $(element).val().indexOf('.') != -1) && // “.” CHECK DOT, AND ONLY ONE.
(charCode < 48 || charCode > 57)
)
return false;
return true;
}
I found this but no idea how to implement it jquery - allow only negative, positive or decimal number validation

You can use regex instead to solve your problem, change your method to something like this:
function isNumbers(evt, element)
{
var elementValue = $(element).val();
var regex = /^(\+|-)?(\d*\.?\d*)$/;
if (regex.test(elementValue + String.fromCharCode(evt.charCode))) {
return true;
}
return false;
}

Related

Restrict entering Spaces in TextBox in Javascript

In my code have to allow numerical alphabets and special characters. but in my code not accepting the space and special characters except #.
Here is my code.
allowAlphaNumericSpace(e: any) {
var code = 'charCode' in e ? e.charCode : e.keyCode;
if (
!(code > 47 && code < 58) && // numeric (0-9)
!(code >= 64 && code <= 91) && // upper alpha (A-Z)
!(code > 96 && code < 123)
) {
// lower alpha (a-z)
e.preventDefault();
}
}
charCode is non-standard, deprecated, and not foreseen for keydown events, it may be available, but always 0.
keyCode is also deprecated.
Use e.key:
const accepted = " ,;!?";
function allowAlphaNumericSpace(e) {
var code = e.key;
if (isNaN(code) && code.toUpperCase() == code.toLowerCase()
&& !accepted.includes(code)) {
e.preventDefault();
}
}
document.querySelector("input").addEventListener("keydown", allowAlphaNumericSpace);
<input>
If some other characters need to be accepted, it is easily adapted.

How to executing a validation in text box number format like 44.44

I want to Check the value to both javascript and php ,which one should be like this format 22.22 or 00.44 or 44 or 55.00.
I have the below code.
$(function(){
// $('.pixcel_rate').keypress(function (event) {
// return isNumber(event, this)
// });
$('.pixcel_rate').keypress(function (event) {
return validateFloatKeyPress($(this).val());
});
});
// THE SCRIPT THAT CHECKS IF THE KEY PRESSED IS A NUMERIC OR DECIMAL VALUE.
function validateFloatKeyPress(evt,el) {
var charCode = (evt.which) ? evt.which : event.keyCode;
var number = el.value.split('.');
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
//just one dot (thanks ddlab)
if(number.length>1 && charCode == 46){
return false;
}
//get the carat position
var caratPos = getSelectionStart(el);
var dotPos = el.value.indexOf(".");
console.log(caratPos);
console.log(dotPos);
if( caratPos >1 && dotPos>-1 && (number[0].length > 1)){
return false;
}
if( caratPos > dotPos && dotPos>-1 && (number[1].length > 1)){
return false;
}
return true;
}
function getSelectionStart(o) {
if (o.createTextRange) {
var r = document.selection.createRange().duplicate()
r.moveEnd('character', o.value.length)
if (r.text == '') return o.value.length
return o.value.lastIndexOf(r.text)
} else return o.selectionStart
}
You can use preg_match in php to see if it matches the pattern.
preg_match("/^\d{2}\.\d{2}$|^\d{2}$/", $val);
This matches either two digits, dot, two digits. Or just two digits.
Example test cases:
https://3v4l.org/G6D8l
You can use regex to achieve this. Below is the regex for your requirement.
https://regex101.com/r/N5gbqs/3/
function validateFloatKeyPress(value) {
//returns null if it doesnt match the given regular expression
return value.toString().match(/^(\d{2}|\d{2}\.\d{2})$/)
}
function validateFloatKeyPress(value) {
//returns false if it doesnt match the given regular expression
return (/^(\d{2}|\d{2}\.\d{2})$/).test(value.toString())
}

validate input with decimal precision and scale

I am trying to create a javascript function which is called on keypress event on a input which does the following:
Input should be a valid decimal with format (5,2) => (XXXXX.YY) which are variable to the function. Input is restricted if user adds any value which does not conform to the format above.
If existing input starts with . append 0 to the starting automatically
HTML
<input type="text" onkeypress="return checkDecimal(event, this, 5, 2);" id="price2" value="27.15">
Javascript
function checkDecimal(evt, item, lenBeforeDecimal, lenAfterDecimal) {
var charCode = evt.which;
var trimmed = $(item).val().replace(/\b^0+/g, "");
if(checkStartsWith(trimmed, '.') == true){
trimmed = '0' + trimmed;
}
//Allow following keys
//8 = Backspace, 9 = Tab
if(charCode == 8 || charCode == 9){
return true;
}
//Only a single '.' is to be allowed
if(charCode == 46){
var dotOccurrences = (trimmed.match(/\./g) || []).length;
if(dotOccurrences != undefined && dotOccurrences == 1){
return false;
}else{
return true;
}
}
if (charCode > 31 && ((charCode < 48) || (charCode > 57))) {
return false;
}
if ($(item).val() != trimmed){
$(item).val(trimmed);}
//Check the start and end length
if(trimmed.indexOf('.') == -1){
if(trimmed.length >= parseInt(lenBeforeDecimal)){
return false;
}
}else{
var inputArr = trimmed.split(".");
if(inputArr[0].length > parseInt(lenBeforeDecimal) || inputArr[1].length >= parseInt(lenAfterDecimal)){
return false;
}
}
return true;
}
function checkStartsWith(str, prefix){
return str.indexOf(prefix) === 0;
}
Issues
If user inputs 12345.9 and then moves the caret position after 5, user is able to add another digit before the decimal 123456.9 which should not be allowed.
If user inputs 1.9 and then remove 1 and add 5, 5 is added at the end and the entered value becomes 0.95 and not 5.9
JS Fiddle
Consider using a regular expression like:
/^(\d{0,5}\.\d{0,2}|\d{0,5}|\.\d{0,2})$/;
that allows everything up to and including your required format, but returns false if the number part is more than 5 digits or if the fraction is more than 2 digits, e.g.:
<input type="text" onkeyup="check(this.value)"><span id="er"></span>
<script>
function check(v) {
var re = /^(\d{0,5}\.\d{0,2}|\d{0,5}|\.\d{0,2})$/;
document.getElementById('er').innerHTML = re.test(v);
}
</script>
You'll need separate validation for the final value, e.g.
/^\d{5}\.\d{2}$/.test(value);
to make sure it's the required format.
I don't understand the requirement to add a leading zero to "." since the user must enter 5 leading digits anyway (unless I misunderstand the question).

Alpha-only character validation in JavaScript

I am working on this code in which it checks validation on numeric characters. In the same way, I want validation on alpha-only characters. I have tried many symbols but failed to succeed.
if (/\D/.test(x))
{
alert("Please only enter numeric characters (Allowed input:0-9)")
return false;
}
What changes are required in this code for alpha-only validation.
Using .test()
If you want to keep with the .test() method, I believe that the below would work for you.
Identify if the input is numeric.
if (/^[a-zA-Z]+$/.test(x))
{
alert("Please only enter numeric characters (Allowed input:0-9)")
return false;
}
Identify if the input contains a-z/A-Z
if (!/^[a-zA-Z]+$/.test(x))
{
alert("Please only enter letters (Allowed input: a-z, A-Z)")
return false;
}
Fiddle
Not Using .test()
You can also set up functions that look for the value during the onkeypress event
Allow only numerical characters to be entered in select fields || onkeypress="return isNumberKey(event)"
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if(charCode > 31 && (charCode < 48 || charCode > 57)){return false;}
return true;
}
Allow only alpha characters to be entered in select fields || onkeypress="return isAlphaKey(event)"
function isAlphaKey(evt)
{
evt = (evt) ? evt : event;
var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :((evt.which) ? evt.which : 0));
if(charCode > 32 && (charCode < 65 || charCode > 90) && (charCode < 97 || charCode > 122)){return false;}
return true;
}

Javascript limit text input characters

I am wanting to restrict the input characters for a text box to [a-z0-9_-]. However whenever if do this buttons like backspace and the arrow keys don't work. I have found some attempts on this website and others but either they don't work properly on all browsers or they use a black list. For example the W3Schools website example black lists numbers. Is there a way to use white list (the one above) and still allow keys like backspace, arrows, home, end etc? Or do I have to add everyone of the key codes that match the keys I want to allow? I do something like this (this is shortened for simplicity).
EDIT - Added code
<input type="text" onkeypress="return checkInput();">
function checkInput(){
return /[a-z0-9_-]/gi.test(String.fromCharCode(window.event.keyCode));
}
Just change the regex in the example to something like this:
numcheck = /[^a-z0-9_-]/;
Or better yet, avoid the double negative with:
numcheck = /[a-z0-9_-]/;
return numcheck.test(keychar);
Then you can look up the keycodes of backspace, etc. and check for them too:
if (keychar === 8) return true;
...
Or even put them in your regex:
numcheck = /[a-z0-9_\x08-]/;
You haven't provided any code samples, so it's hard to be specific in a response, but as a general strategy, try this: instead of trying to whitelist characters that can be input while they are being typed in, validate the contents of the text box after every key stroke to make sure that it still contains valid characters. If it doesn't, remove the last character entered.
This approach will allow special keys like backspace, etc., while at the same time achieve what it sounds like you are really after: a valid value in the text box.
Yes you can limit the input of characters. For example create a function that checks what is going on, return true if everything is OK and false if not:
// return true for 1234567890A-Za-z - _
function InputCheck(e) {
if ((e.shiftKey && e.keyCode == 45) || e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
if (e.which == 45 || e.which == 95 || (e.which >= 65 && e.which <= 90) || (e.which >= 97 && e.which <= 122))
return true;
return false;
}
return true;
}
once you have the function, hook it into you input (this is with jQuery):
$('#InputID').keypress(InputCheck);
You can make as complicated a check as you want, for example this will allow for USD money values:
function InputCheck(e) {
if ((e.shiftKey && e.keyCode == 45) || e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57) && e.which != 46 && e.which != 36) {
return false;
}
// . = 46
// $ = 36
var text = $(this).val();
// Dollar sign first char only
if (e.which == 36 && text.length != 0) {
return false;
}
// Only one decimal point
if (e.which == 46 && text.indexOf('.') != -1) {
return false;
}
// Only 2 numbers after decimal
if (text.indexOf('.') != -1 && (text.length - text.indexOf('.')) > 2) {
return false;
}
return true;
}
You can press any key you like, as long as you keep the value from including anything
not in the white-list.
inputelement.onkeyup=function(e){
e=e || window.event;
var who=e.target || e.srcElement;
who.value= who.value.replace(/[^\w-]+/g,'');
}
Add this code to onkeypress event.
var code;
document.all ? code = e.keyCode : code = e.which;
return ((code > 64 && code < 91) || (code > 96 && code < 123) || code == 8 || code == 32 || (code >= 48 && code <= 57));
For browser compatibility, You can add
var k = e.keyCode == 0 ? e.charCode : e.keyCode;

Categories