Javascript to restrict entry to numbers in textbox - javascript

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

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

How to automatically add a dot after the nth character automatically in textarea?

I have to write a textarea in which the user should enter the given latitude in decimal degrees.
For example: 60.45678 or 05.1
What should I do to make a dot appear in the textarea automatically after the second character?
I already have a function to check if the characters are numbers:
<script language=Javascript>
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
} </script>
Maybe it can be somehow modified so that it would add a dot and check if the first two numbers are smaller than 90?
<textarea name="LongitudeEW" placeholder="Longitude East/West." onkeypress="return isNumberKey(event)"></textarea>
Thanks for the help :)
Try this
var DECIMAL_REGEXP = /(?<=^.{2}$)/g;
function handleKeyUp(e) {
var target = e.target;
var charCode = e.which || e.keyCode;
if(charCode > 31 && (charCode < 48 || charCode > 57)){
return false;
}
target.value = target.value.replace(DECIMAL_REGEXP, '.');
return true;
}
var DECIMAL_REGEXP = /(?<=^.{2}$)/g;
function handleKeyUp(e) {
var target = e.target;
var charCode = e.which || e.keyCode;
if(charCode > 31 && (charCode < 48 || charCode > 57)){
return false;
}
target.value = target.value.replace(DECIMAL_REGEXP, '.');
return true;
}
<textarea name="LongitudeEW" placeholder="Longitude East/West." onkeypress="return handleKeyUp(event)"></textarea>
In case you want to bind to the elements keypress event vs inlining:
// cache the regexp
var DECIMAL_REGEXP = /(?<=^.{2}$)/g;
// ref the textarea
var textrea = document.getElementById('LongitudeEW');
// bind to the keypress event
textrea.addEventListener('keypress', function(e){
var target = e.target,
charCode = e.which || e.keyCode;
if(charCode > 31 && (charCode < 48 || charCode > 57)){
e.preventDefault();
}
target.value = target.value.replace(DECIMAL_REGEXP, '.');
});
<textarea id="LongitudeEW" name="LongitudeEW" placeholder="Longitude East/West."></textarea>
You can try using this library: https://nosir.github.io/cleave.js/
For example as your requirement. Hope to help, my friend :))
<script src="cleave.js"></script>
<input class="input-element" type="textarea" >
<script>
$(function(){
var cleave = new Cleave('.input-element', {
delimiter: '.',
blocks: [2, 100],
numericOnly: true
});
});
</script>

JavaScript: Mobile number validation with numbers and max length

I'm trying to have a JS which has the requirement as below
I have a textbox of type number and whenever i typed inside that textbox should ONLY ALLOW numbers [0-9] and it should NOT ALLOW the length of the numbers entered to be more than 8 digits.
Eg:
12345678 - Allow
1234 - Dont Allow
1234%^ - Dont Allow
My Html:
<input type="number" id="txt_number" maxlength="8" onkeypress="return isNumber(event)">
My JS
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57 ||charCode>=190)) {
return false;
}
return true;
}
Please help me.
Appreciate.
Thanks
please try this
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
$(function () {
$(".numericOnly").bind('keypress', function (e) {
if (e.keyCode == '9' || e.keyCode == '16') {
return;
}
var code;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
if (e.which == 46)
return false;
if (code == 8 || code == 46)
return true;
if (code < 48 || code > 57)
return false;
}
);
$(".numericOnly").bind("paste", function (e) {
$("#lblSearchError").text("Phone no must be numeric digit only !!!");
$('#lblSearchError').show('slow').delay(3000).queue(function (n) {
$(this).hide('slow'); n();
});
e.preventDefault();
});
$(".numericOnly").bind('mouseenter', function (e) {
var val = $(this).val();
if (val != '0') {
val = val.replace(/[^0-9]+/g, "")
$(this).val(val);
}
});
});
with this function you can restrict user to enter other than numeric values and user won't be able to past any non-numeric data. this works for me
You can use it by class name or by ID
Use RegEx match:
function checkMonum(){
var input=document.getElementById('txt_number').value;
var state=false;
var re=/^[\d\.]{8}$/;
var output = re.test(input);
if(output==true){
state=true;
}
return state;
}
i change method match with test, you can check in FF. i am on mobile in chrome. Exactly with 8 digits or has period

Cross Browser issue with Keyup Validation

