How to assign only numbers to text box in MVC view - javascript

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>

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="">

Can't enter numbers using numbers pad

I have a function that formats user input into phone format.
It works fine except it's not allowing numbers from numbers pad at the right, Only the numbers at the top of the alphabetic characters.
I want to keep the same format, But allow entering numbers from numbers pad.
Here is a fiddle:
https://jsfiddle.net/s1wyrmk6
Here is the code:
HTML:
<input type="text" id="phone">
JS/jQuery:
(function ($) {
$.fn.usPhoneFormat = function (options) {
var params = $.extend({
format: 'xxx-xxx-xxxx',
international: false,
}, options);
if (params.format === 'xxx-xxx-xxxx') {
$(this).bind('paste', function (e) {
e.preventDefault();
var inputValue = e.originalEvent.clipboardData.getData('Text');
if (!$.isNumeric(inputValue)) {
return false;
} else {
inputValue = String(inputValue.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3"));
$(this).val(inputValue);
$(this).val('');
inputValue = inputValue.substring(0, 12);
$(this).val(inputValue);
}
});
$(this).on('keydown touchend', function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
var curchr = this.value.length;
var curval = $(this).val();
if (curchr == 3 && e.which != 8 && e.which != 0) {
$(this).val(curval + "-");
} else if (curchr == 7 && e.which != 8 && e.which != 0) {
$(this).val(curval + "-");
}
$(this).attr('maxlength', '12');
});
} else if (params.format === '(xxx) xxx-xxxx') {
$(this).on('keydown touchend', function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
var curchr = this.value.length;
var curval = $(this).val();
if (curchr == 3 && e.which != 8 && e.which != 0) {
$(this).val('(' + curval + ')' + " ");
} else if (curchr == 9 && e.which != 8 && e.which != 0) {
$(this).val(curval + "-");
}
$(this).attr('maxlength', '14');
});
$(this).bind('paste', function (e) {
e.preventDefault();
var inputValue = e.originalEvent.clipboardData.getData('Text');
if (!$.isNumeric(inputValue)) {
return false;
} else {
inputValue = String(inputValue.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3"));
$(this).val(inputValue);
$(this).val('');
inputValue = inputValue.substring(0, 14);
$(this).val(inputValue);
}
});
}
}
}(jQuery));
Change the following
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) { return false; }
The additional range 96 to 105 is greater than 57 currently, which causes this statement to catch the numpad.
To allow the numpad:
if (e.which != 8 && e.which != 0 && (e.which < 48 || (e.which > 57 && !(e.which>=96 && e.which<=105 )))) {
return false;
}

Blocking spaces ASP MVC and 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>

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;
}
});
});

Key Press Event In Jquery

I have many input types in the form .Now i want that the user can enter only integer values in the input types.The input can be like this 110.00 only two values after ..But i am not able to get this features.
I have done with the interger input but i am not getting how can we do this :
Code
$(".amount_class").live("keypress",function(e){
var charCode = (e.which) ? e.which : e.keyCode;
var Enteted = String.fromCharCode(e.which).toLowerCase();
if ((charCode >= 48 && charCode <= 57) || charCode == 8 || charCode == 9 || charCode == 37 || charCode == 39 || (charCode == 46 && Enteted != '.'))
return true;
else
return false;
});
The values are amount and it can be decimal but not more than two after decimal sign.Please help me
I have done this and working fine for me :
$('.salary').live("keypress",function(e) {
var charCode = (e.which) ? e.which : e.keyCode;
var Enteted = String.fromCharCode(e.which).toLowerCase();
if(!((charCode >= 48 && charCode <= 57) || charCode == 8 || charCode == 9 || (charCode == 37 && Enteted !='%') || charCode == 39 || charCode == 46)) {
e.preventDefault();
}
if(charCode == 46 && $(this).val().indexOf('.') != -1 && Enteted ==".") {
e.preventDefault();
} // prevent if already dot
if(charCode == 46 && Enteted =="." && !$(this).val()) {
e.preventDefault();
}
if($(this).val().indexOf('.')!=-1){
if($(this).val().split(".")[1].length >= 2){
if(charCode != 8 && charCode != 46) e.preventDefault();
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixed(2);
}
}
return this;
});
Use as below
HTML
<input type="text" id="checkDecimal" class="decimal" />
JS
$(function () {
$('#checkDecimal').bind('paste', function () {
var self = this;
setTimeout(function () {
if (!/^\d*(\.\d{1,2})+$/.test($(self).val())) $(self).val('');
}, 0);
});
$('#checkDecimal').keypress(function (e) {
var character = String.fromCharCode(e.keyCode)
var newValue = this.value + character;
if (isNaN(newValue) || parseFloat(newValue) * 100 % 1 > 0) {
e.preventDefault();
return false;
}
});
});
have a look here.
Regex - /^\d+(\.\d{0,2})?$/g;
i have experimented here
<!DOCTYPE html>
<html>
<head>
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$('#input_field').keyup(function(e) {
var regex = /^\d+(\.\d{0,2})?$/g;
if (!regex.test(this.value)) {
this.value = '';
}
});
});
</script>
</head>
<body>
<input type= "text" id = "input_field" name ="input_field" value=""/>
</body>
</html>
The logic is every time a user entering a number you have to check two things.
Has the user entered decimal point?
Are the decimal places more than two?
For the first one you can use $(this).val().indexOf('.') != -1For the second one you can use $(this).val().substring($(this).val().indexOf('.'), $(this).val().indexOf('.').length).length > 2
Here is the code:
$('.amount_class').keypress(function (event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
var text = $(this).val();
if ((text.indexOf('.') != -1) && (text.substring(text.indexOf('.')).length > 2)) {
event.preventDefault();
}
});
And the DEMO
Simply use
value.toFixed(2);
thats it..

Categories

Resources