I'm trying to avoid input of any marks except numbers and letters with input string on my page.php:
<input type="text" id="input">
From this answer only allow English characters and numbers for text input <input type="text" id="input" class="clsAlphaNoOnly"> :
$(document).ready(function () {
$('.clsAlphaNoOnly').keypress(function (e) { // Accept only alpha numerics, no special characters
var regex = new RegExp("^[a-zA-Z0-9 ]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
});
})
or this:
$(function(){
$("#input").keypress(function(event){
var ew = event.which;
if(ew == 32)
return true;
if(48 <= ew && ew <= 57)
return true;
if(65 <= ew && ew <= 90)
return true;
if(97 <= ew && ew <= 122)
return true;
return false;
});
});
in both cases string is clear, but I'm using two types of input with button click $("#btn").click(function() to process input and $(document).keypress(function(e) with hit on enter key on keyboard for same input. By some reason if I include this methods to avoid extra marks in string, pressing on enter key does not allows to input inserted value.
This way works fine:
<input type="text" id="input" onkeypress="return (event.charCode >= 65 && event.charCode <= 90) || (event.charCode >= 97 && event.charCode <= 122) || (event.charCode >= 48 && event.charCode <= 57)" />
but I want avoid extra code with html in page.php. I'm trying to figure out, what causes blocking of entering for inserted value with given methods
Would tell you may miss event parameter ?
Without jQuery works like this for me in 3 browsers:
function clsAlphaNoOnly (e) { // Accept only alpha numerics, no special characters
var regex = new RegExp("^[a-zA-Z0-9 ]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
}
function clsAlphaNoOnly2 () { // Accept only alpha numerics, no special characters
return clsAlphaNoOnly (this.event); // window.event
}
<input type="text" id="input" onkeypress="clsAlphaNoOnly(event)" onpaste="return false;">
<input type="text" id="input" onkeypress="clsAlphaNoOnly2()" onpaste="return false;">
One way of validation is using pattern attribute on input element
MDN: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation#Validating_against_a_regular_expression
In your case:
<input type="text" pattern="[a-zA-Z0-9]*">
If you really do not want to use the Regex method as the comments bellow advice you, then you can use this simple code :
document.querySelector("input#testInput").addEventListener("input", function(){
const allowedCharacters="0123456789azertyuiopqsdfghjklmwxcvbnAZERTYUIOPQSDFGHJKLMWXCVBNzáàâãéèêíïóôõöúçñÁÀÂÃÉÈÍÏÓÔÕÖÚÇÑ "; // You can add any other character in the same way
this.value = this.value.split('').filter(char => allowedCharacters.includes(char)).join('')
});
<input type="text" id="testInput">
Instead of javascript you could use a pattern along with required. pattern will allow you to specify a required pattern for the input, and required will make the input required. Both must evaluate to true in order for the form to submit.
<form>
<input type="text" id="input" pattern="[a-zA-Z0-9]+" required>
<input type="submit">
</form>
HTML Input Way :
1- Simple HTML5 Input
<input type="text" pattern="[a-zA-Z0-9]*">
2- Inline Function
<input type="text" id="input" onkeypress="return (event.charCode >= 65 && event.charCode <= 90) || (event.charCode >= 97 && event.charCode <= 122) || (event.charCode >= 48 && event.charCode <= 57)" />
Jquery Way :
$('#ID').on('keypress', function (e) { var code = ('charCode' in e) ? e.charCode : e.keyCode; if (!(code > 47 && code < 58) && !(code > 64 && code < 91) && !(code > 96 && code < 123)) {e.preventDefault();}});
Javascript Function :
function allowAlphaNumericSpace(e) {
var code = ('charCode' in e) ? e.charCode : e.keyCode;
if ( !(code > 47 && code < 58) && !(code > 64 && code < 91) && !(code > 96 && code < 123)) { e.preventDefault();}};
<input type="text" onkeypress="allowAlphaNumeric(event)" />
Related
i have input numeric field with format like 20,000.00
how to remove Nan if user not key in the first field?
document.getElementById("BasicSalary_x").onblur =function (){
this.value = parseFloat(this.value.replace(/,/g, ""))
.toFixed(2)
.toString()
.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function isNumberKey(evt) {
var charCode = ((evt.which) ? evt.which : event.keyCode);
return !(charCode > 31 && (charCode != 46 && charCode != 44 && (charCode < 48 || charCode > 57)));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="tel" onkeypress="return isNumberKey(event)" id="BasicSalary_x" placeholder="Basic Salary (RM)" >
<input type="tel" value="0.00" onkeypress="return isNumberKey(event)" id="deduction" placeholder="Deduction (RM)" >
If you get NaN with parseFloat, then you can use ||0 to convert it to zero (or any default you prefer).
parseFloat("x,xx".replace(/,/g, "")) || 0
Alternatively, you can check if it's a number with isNaN
var val = this.value.replace(/,/g, "");
if (isNaN(val)) {
alert("Please only enter valid values.");
} else {
... parseFloat(val) ...
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
I have this simple HTML document
<input type="text" id="my_text" onkeypress="valid_numbers(event);" size="30"/>
<script type="javascript">
function valid_numbers(e)
{
var key=e.which || e.KeyCode;
if ( key >=48 && key <= 57)
// to check whether pressed key is number or not
return true;
else return false;
}
</script>
What I want is:
onkeypress of my_text if the pressed key is number allow otherwise deny writing of the character.
But the above code doesn't work, my_text element accept any character, what is wrong with the above code ?!..
Help Please!..
I think the easy way to do this would be:
<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57' />
But the problem comes up when you paste some text then HTML5's number type input may be a better choice:
<input type="number" />
BTW you can find better suggestions if you search the SO like this.
Some very complex answers, but it can be as simple as using a regular expression to return the result of checking if the input was a number or not:
<input onkeypress="return /\d/.test(String.fromCharCode(event.keyCode || event.which))">
Note that this will not stop entering of non-digit characters by pasting, dragging and dropping or script.
var input = document.getElementById('my_text');
input.onkeydown = function(e) {
var k = e.which;
if ( (k < 48 || k > 57) && (k < 96 || k > 105) && k!=8) {
e.preventDefault();
return false;
}
};
and
<input type="text" id="my_text" size="30"/>
Allows only [0-9] number, numpad number, arrow, BackSpace, Tab, Del as wel as Ctrl + C, Ctrl + V, Ctrl + A.
Allow only one dot.
Remove if last char is dot on a blur event.
element.on('keydown', function(e) {
var arrowsKeyCodes = [37, 38, 39, 40];
var numPadNumberKeyCodes = [96, 97, 98, 99, 100, 101, 102, 103, 104, 105];
var dots = [110, 190];
var tabBackDel = [8, 9, 46];
var acv = [65, 67, 86];
// Allow only one dot.
if (e.target.value.indexOf('.') !== -1 && dots.indexOf(e.keyCode) !== -1) {
event.preventDefault();
}
// allow only [0-9] number, numpad number, arrow, BackSpace, Tab, Del
// Ctrl + C, Ctrl + V, Ctrl + A
if (
(e.keyCode < 48 &&
arrowsKeyCodes.indexOf(e.keyCode) === -1 || e.keyCode > 57 &&
numPadNumberKeyCodes.indexOf(e.keyCode) === -1 &&
dots.indexOf(e.keyCode) === -1
) &&
tabBackDel.indexOf(e.keyCode) === -1 &&
(e.ctrlKey === false || e.ctrlKey === true && acv.indexOf(e.keyCode) === -1)
) {
e.preventDefault();
}
});
element.on('blur', function(e) {
var value = e.target.value;
if (value.substring(value.length - 1) === '.')
e.target.value = value.substring(0, value.length - 1)
});
Have not tried this out, but you can use parseInt in your function to check like:
var t = document.getElementById("my_test").value;
if (parseInt(t) == 'NaN') {
// not a number
}
<html>
<body>
<input id="edValue" type="text" onKeyPress="edValueKeyPress()" onKeyUp="edValueKeyPress()"><br>
</body>
<script>
function edValueKeyPress()
{
var edValue = document.getElementById("edValue");
var s = edValue.value;
var lblValue = document.getElementById("lblValue");
if ( s >=48 && s <= 57)
// to check whether pressed key is number or not
return true;
else return false;
}
</script>
</html>
Use this tested code.it's help you.
You can Simply use JavaScript or HTML5 to execute this
JavaScript:
<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'></input>
HTML 5 (does not require JavaScript, and also does not behave in standard way in many modern browsers.)
<input type="number">
FIDDLE
More on this may look here.
I am facing a weird issue regarding a textbox after using validation for preventing special characters.Lets say I enter some text in it.Now if I change the caret position in between the already entered text and try to add text there, the caret automatically jumps to the end of the text.
Any workaround for this?
Note:- I am using IE 11.
Textbox :-
<div class="form-group">
<label data-i18n="rpt_name"></label>
<span class="required">*</span>
<input type="text" class="form-control" id="subNameID">
</div>
The source of error is validation for avoiding special characters.
$('#subNameID').bind('keypress', function (e) {
if ($('#subNameID').val().length == 0) {
var k = e.which;
var ok = k >= 65 && k <= 90 || // A-Z
k >= 97 && k <= 122 || // a-z
k >= 48 && k <= 57; // 0-9
if (!ok) {
e.preventDefault();
}
}
})
Also tried using below solution but gives the same issue.
$("#subNameID").on("keypress keyup paste", function (e) {
if (e.keyCode == 37 || e.keyCode == 39 || e.keyCode == 32 || e.keyCode == 8)
return true;
this.value = this.value.replace(/[^a-zA-Z0-9\-\._\s]/g, '');
});
I used this code only numeric input but ^ char can input? How can i fix?
<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'></input>
<input type="text" onkeypress='return( event.charCode >= 48 && event.charCode <= 57) || (event.charCode==94) '></input>
This will solve your purpose
function validateInput(evt)
{
if ((evt.charCode >= 48 && evt.charCode <= 57) || (evt.charCode==94))
return true;
else
return false;
}
<input type="text" onkeypress='return validateInput(event)'></input>
I want to use an if-statement to run code only if the user types in a letter or a number.
I could use
if (event.keyCode == 48 || event.keyCode == 49 || event.keyCode == 50 || ...) {
// run code
}
Is there an easier way to do this? Maybe some keycodes don't work in all web browsers?
If you want to check a range of letters you can use greater than and less than:
if (event.keyCode >= 48 && event.keyCode <= 57) {
alert('input was 0-9');
}
if (event.keyCode >= 65 && event.keyCode <= 90) {
alert('input was a-z');
}
For a more dynamic check, use a regular expression:
const input = String.fromCharCode(event.keyCode);
if (/[a-zA-Z0-9-_ ]/.test(input)) {
alert('input was a letter, number, hyphen, underscore or space');
}
See the MDC documentation for the keyCode property, which explains the difference between that and the which property and which events they apply to.
Use event.key and modern JS!
No number codes anymore. You can check key directly.
const key = event.key.toLowerCase();
if (key.length !== 1) {
return;
}
const isLetter = (key >= 'a' && key <= 'z');
const isNumber = (key >= '0' && key <= '9');
if (isLetter || isNumber) {
// Do something
}
You could also use a simple regex. ^$ ensures 1 char, i ignores case
/^[a-z0-9]$/i.test(event.key)
or individually:
const isLetter = /^[a-z]$/i.test(event.key)
const isNumber = /^[0-9]$/i.test(event.key)
First, if you're doing this, make sure it's in the keypress event, which is the only event for which you can reliably obtain information about the character the user has typed. Then I'd use the approach Andy E suggested:
document.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charStr = String.fromCharCode(charCode);
if (/[a-z0-9]/i.test(charStr)) {
alert("Letter or number typed");
}
};
If you want to check for backspace, I'd use the keydown event instead and check for a keyCode of 8 because several browsers (including Chrome) do not fire a keypress event for the backspace key.
if (event.keyCode >= 48 && event.keyCode <= 90) {
// the key pressed was alphanumeric
}
For numeric values:
function validNumeric() {
var charCode = event.which ? event.which : event.keyCode;
var isNumber = charCode >= 48 && charCode <= 57;
if (isNumber) {
return true;
} else {
return false;
}
}
Here, 48 to 57 is the range of numeric values.
For alphabetic values:
function validAlphabetic() {
var charCode = event.which ? event.which : event.keyCode;
var isCapitalAlphabet = charCode >= 65 && charCode <= 90;
var isSmallAlphabet = charCode >= 97 && charCode <= 122;
if (isCapitalAlphabet || isSmallAlphabet) {
return true;
} else {
return false;
}
}
Here, 65 to 90 is the range for capital alphabets (A-Z), and
97 to 122 is the range for small alphabets (a-z).
As #Gibolt said, you should use event.key.
Because charCode, keyCode and which are being deprecated.
To detect letters & numbers when using <input> or <textarea> you can use input event.
This event fires when <input> or <textarea> value changes so there is no need to worry about keys like Alt, Shift, arrows etc. Even more - if you use mouse to cut part of the text the event fires as well.
var element = document.getElementById('search');
element.addEventListener('input',function(e){
console.log(element.value);
});
<input id="search" type="text" placeholder="Search" autocomplete="off">
Simply you can add your Html forms in the input field like this:
...onkeypress ="return /[a-z .# 0-9]/i.test(event.key)" required accesskey="4"
You don't need any function. This Validation works only with the email field. Don't use naming or number. To use number, remove email regular expression like this:
...onkeypress ="return /[a-z ]/i.test(event.key)" required accesskey="4"
For number only:
...onkeypress ="return /[0-9]/i.test(event.key)" required accesskey="4"
Don't forget, to add for each input fields their own value.
<div class="form-group">
<input type="Email" class="form-control " id="EMAILADDRESS" name="EMAILADDRESS" placeholder="Email Address" autocomplete="false" onkeypress ="return /[a-z .# 0-9]/i.test(event.key)" required accesskey="4"/>
</div>
$('#phone').on('keydown', function(e) {
let key = e.charCode || e.keyCode || 0;
// 32 = space - border of visible and non visible characters - allows us to backspace and use arrows etc
// 127 - delete
if (key > 32 && (key < 48 || key > 58) && key !== 127) {
e.preventDefault();
return false;
}
});
modified answer of #user4584103, allows us to remove characters, and navigate in input box and filter out every not number character
You can also use charCode with onKeyPress event:
if (event.charCode > 57 || event.charCode < 48) {
itsNotANumber();
} else {
itsANumber();
}
number validation, works fine for me
$(document).ready(function () {
$('.TxtPhone').keypress(function (e) {
var key = e.charCode || e.keyCode || 0;
// only numbers
if (key < 48 || key > 58) {
return false;
}
});
});
Accept numbers or letters with JavaScript by Dynamic Process using regular expression.
Add onkeypress event for specific control
onkeypress="javascript:return isNumber(event)"
function numOnly(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charStr = String.fromCharCode(charCode);
if (/[0-9]/i.test(charStr)) {
return true;
} else {
return false;
}
}
function Alphanum(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charStr = String.fromCharCode(charCode);
if (/[a-z0-9]/i.test(charStr)) {
return true;
} else {
return false;
}
}
Use $.isNumeric(value); return type is boolean
$(document).ready(function () {
return $.isNumeric(event.keyCode);
});
A very simple, but useful method to try (i needed on a keyup event, letters only),
use console.log() to check, typeOfKey is a string so you can compare. typeOfKey is either (Digit or Key)
let typeOfKey = e.code.slice(0,-1)
if(typeOfKey === 'Key'){
console.log(typeOfKey)
}