<script type="text/javascript">
function numbersonly(e){
var unicode=e.charCode? e.charCode : e.keyCode
if (unicode!=8){ //if the key isn't the backspace key (which we should allow)
if (unicode<65||unicode>90) //if not a Capital Alphabet
return false //disable key press
}
}
</script>
<form>
<input type="text" size=18 onkeyup="return numbersonly(event)">
</form>
This code is working fine. But IE doesn't support charcode. and In Keycode, 65 to 90 range includes both capital and lower case letters. How to resolve the issue?
It will not handled by the simple one you have to check many conditions in that case like,
Checking caps lock on or not
Use this function for this,
function isCapslock(e){
e = (e) ? e : window.event;
var charCode = false;
if (e.which) {
charCode = e.which;
} else if (e.keyCode) {
charCode = e.keyCode;
}
var shifton = false;
if (e.shiftKey) {
shifton = e.shiftKey;
} else if (e.modifiers) {
shifton = !!(e.modifiers & 4);
}
if (charCode >= 97 && charCode <= 122 && shifton) {
return true;
}
if (charCode >= 65 && charCode <= 90 && !shifton) {
return true;
}
return false;
}
Refered from http://dougalmatthews.com/articles/2008/jul/2/javascript-detecting-caps-lock/
Additionally
just use e.which in jquery. They normalize this value for all browsers.
Additionally you can check for e.shiftKey.
Source Using e.keyCode || e.which; how to determine the differance between lowercase and uppercase?

JavaScript keycode allow number and plus symbol only

I have this JavaScript function that is used to force user only type number in the textbox. Right now and I want to modify this function so it will allow the user to enter plus (+) symbol. How to achieve this?
//To only enable digit in the user input
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
Since the '+' symbol's decimal ASCII code is 43, you can add it to your condition.
for example :
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode != 43 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
This way, the Plus symbol is allowed.
This code might work. I added support for SHIFT + (equal sign) and the numpad +.
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
var shiftPressed = (window.Event) ? e.modifiers & Event.SHIFT_MASK : e.shiftKey;
if ((shiftPressed && charCode == 187) || (charCode == 107))
{
return true;
} else if ((charCode > 95) && (charCode < 106)) {
return true;
} else if (charCode > 31 && (charCode < 48 || charCode > 57))) {
return false;
} else {
return true;
}
}
this is stupid ... not really an answer at all. I would suggest you to do following.
function isNumberKey(evt)
{
console.log(evt.keyCode);
return false;
}
And find out the ranges of all keys, and implement it.
It's Work. Javascript keycode allow number and plus symbol only
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript form validation</title>
</head>
<body>
<form name="form1" action="#">
Mobile Number: <input type='text' id='PhoneNumber' maxlength="10" onKeyPress="return IsNumeric3(event);" ondrop="return false;" onpaste="return false;"/>
<span id="error3" style="color: Red; display: none">* Input digits (0 - 9)</span>
</form>
<script type="text/javascript">
var specialKeys = new Array();
specialKeys.push(8);
specialKeys.push(43);
specialKeys.push(37);
specialKeys.push(39);
//Backspace
function IsNumeric3(e) {
var keyCode = e.which ? e.which : e.keyCode
var ret = (keyCode != 37 && keyCode != 8 && keyCode != 46 && (keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
document.getElementById("error3").style.display = ret ? "none" : "inline";
return ret;
}
</script>
<script>
function stringlength(inputtxt, minlength, maxlength)
{
var field = inputtxt.value;
var mnlen = minlength;
var mxlen = maxlength;
if(field.length<mnlen || field.length> mxlen)
{
alert("Please input the 10 digit mobile number");
return false;
}
else
{
return true;
}
}
</script>
</body>
</html>
Thank you friends
Here is the modified code:
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if ( (charCode >= 48 && charCode <= 57) || charCode == 43)
return true;
return false;
}
Here is the code . working fine with numbers and plus + sign in phone fields. you will have to implement the code on keydown function . target the id/class of the particular phone field and use keydown function.
//allows only these keys
// backspace, delete, tab, escape, and enter
if ( event.keyCode == 107 || event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
// Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
return;
}
else {
// Ensure that it is a number and stop the keypress
if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
event.preventDefault();
}
}
Using experience of my colleagues above, write one function, that fits me well. It filters all except numbers, arrows and backspace. Maybe it would be useful for somebody.
function isKeyCorrect(keyEvent) {
var charCode = keyEvent.which ? keyEvent.which : keyEvent.keyCode;
var isNotNumber = charCode < 48 || charCode > 57;
var isNotArrow = charCode < 37 || charCode > 40;
var isNotBackspace = charCode !== 8;
return isNotNumber && isNotArrow && isNotBackspace;
}
<script type="text/javascript">
$(document).ready(function() {
`enter code here` $('#form-1').submit(function(msg) {
$.post("action.php?act=login",$(this).serialize(),function(data){
if (data == 'ERR:A3001004') { alert("Güvenlik hatası, sayfayı yenileyin."); }
else if (data == 'TIMEEND') { alert("Anahtarınızın süresi dolmuş."); }
else if (data == 'INVALID') { alert("Geçersiz anahtar şifresi girdiniz."); }
else if (data == 'OK') { alert("Başarıyla giriş yaptınız. Yetişkinlere göre içerik barındıran sitelere erişim sağlayabilirsiniz."); }
});
return false;
});
});
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
</script>

Categories

Resources