I need a jquery or js function to only allow enter letters and white spaces.
Thanks in advance.
page:
<p:inputText onkeypress="onlyLetter(this)">
function:
function onlyLetter(input){
$(input).keypress(function(ev) {
var keyCode = window.event ? ev.keyCode : ev.which;
// code
});
}
The following code allows only a-z, A-Z, and white space.
HTML
<input id="inputTextBox" type="text" />
jQuery
$(document).on('keypress', '#inputTextBox', function (event) {
var regex = new RegExp("^[a-zA-Z ]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
Note: KeyboardEvent.which is deprecated as of Jan. 1, 2020
Just use ascii codes (decimal values) of keys/digits that you want to disable or prevent from being work. ASCII Table .
HTML :
<input id="inputTextBox" type="text" />
jQuery :
$(document).ready(function(){
$("#inputTextBox").keydown(function(event){
var inputValue = event.which;
// allow letters and whitespaces only.
if(!(inputValue >= 65 && inputValue <= 120) && (inputValue != 32 && inputValue != 0)) {
event.preventDefault();
}
});
});
jsFiddle Demo
First off, I have little experience in jQuery and will provide a vanilla javascript example. Here it is:
document.getElementById('inputid').onkeypress=function(e){
if(!(/[a-z ]/i.test(String.fromCharCode(e.keyCode))) {
e.preventDefault();
return false;
}
}
Tweaking Ashad Shanto answer a bit. Notice you cant type in y and z if you use the script. You have to change the inputValue from 120 to 123. Here is the ASCII table reference: http://ee.hawaii.edu/~tep/EE160/Book/chap4/subsection2.1.1.1.html Use the script below to type in all the letters, space and backspace.
<script>
$(document).ready(function(){
$("#inputTextBox").keypress(function(event){
var inputValue = event.which;
// allow letters and whitespaces only.
if(!(inputValue >= 65 && inputValue <= 123) && (inputValue != 32 && inputValue != 0)) {
event.preventDefault();
}
console.log(inputValue);
});
});
</script>
you could use this simple method, that I took from this post
<input type="text" name="fullName" onkeypress="return (event.charCode > 64 &&
event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)"
placeholder="Full Name">
jQuery
var letters = /^[A-Za-z ]+$/;
var city_input="";
$(document).ready(function(){
$("#city_name").on("input", function(){
var city_value=$(this).val();
if(city_value==="")
{
city_input=city_value;
}
else if(city_value.match(letters)===null){
$(this).val(city_input);
}
else{
city_input=city_value;
}
});
});
Here is the code which you can understand easily and can modify for any character char exception.
I include the exception for BACKSPACE.
Likewise you can give the exception by including the keycode inside the statement.
var c= ((e.which>=65 && e.which<91) || (e.which==8 /**Here 8 if for the Backspace**/) || (e.which=="your key code"))
https://gist.github.com/SathishSaminathan/e3c509243ead20fcae26c87fdd6f78fd
<!DOCTYPE html>
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>
<body>
<br/>
Enter Only Alphabate: <input id="txtName" name="lname">
<script>
$('#txtName').keypress(function (e) {
var regex = new RegExp("^[a-zA-Z \s]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
else
{
e.preventDefault();
alert('Please Enter Alphabate');
return false;
}
});
</script>
</body>
</html>
For me, adding a space inside input tag after z worked.
<p:inputText onkeydown="return /[a-z ]/i.test(event.key)">
function ValidateAlpha(evt) {
var keyCode = (evt.which) ? evt.which : evt.keyCode if (
(keyCode < 65 || keyCode > 90) &&
(keyCode < 97 || keyCode > 123) &&
keyCode != 32 &&
keyCode != 39
)
Related
I have a function which acts on keydown event and I want it to allow only numbers, backspace and 1 dot. I can't make it work. Here is what I tried:
$('#input[type="number"]').keydown(function(e) {
this.value = this.value.toLowerCase();
var regex = new RegExp("^[0-9.,\b]+$");
var key = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (!regex.test(key)) {
console.log('stop now')
e.preventDefault();
return false;
}
});
It still prevents dot, but allows numbers. I think my Regex is wrong and needs a tweak.
The comment is gone, but some user suggested that it could be to do with the escaping of the . and , ?? Any ideas?
Use keypress insetead of the keydown event. There are different charcodes sent for some keys for the keydown event. The dot is one of them, sending code 190 instead of the ASCII 46. You can play around with it here.
you can use this instead of using regex. I think This will help you
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript" language="jscript">
function fncInputNumericValuesOnly() {
if (!(event.keyCode == 32 || event.keyCode == 46 || event.keyCode == 48 || event.keyCode == 49 || event.keyCode == 50 || event.keyCode == 51 || event.keyCode == 52 || event.keyCode == 53 || event.keyCode == 54 || event.keyCode == 55 || event.keyCode == 56 || event.keyCode == 57))
{
event.returnValue = false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtEmpName" onkeypress="fncInputNumericValuesOnly()" runat="server"></asp:TextBox>
</div>
</form>
</body>
</html>
My answer comes a little late but here I've changed your code to something which may work for you:
var valid_value = '';
$('#input[type="number"]').keyup(function(e) {
var regex = new RegExp(/^[0-9]*\.?[0-9]*$/);
if (!regex.test(this.value)) {
this.value = valid_value;
console.log('stop now');
} else {
valid_value = this.value;
}
});
Have you ever tried something like that?
Of course is not perfect but you can assume it as a starter point:
var whitelist = /^\d+\.?\d+?[\b]?$/;
function testInput() {
var val = document.getElementById('val').value;
var res = document.getElementById('res');
if(whitelist.test(val)) {
res.innerText = 'YEP';
} else {
res.innerText = 'NOOPE';
}
}
<input onchange="testInput()" type="text" id="val"/>
<h1 id="res"></h1>
This is what I came up with in the end. A little manual but does the trick!
$('#input[type="number"]').keydown(function(e) {
if (!(e.keyCode == 190 || e.keyCode == 8 || e.keyCode == 9 || e.keyCode == 13 || e.keyCode == 32 || e.keyCode == 46 || e.keyCode == 48 || e.keyCode == 49 || e.keyCode == 50 || e.keyCode == 51 || e.keyCode == 52 || e.keyCode == 53 || e.keyCode == 54 || e.keyCode == 55 || e.keyCode == 56 || e.keyCode == 57)) {
e.returnValue = false;
e.preventDefault();
return false;
}
});
A bit late to the party, but this would work.
edit: click run code snippit before you downvote
var onlySome = restrictKeys([8,190]) // allow the dot
// decorate the jquery function with some functional goodness
$('input[type="text"]').keydown(onlySome(function(e) {
stackLog(['key alowed', e.which, String.fromCharCode(e.which)]);
}));
// functional function to partially apply restricted keys and callback functiion
function restrictKeys(keys) {
return function(fn) {
return function(e) {
// all codes between 48 and 57 are number and cool to leave in, then just filter out our array
if ((e.which < 48 || e.which > 57) && keys.indexOf(e.which) < 0) {
stackLog(['nope', e.which, String.fromCharCode(e.which)]);
e.preventDefault();
return false
}
return fn.call(this, e);
}
}
}
function stackLog(log) {
var _console = document.querySelector('#console');
_console.innerHTML = JSON.stringify(log) + '\n' + _console.innerHTML;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="enter text here">
<pre id="console"></pre>
i have a input textbox in html and i want to allow the user just 'Y' or 'N' and if he tries to enter any other character then it should show an alert dialog box. so can anyone help me into dis??
jQuery version
$('input').keypress( function( e ){
$(this).val('');
var code = e.which || e.keyCode ;
if ( !( code == 89 || code == 121 ||
code == 78 || code == 110 ) ){
alert('you entered wrong key');
e.preventDefault();
}
});
check it on jsfiddle http://jsfiddle.net/TTgKF/
inline javascript version
<input id="keypress" onkeypress="return allowYN( this, event );" />
and allowYN define as
function allowYN( el, event) {
event = event || window.event;
var charCode = (event.which) ? event.which : event.keyCode;
el.value = '';
isYN = (charCode == 89 || charCode == 121 ||
charCode == 78 || charCode ==110 );
if ( !isYN ) {
alert('you entered wrong key');
}
return isYN;
}
You can add exception for Delete key (46), Backspace key (8) ..
Assuming you're able to get the HTML element by ID, this would check the #myInput element and only accept Y or N.
if ((document.getElementById('myInput').value == 'Y') ||
(document.getElementById('myInput').value == 'N')) {
// Do stuff if it's correct.
} else {
alert("You're doing it wrong!");
}
As previously noted, the best option is to use radio buttons:
<input type="radio" name="yn" value="Y">Y<br>
<input type="radio" name="yn" value="N">N<br>
Then either set one as selected or check on submit that one is selected. Alternatively, you can use scripted input elements, but it is not sensible:
<script>
function validateYN(element) {
var errNode = document.getElementById(element.id + '_err');
if(/^[YN]$/.test(element.value)) {
errNode.innerHTML = '';
} else {
errNode.innerHTML = "You must enter Y or N";
}
}
</script>
Please enter Y or N: <input name="foo" id="foo" onchange="validateYN(this);"
onblur="validateYN(this);">
<span id="foo_err"></span>
you could also try this
$("input").live('keypress', function(e) {
if!( code == 89 || code == 121 ||
code == 78 || code == 110 ) ) {
e.preventDefault();
}
else //your code
<html>
<head>
<script type="text/javascript">
function keyPressed(evt)
{
var theEvent = evt || window.event;
var k = theEvent.keyCode || theEvent.which;
if(k == 89 || k == 78 || k == 8 || k == 46)
return true;
else{
alert("Your Message");
evt.preventDefault();
return false;
}
}
</script>
</head>
<body>
<input type="text" onkeydown="keyPressed(event)" />
</body>
</html>
Guys and gals i have this piece of JavaScript code that only allows for numbers and one decimal period. The problem i'm having is that when i tab over to my textbox controls it highlights the value but i have press backspace to erase then enter a number. That is an extra keystroke that i want to prevent.
Props to the guy who created it found (http://www.coderanch.com/t/114528/HTML-CSS-JavaScript/decimal-point-restriction) and here is the code. I put this on keyUp event.
<script>
// Retrieve last key pressed. Works in IE and Netscape.
// Returns the numeric key code for the key pressed.
function getKey(e)
{
if (window.event)
return window.event.keyCode;
else if (e)
return e.which;
else
return null;
}
function restrictChars(e, obj)
{
var CHAR_AFTER_DP = 2; // number of decimal places
var validList = "0123456789."; // allowed characters in field
var key, keyChar;
key = getKey(e);
if (key == null) return true;
// control keys
// null, backspace, tab, carriage return, escape
if ( key==0 || key==8 || key==9 || key==13 || key==27 )
return true;
// get character
keyChar = String.fromCharCode(key);
// check valid characters
if (validList.indexOf(keyChar) != -1)
{
// check for existing decimal point
var dp = 0;
if( (dp = obj.value.indexOf( ".")) > -1)
{
if( keyChar == ".")
return false; // only one allowed
else
{
// room for more after decimal point?
if( obj.value.length - dp <= CHAR_AFTER_DP)
return true;
}
}
else return true;
}
// not a valid character
return false;
}
</script>
<input type="text" class="decimal" value="" />
And in Js use this
$('.decimal').keyup(function(){
var val = $(this).val();
if(isNaN(val)){
val = val.replace(/[^0-9\.]/g,'');
if(val.split('.').length>2)
val =val.replace(/\.+$/,"");
}
$(this).val(val);
});
Check this fiddle: http://jsfiddle.net/2YW8g/
THis worked for me, i have taken this answer from "Nickalchemist" and take none of its credit.
If you can't use an already stable and well-know library, you can try something like this:
document.write('<input id="inputField" onkeyup="run(this)" />');
function run(field) {
setTimeout(function() {
var regex = /\d*\.?\d?/g;
field.value = regex.exec(field.value);
}, 0);
}
I know it doesn't prevent the wrong char to appear, but it works.
PS: that setTimeout(..., 0) is a trick to execute the function after the value of the field has already been modified.
Here is a sample solution that will accept a number with one(1) decimal point only. e.g 1.12, 11.5
Enter a number with one(1) decimal point only<br />
<input type="text" id="decimalPt"> <br />
$('.decimalPt').keypress(function(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode == 8 || charCode == 37) {
return true;
} else if (charCode == 46 && $(this).val().indexOf('.') != -1) {
return false;
} else if (charCode > 31 && charCode != 46 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
});
Take a look at this: https://jsfiddle.net/sudogem/h43r6g7v/12/
I think it would be best to use something that already exists... like Masked Input Plugin with jQuery
Try this,
$('input').on('keydown', function (event) {
return isNumber(event, this);
});
function isNumber(evt, element) {
var charCode = (evt.which) ? evt.which : evt.keyCode;
if ((charCode != 190 || $(element).val().indexOf('.') != -1) // “.” CHECK DOT, AND ONLY ONE.
&& (charCode != 110 || $(element).val().indexOf('.') != -1) // “.” CHECK DOT, AND ONLY ONE.
&& ((charCode < 48 && charCode != 8)
|| (charCode > 57 && charCode < 96)
|| charCode > 105))
return false;
return true;
}
Be sure to test on any browser. The accepted answer doesn't work on Firefox.
Try HTML5 type number:
<input type="number" placeholder="1.0" step="0.1">
You could define min="0" max="10"
Reference:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number#Controlling_input_size
Note: type="number" is not supported in Internet Explorer 9 and earlier versions.
I solve my problem with like this.
const sanitize = (value = '') => value.replace(/(-(?!\d))|[^0-9|-]/g, '') || ''
export const toNumeric = value => {
let digits = sanitize(value)
// parseInt with 0 fix/avoid NaN
digits = parseInt(0 + digits)
let newValue = digits.toString().padStart(4, 0)
return newValue
}
Am using this javascript for restrict users to type only numbers and only one dot as decimal separator.
<script type="text/javascript">
function fun_AllowOnlyAmountAndDot(txt)
{
if(event.keyCode > 47 && event.keyCode < 58 || event.keyCode == 46)
{
var txtbx=document.getElementById(txt);
var amount = document.getElementById(txt).value;
var present=0;
var count=0;
if(amount.indexOf(".",present)||amount.indexOf(".",present+1));
{
// alert('0');
}
/*if(amount.length==2)
{
if(event.keyCode != 46)
return false;
}*/
do
{
present=amount.indexOf(".",present);
if(present!=-1)
{
count++;
present++;
}
}
while(present!=-1);
if(present==-1 && amount.length==0 && event.keyCode == 46)
{
event.keyCode=0;
//alert("Wrong position of decimal point not allowed !!");
return false;
}
if(count>=1 && event.keyCode == 46)
{
event.keyCode=0;
//alert("Only one decimal point is allowed !!");
return false;
}
if(count==1)
{
var lastdigits=amount.substring(amount.indexOf(".")+1,amount.length);
if(lastdigits.length>=2)
{
//alert("Two decimal places only allowed");
event.keyCode=0;
return false;
}
}
return true;
}
else
{
event.keyCode=0;
//alert("Only Numbers with dot allowed !!");
return false;
}
}
</script>
<td align="right">
<asp:TextBox ID="txtQ1gTarget" runat="server" Width="30px" CssClass="txtbx" MaxLength="6" onkeypress="return fun_AllowOnlyAmountAndDot(this);"></asp:TextBox>
</td>
But the onkeypress(this) event returns object required error in that function at this place
var amount = document.getElementById(txt).value;
What's my mistake here?
This is a great place to use regular expressions.
By using a regular expression, you can replace all that code with just one line.
You can use the following regex to validate your requirements:
[0-9]*\.?[0-9]*
In other words: zero or more numeric characters, followed by zero or one period(s), followed by zero or more numeric characters.
You can replace your code with this:
function validate(s) {
var rgx = /^[0-9]*\.?[0-9]*$/;
return s.match(rgx);
}
That code can replace your entire function!
Note that you have to escape the period with a backslash (otherwise it stands for 'any character').
For more reading on using regular expressions with javascript, check this out:
http://www.regular-expressions.info/javascript.html
You can also test the above regex here:
http://www.regular-expressions.info/javascriptexample.html
Explanation of the regex used above:
The brackets mean "any character inside these brackets." You can use a hyphen (like above) to indicate a range of chars.
The * means "zero or more of the previous expression."
[0-9]* means "zero or more numbers"
The backslash is used as an escape character for the period, because period usually stands for "any character."
The ? means "zero or one of the previous character."
The ^ represents the beginning of a string.
The $ represents the end of a string.
Starting the regex with ^ and ending it with $ ensures that the entire string adheres to the regex pattern.
Hope this helps!
Use Jquery instead. Add a decimal class to your textbox:
<input type="text" class="decimal" value="" />
Use this code in your JS. It checks for multiple decimals and also restrict users to type only numbers.
$('.decimal').keyup(function(){
var val = $(this).val();
if(isNaN(val)){
val = val.replace(/[^0-9\.]/g,'');
if(val.split('.').length>2)
val =val.replace(/\.+$/,"");
}
$(this).val(val);
});
Check this fiddle: http://jsfiddle.net/2YW8g/
Hope it helps.
Just add the code below in your input text:
onkeypress='return event.charCode == 46 || (event.charCode >= 48 && event.charCode <= 57)'
Instead of using this:
onkeypress="return fun_AllowOnlyAmountAndDot(this);"
You should use this:
onkeypress="return fun_AllowOnlyAmountAndDot(this.id);"
function isNumberKey(evt,id)
{
try{
var charCode = (evt.which) ? evt.which : event.keyCode;
if(charCode==46){
var txt=document.getElementById(id).value;
if(!(txt.indexOf(".") > -1)){
return true;
}
}
if (charCode > 31 && (charCode < 48 || charCode > 57) )
return false;
return true;
}catch(w){
alert(w);
}
}
<html>
<head>
</head>
<body>
<INPUT id="txtChar" onkeypress="return isNumberKey(event,this.id)" type="text" name="txtChar">
</body>
</html>
<input type="text" class="decimal" value="" />
$('.decimal').keypress(function(evt){
return (/^[0-9]*\.?[0-9]*$/).test($(this).val()+evt.key);
});
I think this simple solution may be.
This works best for me.
I also apply a currency formatter on blur where the decimal part is rounded at 2 digits just in case after validating with parseFloat.
The functions that get and set the cursor position are from Vishal Monpara's blog. I also do some nice stuff on focus with those functions. You can easily remove 2 blocks of code where 2 decimals are forced if you want and get rid of the set/get caret functions.
<html>
<body>
<input type="text" size="30" maxlength="30" onkeypress="return numericValidation(this,event);" />
<script language="JavaScript">
function numericValidation(obj,evt) {
var e = event || evt; // for trans-browser compatibility
var charCode = e.which || e.keyCode;
if (charCode == 46) { //one dot
if (obj.value.indexOf(".") > -1)
return false;
else {
//---if the dot is positioned in the middle give the user a surprise, remember: just 2 decimals allowed
var idx = doGetCaretPosition(obj);
var part1 = obj.value.substr(0,idx),
part2 = obj.value.substring(idx);
if (part2.length > 2) {
obj.value = part1 + "." + part2.substr(0,2);
setCaretPosition(obj, idx + 1);
return false;
}//---
//allow one dot if not cheating
return true;
}
}
else if (charCode > 31 && (charCode < 48 || charCode > 57)) { //just numbers
return false;
}
//---just 2 decimals stubborn!
var arr = obj.value.split(".") , pos = doGetCaretPosition(obj);
if (arr.length == 2 && pos > arr[0].length && arr[1].length == 2)
return false;
//---
//ok it's a number
return true;
}
function doGetCaretPosition (ctrl) {
var CaretPos = 0; // IE Support
if (document.selection) {
ctrl.focus ();
var Sel = document.selection.createRange ();
Sel.moveStart ('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}
// Firefox support
else if (ctrl.selectionStart || ctrl.selectionStart == '0')
CaretPos = ctrl.selectionStart;
return (CaretPos);
}
function setCaretPosition(ctrl, pos){
if(ctrl.setSelectionRange)
{
ctrl.focus();
ctrl.setSelectionRange(pos,pos);
}
else if (ctrl.createTextRange) {
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
</script>
</body>
</html>
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 46 || charCode > 57)) {
return false;
}
return true;
}
you should use this function and write the properties of this element ;
HTML Code:
<input id="deneme" data-mini="true" onKeyPress="return isNumber(event)" type="text"/>`
try This Code
var check = function(evt){
var data = document.getElementById('num').value;
if((evt.charCode>= 48 && evt.charCode <= 57) || evt.charCode== 46 ||evt.charCode == 0){
if(data.indexOf('.') > -1){
if(evt.charCode== 46)
evt.preventDefault();
}
}else
evt.preventDefault();
};
document.getElementById('num').addEventListener('keypress',check);
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<input type="text" id="num" value="" />
</body>
</html>
<script type="text/javascript">
function numericValidation(txtvalue) {
var e = event || evt; // for trans-browser compatibility
var charCode = e.which || e.keyCode;
if (!(document.getElementById(txtvalue.id).value))
{
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
else {
var val = document.getElementById(txtvalue.id).value;
if(charCode==46 || (charCode > 31 && (charCode > 47 && charCode < 58)) )
{
var points = 0;
points = val.indexOf(".", points);
if (points >= 1 && charCode == 46)
{
return false;
}
if (points == 1)
{
var lastdigits = val.substring(val.indexOf(".") + 1, val.length);
if (lastdigits.length >= 2)
{
alert("Two decimal places only allowed");
return false;
}
}
return true;
}
else {
alert("Only Numarics allowed");
return false;
}
}
}
</script>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtHDLLevel" MaxLength="6" runat="server" Width="33px" onkeypress="return numericValidation(this);" />
</div>
</form>
You can use this
Javascript
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)&&(charCode!=46)) {
return false;
}
return true;
}
Usage
<input onkeypress="return isNumber(event)" class="form-control">
This function will prevent entry of anything other than numbers and a single dot.
function validateQty(el, evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode != 45 && charCode != 8 && (charCode != 46) && (charCode < 48 || charCode > 57))
return false;
if (charCode == 46) {
if ((el.value) && (el.value.indexOf('.') >= 0))
return false;
else
return true;
}
return true;
var charCode = (evt.which) ? evt.which : event.keyCode;
var number = evt.value.split('.');
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
};
<input type="text" onkeypress='return validateQty(this,event);'>
Try this for multiple text fileds (using class selector):
Click here for example..
var checking = function(event){
var data = this.value;
if((event.charCode>= 48 && event.charCode <= 57) || event.charCode== 46 ||event.charCode == 0){
if(data.indexOf('.') > -1){
if(event.charCode== 46)
event.preventDefault();
}
}else
event.preventDefault();
};
function addListener(list){
for(var i=0;i<list.length;i++){
list[i].addEventListener('keypress',checking);
}
}
var classList = document.getElementsByClassName('number');
addListener(classList);
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<input type="text" class="number" value="" /><br><br>
<input type="text" class="number" value="" /><br><br>
<input type="text" class="number" value="" /><br><br>
<input type="text" class="number" value="" /><br><br>
</body>
</html>
<script type="text/Javascript">
function checkDecimal(inputVal) {
var ex = /^[0-9]+\.?[0-9]*$/;
if (ex.test(inputVal.value) == false) {
inputVal.value = inputVal.value.substring(0, inputVal.value.length - 1);
}
}
</script>
In this function there is an error while editing it when I have added 2 digits(I have defined it's limit 2) after decimal point than it returns false, like if we have to change 1486.00 to 1582.00 without clearing the whole input or deleting any number after decimal point it will return false.
There is a small change required, where the condition of count is 1(count === 1) there add a condition event.target.selectionStart > amount.indexOf(".")
The final code will be
const validDecimal = (event) => {
if ((event.charCode > 47 && event.charCode < 58) || event.charCode === 46) {
var amount = event.target.value;
var present = 0;
var count = 0;
do {
present = amount.indexOf(".", present);
if (present != -1) {
count++;
present++;
}
} while (present != -1);
if (present === -1 && amount.length === 0 && event.charCode === 46) {
event.charCode = 0;
// alert("Wrong position of decimal point not allowed !!");
return false;
}
if (count >= 1 && event.charCode === 46) {
event.charCode = 0;
// alert("Only one decimal point is allowed !!");
return false;
}
if (count === 1 && event.target.selectionStart > amount.indexOf(".")) {
var lastdigits = amount.substring(
amount.indexOf(".") + 1,
amount.length
);
if (lastdigits.length >= 2) {
// alert("Two decimal places only allowed");
event.charCode = 0;
return false;
}
}
return true;
} else {
event.charCode = 0;
// alert("Only Numbers with dot allowed !!");
return false;
}
};
Please try below code. this could help you to solve it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script>
function fnAllowNumbersAndDotKey(input, event)
{
var charCode = (event.which) ? event.which : event.keyCode;
if (charCode == 46)
{
//only one dot (.) allow
if (input.value.indexOf('.') === -1)
{
return true;
}
else
{
return false;
}
}
else
{
if (charCode > 31 && (charCode < 48 || charCode > 57))
{
return false;
}
}
return true;
}
</script>
</head>
<body>
<form method='post' >
<input type="text" name='amount' class='form-control' onkeypress="return fnAllowNumbersAndDotKey(this, event);" maxlength="50" />
</form>
</body>
</html>
<input type="text" class="form-control" id="odometer_reading" name="odometer_reading" placeholder="Odometer Reading" onblur="odometer_reading1();" onkeypress='validate(event)' required="" />
<script>
function validate(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
</script>
Hope this could help someone
$(document).on("input", ".numeric", function() {
this.value = this.value.match(/^\d+\.?\d{0,2}/);});
I wanted a text field to take only numbers ans some control keys and number should be exactly four digit long, not less not more. My validation code is
function checkValidInput()
{
$(".validateYearTextBox").keydown(function(event)
{
// Allow only delete, backspace,left arrow,right arraow and Tab
if (
event.keyCode == 46 //delete
|| event.keyCode == 8 //backspace
|| event.keyCode == 37 //leftarow
|| event.keyCode == 39 //rightarrow
|| event.keyCode == 9 //tab
)
{
// let it happen, don't do anything
}
else {
// Ensure that it is a number and stop the keypress
if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode <96 ||event.keyCode > 105) ) {
event.preventDefault();
}
}
});
$(".validateYearTextBox").keyup(function(event)
{
var val = $(this).val();
if (val.length > 4){
alert ("Max length is 4");
val = val.substring(0, valore.length - 1);
$(this).val(val);
$(this).focus();
return false;
}
});
}
Here, my first validation is working, but my send one is not working.
I am calling this validation function in my aspx page like this
<script type="text/javascript">
$(document).ready(function(){
checkValidInput();
}
</script>
What is going wrong?
Simplify it:
function checkValidInput() {
// Allow only delete, backspace, left arrow, right arrow,
// Tab, ctrl+v and numbers
$(".validateYearTextBox").keydown(function(event) {
if (!((event.keyCode == 46 ||
event.keyCode == 8 ||
event.keyCode == 37 ||
event.keyCode == 39 ||
event.keyCode == 9) ||
(event.ctrlKey && event.keyCode == 86) || // Edit: Added to allow ctrl+v
$(this).val().length < 4 &&
((event.keyCode >= 48 && event.keyCode <= 57) ||
(event.keyCode >= 96 && event.keyCode <= 105)))) {
// Stop the event
event.preventDefault();
return false;
}
});
// Edit: Added validate after copy+paste.
// This removes non-numeric characters and truncates the length
// to 4 if the user copy + pasted.
$(".validateYearTextBox").change(function(event) {
var value = $(this).val();
value = value.replace(/[^0-9]/g,'');
value = value.substr(0,4);
$(this).val(value);
});
}
$(document).ready(function() {
checkValidInput();
});
http://jsfiddle.net/nwellcome/687kD/
Edit: Personally I like the Masked Input jQuery plugin but that might be a heavy-handed solution if this is all you need to do.
There are many, many jQuery plugins that already do this in one form or another.
One that does mostly1 what you want is Masked Input Plugin. If you can, I recommend using something existing, working and proven, rather than reinventing.
1 The only part that it doesn't seem to do is display an error if a user tries to enter more than n characters but I'm sure you could modify the plugin or add a length check to the <input>
Use regular expression :
enter code here
function validator(elem,msg)
{
var exp=/^([0-9]+)$/; //it only allows for numbers
if(elem.value.match(exp))
{return true;}
else
{
alert(msg);
elem.focus();
return false;
}
}
the html code :
enter code here
<html><head>
<script src="javasript.js" type="text/javascript">
</head>
<body>
<form method=POST>
<input type='text' maxlength=4 name='num' id='num'>
<input type='submit' value=OK onClick="validator(document.getElementById('num'),'Only four numbers and numbers only!');">
</form> //the maxlength in input text tag restrict the maximum length of the input
</body></html>
Here's a simple way of doing it. Stores the old text before an event changes the text. Then check to see if the new text is valid or not. If it isn't, then revert back to the old text. To further ensure the maximum of 4 characters, add a maxlength attribute to all <input type="text"> elements.
jQuery.fn.forceNumericOnly = function() {
return this.each(function() {
var oldText;
$(this).keyup(function(e) {
var newText = $(this).val();
if (newText != "" && (isNaN(newText) || val.length > 4))
$(this).val(oldText);
else
oldText = $(this).val();
})
$(this).blur(function(e) {
var newText = $(this).val();
if (newText != "" && (isNaN(newText) || val.length > 4))
$(this).val(newText = oldText);
else
oldText = $(this).val();
});
})
};
$(".validateYearTextBox").forceNumericOnly();
if (document.ExamEntry.examnum.value=="") {
msg+="You must enter your examination number \n";
document.ExamEntry.examnum.focus();
document.getElementById('examnum').style.color="red";
result = false;
}
$('.numeric').keypress(function(e) {
var verified = (e.which == 8 || e.which == undefined || e.which == 0) ? null : String.fromCharCode(e.which).match(/[^0-9]/);
if (verified || e.delegateTarget.value.length>3 || e.ctrlKey ==true) { if(e.which!=8 ){e.preventDefault();}}
}).on('paste',function(e){ e.preventDefault();});
Here add class=numeric to input text box'. it will allow only 4 digits if you want to limit size to 2 digits change to e.delegateTarget.value.length>1 and so on as index starts from zero
Use HTML input maxlength attribute for this and also set the size value of fixing width 4 in same input size attribute.
<input type="text" maxlength="4" size="4">
Here is a simple answer that takes care of copy paste and all.
$(document).on("input", ".validateYearTextBox", function() {
var value = this.value
value = value.replace(/\D/g,'');
for (i = 0; i < value.length; i++) {
if (i > 3) {
value = value.replace(value[i], '')
}
}
});