Restricting input to textbox: allowing only numbers and decimal point
<HTML> <HEAD> <SCRIPT language=Javascript> <!-- function isNumberKey(evt) { var charCode = (evt.which) ? evt.which : evt.keyCode; if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) return false;
return true; } //--> </SCRIPT> </HEAD> <BODY> <INPUT id="txtChar" onkeypress="return isNumberKey(event)" type="text" name="txtChar"> </BODY></HTML>
Restricting input to textbox: it only accept number and should not accept decimal value
first you need to create an input element which call a function
<input type = "text" id = "a" onkeyup="myFunction(event)"/>
now you define your input box which will call a function myFunction (which takes event) whenever you will press a key on your keyboard.
now we need to prevent all the other key except 0-9 and without (.) becuase you don't want any decimal point.
so we need to create a regex which can check the pattern and check if the typed value follows the pattern or not if it follow we will set the value in a variable if not then we will set input value to old correct value and call preventDefault.
<script>
let value = null;
function myFunction(event) {
// event.target.value = what ever you typed
// /^[0-9]+$/ = regex code to prevent other letter except 0123456789
if (event.target.value.match(/^[0-9]+$/)) {
value = event.target.value;
} else {
// this line will update your input box to correct value
document.getElementById("a").value = value;
event.preventDefault();
}
}
</script>
How can I restrict input to a text-box so that it accepts only numbers and the decimal point( atleast 4 decimals e.g 192.168.192.192)?
What you are looking for is the HTML input pattern.
The pattern attribute specifies a regular expression that the element's value is checked against on form submission.
For IP validation you can use this regular expression : ^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
Edit:
In order to ignore any other keys than the one you want you can use something like this.
@Directive( {
selector : '[allow-keys]',
host : {
'(keydown)' : 'onKeyUp($event)'
}
} )
export class AllowKeysDirective {
@Input( 'allow-keys' ) allowKeys;
onKeyUp ( $event ) {
if ( this.allowKeys && !this.allowKeys.includes( $event. keyCode ) ) {
$event.preventDefault();
}
}
}
It is a more "angular-like" way to handle ignoring keystrokes than the one I described in my comment. I created an example to demonstrate its use.
How allow only numbers and 2 digit decimal in textbox by using jquery
Here is the solution which will allow user to enter only numbers and single period (.).
$('#text').keypress(function (event) {
return isNumber(event, this)
});
// THE SCRIPT THAT CHECKS IF THE KEY PRESSED IS A NUMERIC OR DECIMAL VALUE.
function isNumber(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;
}
OR
<input id="txtId" type="text"></input>
var txt = document.getElementById('txtId');
txt.addEventListener('keyup', myFunc);
function myFunc(e) {
var val = this.value;
var re = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)$/g;
var re1 = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)/g;
if (re.test(val)) {
//do something here
} else {
val = re1.exec(val);
if (val) {
this.value = val[0];
} else {
this.value = "";
}
}
}
I hope this will fulfill your need.
Regex to allow only numbers and decimals not working in Javascript
Here's an alternative way. I'm using the oninput
event that is triggered on every value change by user (not only key presses). I'm saving the last valid value and restoring it whenever the new value is invalid.
<input type="text" id="test1" oninput="validateNumber(this);" /><script>var validNumber = new RegExp(/^\d*\.?\d*$/);var lastValid = document.getElementById("test1").value;function validateNumber(elem) { if (validNumber.test(elem.value)) { lastValid = elem.value; } else { elem.value = lastValid; }}</script>
jQuery: what is the best way to restrict number-only input for textboxes? (allow decimal points)
Update
There is a new and very simple solution for this:
It allows you to use any kind of input filter on a text
<input>
,
including various numeric filters. This will correctly handle
Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations,
non-typeable keys, and all keyboard layouts.
See this answer or try it yourself on JSFiddle.
jquery.numeric plugin
I've successfully implemented many forms with the jquery.numeric plugin.
$(document).ready(function(){
$(".numeric").numeric();
});
Moreover this works with textareas also!
However, note that Ctrl+A, Copy+Paste (via context menu) and Drag+Drop will not work as expected.
HTML 5
With wider support for the HTML 5 standard, we can use pattern
attribute and number
type for input
elements to restrict number only input. In some browsers (notably Google Chrome), it works to restrict pasting non-numeric content as well. More information about number
and other newer input types is available here.
Allow 2 decimal places in input type=number
Instead of step="any"
, which allows for any number of decimal places, use step=".01"
, which allows up to two decimal places.
More details in the spec: https://www.w3.org/TR/html/sec-forms.html#the-step-attribute
Restricting input to textbox: allowing only numbers and decimal point
<HTML> <HEAD> <SCRIPT language=Javascript> <!-- function isNumberKey(evt) { var charCode = (evt.which) ? evt.which : evt.keyCode; if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) return false;
return true; } //--> </SCRIPT> </HEAD> <BODY> <INPUT id="txtChar" onkeypress="return isNumberKey(event)" type="text" name="txtChar"> </BODY></HTML>
Related Topics
How to Wait For the 'End' of 'Resize' Event and Only Then Perform an Action
How to Render an 'Atmosphere' Over a Rendering of the Earth in Three.Js
How to Calculate the Number of Days Between Two Dates
How to Render HTML String as Real Html
JavaScript Not Running on Jsfiddle.Net
JavaScript: How to Find Out If the User Browser Is Chrome
How to Apply CSS to Half of a Character
Disabling Browser Print Options (Headers, Footers, Margins) from Page
Jquery Disable/Enable Submit Button
How to Implement "Select All" Check Box in Html
Browser Detection Versus Feature Detection
How to Correctly Iterate Through Getelementsbyclassname
Link Index.Html Client.Js and Server.Js
How to Set Selected Value of Jquery Select2
Capture HTML Canvas as Gif/Jpg/Png/Pdf
User Recognition Without Cookies or Local Storage
Performance of Mutationobserver to Detect Nodes in Entire Dom