Blocking spaces ASP MVC and Javascript - javascript

I'm trying to validate the code that users enter in my view. I want it to be MAJ and only letters and numbers. So no ""/(!/ or spaces. Everything works just fine except for the spaces...
Here's the code
#Html.TextBoxFor(m => m.Code, new { #onkeydown = "onKeyDown(this);", #class = "input-visual-helper form-control", placeholder = #MyProject.Resources.home.ActivationCode })
<script type="text/javascript">
function onKeyDown(a) {
var charCode = (a.which) ? a.which : event.keyCode
setTimeout(function () {
a.value = a.value.toUpperCase();
}, 1);
return ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || charCode == 8 || (charCode >= 48 && charCode <= 57));
}
</script>
I did a console.log of the condition in the return and it logs false when I type the space (code 32). I even tried doing if(charCode ==32) return false. Still not working... The interface keeps doing a space in the textbox.
Any help would be greatly appreciated.
Thanks

$("#jam").keydown(function (e) {
if (e.keyCode == 32) {
return false;
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>
<body>
<input id="jam"/>
</body>
</html>
Something like this?
<script type="text/javascript">
$("#targetElement").keydown(function (e) {
if (e.keyCode == 32) {
return false;
}
});
</script>
https://jsbin.com/didohiloni/1/edit
For the MVC textbox you would append new { id = "youid" } in there

If anyone wants a complete version of the code
the control :
#Html.TextBoxFor(m => m.Model.Code, new { #onkeydown= "onKeyDown(this)", #id = "bindingCode", #class = "input-visual-helper form-control", placeholder = #Resources.home.Code })
<script type="text/javascript">
//No spaces and no special characters
$(document).on('keypress', '#bindingCode', function (event) {
if (event.keyCode == 32) {
return false;
}
var regex = new RegExp("^[A-Z0-9]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
key = key.toUpperCase();
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
// All Letters in maj
function onKeyDown(a) {
var charCode = a.which;
setTimeout(function () {
a.value = a.value.toUpperCase();
}, 1);
}
</script>

Related

Only 4 digit numbers in input field in MVC TextBoxFor

I have an MVC5 project and I have an input field that I only want to take an 8 digit number. I tried implementing it like this:
#Html.TextBoxFor(model => model.oldPin, new { maxlength = "8", #class = "form-control disablecopypaste", onkeydown = "return isNumber(event);" })
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode === 16) {
return false;
}
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
My problem is that while this prevents numbers it allows spaces and special characters. How do I prevent this? It works with the keypress event but its depreciated and I'm concerned about browser compatibility. Is there any way to do this with the keydown event? All the answers I've seen are all with the keypress event.
function allowNumberOnly (e) {
var ascii = (e.which) ? e.which : e.keyCode
if (ascii> 31 && (ascii< 48 || ascii> 57)) {
return false;
}
else {
var vall = $('#oldPin').val()
if (vall.length > 3) {
return false;
}
else {
return true;
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="form-control " id="oldPin" name="oldPin" onkeypress="return allowNumberOnly(event)" type="text" value="">

Javascript to restrict entry to numbers in textbox

I have an MVC form that I want to restrict the entry on some textboxes to numbers only. I found this code that does that, however, it also restricts the use of the numbers on the keypad pad on the right of the keyboard. Any ideas on how to allow the keypad? I am not sure what is causing that to happen.
<script type="text/javascript">
function ValidateNumber(e) {
var evt = (e) ? e : window.event;
var charCode = (evt.keyCode) ? evt.keyCode : evt.which;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
};
HTML Razor:
#Html.TextBoxFor(m => m.CustomerSSN, new { #placeholder = "Customer SSN", #type="number" })
Another approach would be to use the HTML 5 input tag that has built in validation.
<input type="number" name="quantity">
www.w3schools.com/html/html_form_input_types.asp
So here is how I solved this...
<script type="text/javascript">
//Allow only numbers entered
$(document).ready(function () {
$("#CustomerSSN").keypress(function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
});
});

Restricting Input to numbers only(-100.00 to 100.00) in a HTML input field

I am trying to restrict html input field to accept numbers only
The JS code is working fine with English keyboard on an android device but when i change keyboard to Japaneses it starts accepting Japaneses characters.
(Update: Japanese input problem solved only - and decimal point is not being entered)
Here is the HTML
<input type='text' style='height: 100%;' name='lmt_c13' id='lmt_c13' isNumeric='true' onblur='updateJudgment(this);' onkeyup='removeSpaces(this);' onkeypress='return isNumberKey(event,this);' class='txtCtrl' >0</input>
and here is the JS code
function isNumberKey(evt, control) {
if ($(control).attr("isNumeric") == "true") {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) || charCode == 13)
return false;
return true;
}
};
the input I want in this input field in something like -12.24 and 23.78
See the
// Restricts input for each element in the set of matched elements to the given inputFilter.
(function($) {
$.fn.inputFilter = function(inputFilter) {
return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function() {
if (inputFilter(this.value)) {
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty("oldValue")) {
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
} else {
this.value = "";
}
});
};
}(jQuery));
// Install input filters.
$("#intTextBox").inputFilter(function(value) {
return /^-?\d*$/.test(value); });
$("#uintTextBox").inputFilter(function(value) {
return /^\d*$/.test(value); });
$("#intLimitTextBox").inputFilter(function(value) {
return /^\d*$/.test(value) && (value === "" || parseInt(value) <= 500); });
$("#floatTextBox").inputFilter(function(value) {
return /^-?\d*[.,]?\d*$/.test(value); });
$("#currencyTextBox").inputFilter(function(value) {
return /^-?\d*[.,]?\d{0,2}$/.test(value); });
$("#latinTextBox").inputFilter(function(value) {
return /^[a-z]*$/i.test(value); });
$("#hexTextBox").inputFilter(function(value) {
return /^[0-9a-f]*$/i.test(value); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2>jQuery input filter showcase</h2>
<p>Supports Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, the caret position, different keyboard layouts, and all browsers since IE 9.</p>
<p>There is also a pure JavaScript version of this (without jQuery).</p>
<table>
<tr><td>Integer</td><td><input id="intTextBox"></td></tr>
<tr><td>Integer >= 0</td><td><input id="uintTextBox"></td></tr>
<tr><td>Integer >= 0 and <= 500</td><td><input id="intLimitTextBox"></td></tr>
<tr><td>Float (use . or , as decimal separator)</td><td><input id="floatTextBox"></td></tr>
<tr><td>Currency (at most two decimal places)</td><td><input id="currencyTextBox"></td></tr>
<tr><td>A-Z only</td><td><input id="latinTextBox"></td></tr>
<tr><td>Hexadecimal</td><td><input id="hexTextBox"></td></tr>
</table>
for more input filter examples. Also note that you still must do server side validation!
If you want to know more about regular expressions see this link: https://www.w3schools.com/jsref/jsref_obj_regexp.asp
For decimal point allow, You can add below condition :: || charCode == 46
if (charCode > 31 && (charCode < 48 || charCode > 57) || charCode == 13 || charCode == 46 )
Or if you want to test decimal validation then
function CheckDecimal(inputtxt)
{
var decimal= /^[-+]?[0-9]+\.[0-9]+$/;
if(inputtxt.value.match(decimal))
{
return true;
}
else
{
return false;
}
}
Hope it helps
i think me i'll do this: (using regular expressions)
function isNumberKey(control) {
if ($(control).attr("isNumeric") == "true") {
var regex = /^[0-9.-]$/;
var _event = event || window.event;
var key = _event.keyCode || _event.which;
key = String.fromCharCode(key);
if(!regex.test(key)) {
//alert(key);
_event.returnValue = false;
if (_event.preventDefault)
_event.preventDefault();
}
}
};
function isDecimal(control) {
if ($(control).attr("isNumeric") == "true") {
var regex = /^[-]?[0-9]+[.]?[0-9]*$/;
str = $(control)[0].value;
var _event = event || window.event;
if(!regex.test(str)) {
var m = str.match(/^[-]?[0-9]+[.]?[0-9]*/g);
$(control)[0].value = m[0];
_event.returnValue = false;
if (_event.preventDefault)
_event.preventDefault();
}
}
};
and my html:
<input type='text' style='height: 20px;' name='lmt_c13' id='lmt_c13' isNumeric='true' onblur='updateJudgment(this);' onkeyup='isDecimal(this);' onkeypress='isNumberKey(this);' class='txtCtrl' value='0' />
please try it and tell me if it works.

How to assign only numbers to text box in MVC view

I have put a text box where i want only numbers. I want to validate it in the client side and written the following code
#using (Html.BeginForm("LoyaltyPoints","Cart",FormMethod.Post))
{
<label>Enter point:</label>
<br />
#Html.TextBoxFor(m => m.txtLoyaltyPoints, new { #onkeypress = "OnlyNumeric(this)" })
<br />
<input type="submit" value="Submit" />
<br />
#ViewBag.LoyaltyPointsErrorMessage
}
#Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
function OnlyNumeric(e) {
if ((e.which < 48 || e.which > 57)) {
if (e.which == 8 || e.which == 46 || e.which == 0) {
return true;
}
else {
return false;
}
}
}
now here my javascript is not firing. i tried keeping alert here but not working as intended. What could be the error. please help.
use the following code:
#Html.TextBoxFor(m => m.txtLoyaltyPoints, new {#id ="txtLoyalty" })`
<script type="text/javascript">
$(document).ready(function () {
$("#txtLoyalty").keydown(function (event) {
if (event.shiftKey) {
event.preventDefault();
}
if (event.keyCode == 46 || event.keyCode == 8) {
}
else {
if (event.keyCode < 95) {
if (event.keyCode < 48 || event.keyCode > 57) {
event.preventDefault();
}
}
else {
if (event.keyCode < 96 || event.keyCode > 105) {
event.preventDefault();
}
}
}
});
});
#Html.TextBoxFor(m => m.Height, new { #type = "number", #onkeypress = "ValidateNumber(event);" })
function ValidateNumber(event) {
var theEvent = event || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = /[0-9]|\./;
if (!regex.test(key)) {
theEvent.preventDefault ? theEvent.preventDefault() : (theEvent.returnValue = false);
}
You can replace onkeypress with onblur
i.e.
#Html.TextBoxFor(m => m.txtLoyaltyPoints, new { #onblur = "OnlyNumeric(this)" })
<td class="field_nameW">
$#Html.TextBox("PayFromBankId3_Amount", 0.00M, new { #class = "amount_field", #onblur = "FormatAmountDecimal(this,3);", #size = "7", title = "Amount", #maxlength = "11" })
<script>
$('#Id').numeric({ allow: "." });
</script>
#Html.TextBoxFor(m => m.txtLoyaltyPoints, new { #onkeypress = "return onlyNos(event,this);" })
<script>
function onlyNos(e, t) {<br/>
if (window.event) {<br/>
var charCode = window.event.keyCode;<br/>
}<br/>
else if (e) {<br/>
var charCode = e.which;<br/>
}<br/>
else { return true; }<br/>
if (charCode > 31 && (charCode < 48 || charCode > 57)) {<br/>
alert("Please Enter only Numbers");<br/>
return false;<br/>
}<br/>
return true;<br/>
}
</script>

Restricting input to textbox: allowing only numbers and decimal point

How can I restrict input to a text-box so that it accepts only numbers and the 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>
This really works!
The accepted solution is not complete, since you can enter multiple '.', for example 24....22..22. with some small modifications it will work as intended:
<html>
<head>
<script type="text/javascript">
function isNumberKey(txt, evt) {
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode == 46) {
//Check if the text already contains the . character
if (txt.value.indexOf('.') === -1) {
return true;
} else {
return false;
}
} else {
if (charCode > 31 &&
(charCode < 48 || charCode > 57))
return false;
}
return true;
}
</script>
</head>
<body>
<input type="text" onkeypress="return isNumberKey(this, event);" />
</body>
</html>
form.onsubmit = function(){
return textarea.value.match(/^\d+(\.\d+)?$/);
}
Is this what you're looking for?
I hope it helps.
EDIT: I edited my example above so that there can only be one period, preceded by at least one digit and followed by at least one digit.
Here is one more solution which allows for decimal numbers and also limits the digits after decimal to 2 decimal places.
function isNumberKey(evt, element) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) && !(charCode == 46 || charCode == 8))
return false;
else {
var len = $(element).val().length;
var index = $(element).val().indexOf('.');
if (index > 0 && charCode == 46) {
return false;
}
if (index > 0) {
var CharAfterdot = (len + 1) - index;
if (CharAfterdot > 3) {
return false;
}
}
}
return true;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="rate" placeholder="Billing Rate" required onkeypress="return isNumberKey(event,this)">
All solutions presented here are using single key events. This is very error prone since input can be also given using copy'n'paste or drag'n'drop. Also some of the solutions restrict the usage of non-character keys like ctrl+c, Pos1 etc.
I suggest rather than checking every key press you check whether the result is valid in respect to your expectations.
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;
}
}
<textarea id="test1" oninput="validateNumber(this);" ></textarea>
The oninput event is triggered just after something was changed in the text area and before being rendered.
You can extend the RegEx to whatever number format you want to accept. This is far more maintainable and extendible than checking for single key presses.
Are you looking for something like this?
<HTML>
<HEAD>
<SCRIPT language=Javascript>
<!--
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.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>
Just need to apply this method in Jquery and you can validate your textbox to just accept number with a decimal only.
function IsFloatOnly(element) {
var value = $(element).val();
var regExp ="^\\d+(\\.\\d+)?$";
return value.match(regExp);
}
Please see working demo here
here is script that cas help you :
<script type="text/javascript">
// price text-box allow numeric and allow 2 decimal points only
function extractNumber(obj, decimalPlaces, allowNegative)
{
var temp = obj.value;
// avoid changing things if already formatted correctly
var reg0Str = '[0-9]*';
if (decimalPlaces > 0) {
reg0Str += '\[\,\.]?[0-9]{0,' + decimalPlaces + '}';
} else if (decimalPlaces < 0) {
reg0Str += '\[\,\.]?[0-9]*';
}
reg0Str = allowNegative ? '^-?' + reg0Str : '^' + reg0Str;
reg0Str = reg0Str + '$';
var reg0 = new RegExp(reg0Str);
if (reg0.test(temp)) return true;
// first replace all non numbers
var reg1Str = '[^0-9' + (decimalPlaces != 0 ? '.' : '') + (decimalPlaces != 0 ? ',' : '') + (allowNegative ? '-' : '') + ']';
var reg1 = new RegExp(reg1Str, 'g');
temp = temp.replace(reg1, '');
if (allowNegative) {
// replace extra negative
var hasNegative = temp.length > 0 && temp.charAt(0) == '-';
var reg2 = /-/g;
temp = temp.replace(reg2, '');
if (hasNegative) temp = '-' + temp;
}
if (decimalPlaces != 0) {
var reg3 = /[\,\.]/g;
var reg3Array = reg3.exec(temp);
if (reg3Array != null) {
// keep only first occurrence of .
// and the number of places specified by decimalPlaces or the entire string if decimalPlaces < 0
var reg3Right = temp.substring(reg3Array.index + reg3Array[0].length);
reg3Right = reg3Right.replace(reg3, '');
reg3Right = decimalPlaces > 0 ? reg3Right.substring(0, decimalPlaces) : reg3Right;
temp = temp.substring(0,reg3Array.index) + '.' + reg3Right;
}
}
obj.value = temp;
}
function blockNonNumbers(obj, e, allowDecimal, allowNegative)
{
var key;
var isCtrl = false;
var keychar;
var reg;
if(window.event) {
key = e.keyCode;
isCtrl = window.event.ctrlKey
}
else if(e.which) {
key = e.which;
isCtrl = e.ctrlKey;
}
if (isNaN(key)) return true;
keychar = String.fromCharCode(key);
// check for backspace or delete, or if Ctrl was pressed
if (key == 8 || isCtrl)
{
return true;
}
reg = /\d/;
var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
var isFirstD = allowDecimal ? keychar == '.' && obj.value.indexOf('.') == -1 : false;
var isFirstC = allowDecimal ? keychar == ',' && obj.value.indexOf(',') == -1 : false;
return isFirstN || isFirstD || isFirstC || reg.test(keychar);
}
function blockInvalid(obj)
{
var temp=obj.value;
if(temp=="-")
{
temp="";
}
if (temp.indexOf(".")==temp.length-1 && temp.indexOf(".")!=-1)
{
temp=temp+"00";
}
if (temp.indexOf(".")==0)
{
temp="0"+temp;
}
if (temp.indexOf(".")==1 && temp.indexOf("-")==0)
{
temp=temp.replace("-","-0") ;
}
if (temp.indexOf(",")==temp.length-1 && temp.indexOf(",")!=-1)
{
temp=temp+"00";
}
if (temp.indexOf(",")==0)
{
temp="0"+temp;
}
if (temp.indexOf(",")==1 && temp.indexOf("-")==0)
{
temp=temp.replace("-","-0") ;
}
temp=temp.replace(",",".") ;
obj.value=temp;
}
// end of price text-box allow numeric and allow 2 decimal points only
</script>
<input type="Text" id="id" value="" onblur="extractNumber(this,2,true);blockInvalid(this);" onkeyup="extractNumber(this,2,true);" onkeypress="return blockNonNumbers(this, event, true, true);">
For anyone stumbling here like I did, here is a jQuery 1.10.2 version I wrote which is working very well for me albeit resource intensive:
/***************************************************
* Only allow numbers and one decimal in text boxes
***************************************************/
$('body').on('keydown keyup keypress change blur focus paste', 'input[type="text"]', function(){
var target = $(this);
var prev_val = target.val();
setTimeout(function(){
var chars = target.val().split("");
var decimal_exist = false;
var remove_char = false;
$.each(chars, function(key, value){
switch(value){
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '.':
if(value === '.'){
if(decimal_exist === false){
decimal_exist = true;
}
else{
remove_char = true;
chars[''+key+''] = '';
}
}
break;
default:
remove_char = true;
chars[''+key+''] = '';
break;
}
});
if(prev_val != target.val() && remove_char === true){
target.val(chars.join(''))
}
}, 0);
});
A small correction to #rebisco's brilliant answer to validate the decimal perfectly.
function isNumberKey(evt) {
debugger;
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode == 46 && evt.srcElement.value.split('.').length>1) {
return false;
}
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
If you want it for float values,
Here is the function I am using
<HTML>
<HEAD>
<SCRIPT language=Javascript>
<!--
function check(e, value) {
//Check Charater
var unicode = e.charCode ? e.charCode : e.keyCode;
if (value.indexOf(".") != -1)
if (unicode == 46) return false;
if (unicode != 8)
if ((unicode < 48 || unicode > 57) && unicode != 46) return false;
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<INPUT id="txtChar" onkeypress="return check(event,value)" type="text" name="txtChar">
</BODY>
</HTML>
function onlyDotsAndNumbers(txt, event) {
var charCode = (event.which) ? event.which : event.keyCode
if (charCode == 46) {
if (txt.value.indexOf(".") < 0)
return true;
else
return false;
}
if (txt.value.indexOf(".") > 0) {
var txtlen = txt.value.length;
var dotpos = txt.value.indexOf(".");
//Change the number here to allow more decimal points than 2
if ((txtlen - dotpos) > 2)
return false;
}
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
<input type="text" id="txtAmount" onkeypress="return onlyDotsAndNumbers(this,event);" maxlength="10" oncopy="return false" ondrag="return false" ondrop="return false" onpaste="return false" />
Only Numbers, One decimal point, No Copy Paste.
inputelement.onchange= inputelement.onkeyup= function isnumber(e){
e= window.event? e.srcElement: e.target;
while(e.value && parseFloat(e.value)+''!= e.value){
e.value= e.value.slice(0, -1);
}
}
function integerwithdot(s, iid){
var i;
s = s.toString();
for (i = 0; i < s.length; i++){
var c;
if (s.charAt(i) == ".") {
} else {
c = s.charAt(i);
}
if (isNaN(c)) {
c = "";
for(i=0;i<s.length-1;i++){
c += s.charAt(i);
}
document.getElementById(iid).value = c;
return false;
}
}
return true;
}
Suppose your textbox field name is Income
Call this validate method when you need to validate your field:
function validate() {
var currency = document.getElementById("Income").value;
var pattern = /^[1-9]\d*(?:\.\d{0,2})?$/ ;
if (pattern.test(currency)) {
alert("Currency is in valid format");
return true;
}
alert("Currency is not in valid format!Enter in 00.00 format");
return false;
}
Extending the #rebisco's answer. this below code will allow only numbers and single '.'(period) in the text box.
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
} else {
// If the number field already has . then don't allow to enter . again.
if (evt.target.value.search(/\./) > -1 && charCode == 46) {
return false;
}
return true;
}
}
alternative way to restrict input to a text-box so that it accepts only numbers and the decimal point is to
use javascript inside the html input. This works for me:
<input type="text" class="form-control" id="price" name="price" placeholder="Price"
vrequired onkeyup="this.value=this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1')">
--Accepts--
9
9.99
--Do not accept--
9.99.99
ABC
Better solution
var checkfloats = function(event){
var charCode = (event.which) ? event.which : event.keyCode;
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
if(event.target.value.indexOf('.') >=0 && charCode == 46)
return false;
return true;
}
I chose to tackle this on the oninput event in order to handle the issue for keyboard pasting, mouse pasting and key strokes. Pass true or false to indicate decimal or integer validation.
It's basically three steps in three one liners. If you don't want to truncate the decimals comment the third step. Adjustments for rounding can be made in the third step as well.
// Example Decimal usage;
// <input type="text" oninput="ValidateNumber(this, true);" />
// Example Integer usage:
// <input type="text" oninput="ValidateNumber(this, false);" />
function ValidateNumber(elm, isDecimal) {
try {
// For integers, replace everything except for numbers with blanks.
if (!isDecimal)
elm.value = elm.value.replace(/[^0-9]/g, '');
else {
// 1. For decimals, replace everything except for numbers and periods with blanks.
// 2. Then we'll remove all leading ocurrences (duplicate) periods
// 3. Then we'll chop off anything after two decimal places.
// 1. replace everything except for numbers and periods with blanks.
elm.value = elm.value.replace(/[^0-9.]/g, '');
//2. remove all leading ocurrences (duplicate) periods
elm.value = elm.value.replace(/\.(?=.*\.)/g, '');
// 3. chop off anything after two decimal places.
// In comparison to lengh, our index is behind one count, then we add two for our decimal places.
var decimalIndex = elm.value.indexOf('.');
if (decimalIndex != -1) { elm.value = elm.value.substr(0, decimalIndex + 3); }
}
}
catch (err) {
alert("ValidateNumber " + err);
}
}
Starting from #rebisco answer :
function count_appearance(mainStr, searchFor) {
return (mainStr.split(searchFor).length - 1);
}
function isNumberKey(evt)
{
$return = true;
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31
&& (charCode < 48 || charCode > 57))
$return = false;
$val = $(evt.originalTarget).val();
if (charCode == 46) {
if (count_appearance($val, '.') > 0) {
$return = false;
}
if ($val.length == 0) {
$return = false;
}
}
return $return;
}
Allows only this format : 123123123[.121213]
Demo here demo
Hope it will work for you.
<input type="text" onkeypress="return chkNumeric(event)" />
<script>
function chkNumeric(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
if (charCode == 46) { return true; }
else { return false; }
}
return true;
}
</script>
Following code worked for me
The input box with "onkeypress" event as follows
<input type="text" onkeypress="return isNumberKey(this,event);" />
The function "isNumberKey" is as follows
function isNumberKey(txt, evt) {
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode == 46) {
//Check if the text already contains the . character
if (txt.value.indexOf('.') === -1) {
return true;
} else {
return false;
}
} else {
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
}
return true;
}
I observed that for all the answers provided here, the things are not working if we select some portion of the text in textbox and try to overwrite that part.
So I modified the function which is as below:
<HTML>
<HEAD>
<SCRIPT language=Javascript>
<!--
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
{
return false;
}
if (charCode == 46 && evt.srcElement.value.split('.').length>1 )
{
return false;
}
if(evt.srcElement.selectionStart<evt.srcElement.selectionEnd)
{
return true;
}
if(evt.srcElement.value.split('.').length>1 && evt.srcElement.value.split('.')[1].length==2)
{
return false;
}
return true;
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<INPUT id="txtChar" onkeypress="return isNumberKey(event)"
type="text" name="txtChar">
</BODY>
</HTML>
For Decimal numbers and also allowing Negatives numbers with 2 places for decimals after the point... I modified the function to:
<input type="text" id="txtSample" onkeypress="return isNumberKey(event,this)"/>
function isNumberKey(evt, element){
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) && !(charCode == 46 || charCode == 8 || charCode == 45))
return false;
else {
var len = $(element).val().length;
// Validation Point
var index = $(element).val().indexOf('.');
if ((index > 0 && charCode == 46) || len == 0 && charCode == 46) {
return false;
}
if (index > 0) {
var CharAfterdot = (len + 1) - index;
if (CharAfterdot > 3) {
return false;
}
}
// Validating Negative sign
index = $(element).val().indexOf('-');
if ((index > 0 && charCode == 45) || (len > 0 && charCode == 45)) {
return false;
}
}
return true;
}
<input type="text" class="number_only" />
<script>
$(document).ready(function() {
$('.number_only').keypress(function (event) {
return isNumber(event, this)
});
});
function isNumber(evt, element) {
var charCode = (evt.which) ? evt.which : event.keyCode
if ((charCode != 45 || $(element).val().indexOf('-') != -1) && (charCode != 46 || $(element).val().indexOf('.') != -1) && ((charCode < 48 && charCode != 8) || charCode > 57)){
return false;
}
else {
return true;
}
}
</script>
http://www.encodedna.com/2013/05/enter-only-numbers-using-jquery.htm
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : evt.keyCode;
if(charCode==8 || charCode==13|| charCode==99|| charCode==118 || charCode==46)
{
return true;
}
if (charCode > 31 && (charCode < 48 || charCode > 57))
{
return false;
}
return true;
}
It will allow only numeric and will let you put "." for decimal.
<script type="text/javascript">
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
</script>
#Html.EditorFor(model => model.Orderids, new { id = "Orderids", Onkeypress=isNumberKey(event)})
This works fine.
Best and working solution with Pure-Javascript sample
Live demo : https://jsfiddle.net/manoj2010/ygkpa89o/
<script>
function removeCommas(nStr) {
if (nStr == null || nStr == "")
return "";
return nStr.toString().replace(/,/g, "");
}
function NumbersOnly(myfield, e, dec,neg)
{
if (isNaN(removeCommas(myfield.value)) && myfield.value != "-") {
return false;
}
var allowNegativeNumber = neg || false;
var key;
var keychar;
if (window.event)
key = window.event.keyCode;
else if (e)
key = e.which;
else
return true;
keychar = String.fromCharCode(key);
var srcEl = e.srcElement ? e.srcElement : e.target;
// control keys
if ((key == null) || (key == 0) || (key == 8) ||
(key == 9) || (key == 13) || (key == 27))
return true;
// numbers
else if ((("0123456789").indexOf(keychar) > -1))
return true;
// decimal point jump
else if (dec && (keychar == ".")) {
//myfield.form.elements[dec].focus();
return srcEl.value.indexOf(".") == -1;
}
//allow negative numbers
else if (allowNegativeNumber && (keychar == "-")) {
return (srcEl.value.length == 0 || srcEl.value == "0.00")
}
else
return false;
}
</script>
<input name="txtDiscountSum" type="text" onKeyPress="return NumbersOnly(this, event,true)" />
Working on the issue myself, and that's what I've got so far. This more or less works, but it's impossible to add minus afterwards due to the new value check. Also doesn't allow comma as a thousand separator, only decimal.
It's not perfect, but might give some ideas.
app.directive('isNumber', function () {
return function (scope, elem, attrs) {
elem.bind('keypress', function (evt) {
var keyCode = (evt.which) ? evt.which : event.keyCode;
var testValue = (elem[0].value + String.fromCharCode(keyCode) + "0").replace(/ /g, ""); //check ignores spaces
var regex = /^\-?\d+((\.|\,)\d+)?$/;
var allowedChars = [8,9,13,27,32,37,39,44,45, 46] //control keys and separators
//allows numbers, separators and controll keys and rejects others
if ((keyCode > 47 && keyCode < 58) || allowedChars.indexOf(keyCode) >= 0) {
//test the string with regex, decline if doesn't fit
if (elem[0].value != "" && !regex.test(testValue)) {
event.preventDefault();
return false;
}
return true;
}
event.preventDefault();
return false;
});
};
});
Allows:
11 11 .245 (in controller formatted on blur to 1111.245)
11,44
-123.123
-1 014
0123 (formatted on blur to 123)
doesn't allow:
!##$/*
abc
11.11.1
11,11.1
.42
<input type="text" onkeypress="return isNumberKey(event,this)">
<script>
function isNumberKey(evt, obj) {
var charCode = (evt.which) ? evt.which : event.keyCode
var value = obj.value;
var dotcontains = value.indexOf(".") != -1;
if (dotcontains)
if (charCode == 46) return false;
if (charCode == 46) return true;
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
</script>

Categories

Resources