How prevent whitespace in input field with plain javascript - javascript

I have an username input field and trying to prevent user fill them with white spaces.
<input type="text" name="username" />
i do this and whitespace isn't blocked
var
field = document.querySelector('[name="username"]');
field.addEventListener('keypress', function ( event ) {
var
key = event.keyCode;
return (key !== 32);
});

Use event.preventDefault to prevent its default behavior.
var field = document.querySelector('[name="username"]');
field.addEventListener('keypress', function ( event ) {
var key = event.keyCode;
if (key === 32) {
event.preventDefault();
}
});
<input type="text" name="username" />
If you want to use the return false;, then you should use the onkeypress of the input instead, jsfiddle
field.onkeypress = function(e) {
var key = e.keyCode;
return (key !== 32);
};

Modify the input like:
<input type="text" name="username" onkeypress="CheckSpace(event)"/>
Then the javascript is:
<script type="text/javascript">
function CheckSpace(event)
{
if(event.which ==32)
{
event.preventDefault();
return false;
}
}

Try checking for all the different kinds of whitespaces listed here Are there other whitespace codes like &nbsp for half-spaces, em-spaces, en-spaces etc useful in HTML?
So you code would be:
var field = document.querySelector('[name="username"]');
field.addEventListener('keypress', function ( event ) {
var
key = event.keyCode;
return (key !== 32 && key !== 160 && key != 5760 && key != 8192 && key != 8192 && key != 8194 && key != 8195 && key != 8196 && key != 8197 && key != 8198 && key != 8199 && key != 8200 && key != 8201 && key != 8202 && key != 8232 && key != 8233 && key != 8239 && key != 8287 && key != 12288);
});
Here is the complete list of all the different kinds of whitespaces: https://en.wikipedia.org/wiki/Whitespace_character#Spaces_in_Unicode

In case anyone needs this to be done which will replace all whitespace automatically and will not allow user to put space and will force them to put username without space even then copy paste . Here is the code.
<script type="text/javascript">
var field = document.querySelector('[name="username"]');
field.addEventListener('keyup', function ( event ) {
var userName = field.value;
userName = userName.replace(/\s/g, '');
field.value = userName;
});
</script>

HTML only solution using the pattern attribute and regex.
<form>
<input type="text" name="username" pattern="[^\s]+">
<button type="submit">Submit</button>
</form>

const key = e.keyCode
const keyCodes = [
32, 160, 5760, 8192, 8192, 8194, 8195, 8196, 8197, 8198, 8199,
8200, 8201, 8202, 8232, 8233, 8239, 8287, 12288,
]
if (keyCodes.some((val) => val === key)) {
e.preventDefault()
}
here is a simple solution !

Hey i have simple solution regarding your question try one
If you want to submit only text and whitespace than use this one
<input type="text" name="Name" required pattern="[a-zA-Z ]+" >
If you want to submit number and whitespace than use this one
<input type="text" name="Name" required pattern="[0-9 ]+" >
If you want to insert text not whitespace than use this one
<input type="text" name="Name" required pattern="[a-zA-Z]+" >
Use any line according to your requirements no extra line of code or condition simple and secure

Related

How to filter input fields using javascript

I want to filter input fields with numbers 1 to 4, and character "/". Here is what I have tried:
HTML:
<input id='scc' type='text' name='secc3' maxlength='4' onkeypress='return isNumber(event)' placeholder='Security code' required>
JavaScript:
function isNumber(evt) {
var key = evt.key;
if (key != 1 || key != 2 || key != 3 || key != 4) return false;
return true;
}
function isValid(event) {
//this array contains the key codes for every valid character
//other codes can be found here: https://keycode.info/
const validChars = ["Digit1", "Digit2", "Digit3", "Digit4", "Numpad1", "Numpad2", "Numpad3", "Numpad4", "Slash"];
return validChars.includes(event.code);
}
<input id='scc' type='text' name='secc3' maxlength='4' onkeypress='return isValid(event)' placeholder='Security code' required>

How to allow only digits to be entered into an input[type="number"] field?

I have an input field in which the user should only be able to enter digits [0-9].
document.getElementById("integer").addEventListener('input', restrictToInteger);
function restrictToInteger() {
this.value = this.value.replace(/[^\d]/g, '');
}
<input type="number" id="integer" />
jsFiddle Demo
The problem is this: When I enter a number (eg. 1234) and then press dot (.), + or - the content of the input field is automatically deleted by the browser (value is set to "" = empty string). But why? Changing the type from number to text seems to fix the problem. But then I lose the up/down arrow functionality of the input field. Any ideas?
HTML 4 has an event called onkeypress. With that attribute we can do this without using additional JS:
<input type="number" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57">
Here digits from 0 to 9 are allowed using the event.charCode from 48 to 57.
I think the reason that the browser clean the input value it is because a string with two dots it is not a number.
Some corrections about your code:
You need to change your expression regular if you want to accept number with decimal part. Now, you are only express that you want to accept digits [0-9] and no more chars.
To accomplish want you want, you need to change /[^\d]/g to /[^\d.]/g.
document.getElementById("integer").addEventListener('input', restrictToInteger);
function restrictToInteger()
{
this.value = this.value.replace(/[^\d.]/g, '');
}
<input type="number" id="integer" />
HOWEVER: If you define your input as number type, the regular expression is not needed. So, you just need to define the input like this and should your to your case:
<input type="number" id="integer" />
[THE SOLUTION]
To fully meet your needs, I came with a solution that catch the keydown event of the input and check if there is any '.' on the input. If yes, I prevent the char to go to the input.
document.getElementById("integer").addEventListener('keydown', restrictToInteger);
var lastCodeWasDot = false;
function restrictToInteger(e)
{
var inputValue = document.getElementById("integer").value;
var isDot = false;
var isDot = (e.keyCode && e.keyCode == 110) || (e.charCode && e.charCode == 190);
console.log(e.keyCode);
if(isDot && (inputValue.indexOf(".") > -1 || inputValue == "" || lastCodeWasDot)) {
e.preventDefault();
}
lastCodeWasDot = isDot;
}
<input type="number" id="integer" />
Explaning the solution:
The line of code var isDot = (e.keyCode && e.keyCode == 110) || (e.charCode && e.keyCode == 190) || false; is needed because cross browser compatibility.
I don't now why but if you try to get the value from an input number type in the firefox, and if the value finishes with a dot, the value that you will get will be without the last dot of the input. To fix that, I needed to add the variable lastCodeWasDot to fix this issue.
NOTE: The number input can accept floating point numbers, including negative symbols and the e or E character (check out this post)
Based on the answers of Alexandru-Ionut Mihai and natchiketa I created the following solution:
document.getElementById("integer").addEventListener("input", allowOnlyDigits);
function allowOnlyDigits() {
if (this.validity.valid) {
this.setAttribute('current-value', this.value.replace(/[^\d]/g, ""));
}
this.value = this.getAttribute('current-value');
}
<input type="number" id="integer" />
On input the value is checked for validity. If it is valid, all non-digits are removed and the value is stored in a custom attribute of the element. If the value is not valid, the previous value is restored.
Notes:
The RegEx-replace is required only for Internet Explorer as it allows you to enter , or . at the end of a number.
Tested in IE, Edge, Chrome and Firefox
Chrome still allows you to enter a + before and one , after the number.
I found one issue: If you initialize the field with a value, the value is lost when you first hit an invalid char on the keyboard.
Another issue: You can't enter a negative number.
The only problem was your input type. Change it to text and it should work !
function validate(e) {
var charCode = e.keyCode? e.keyCode : e.charCode
if (!(charCode >= 48 && charCode <= 57)) {
if(!(charCode>=37 && charCode<=40))
if(charCode!=8 && charCode!=46)
return false;
}
}
<input type="number" id="integer" pattern="[0-9]"
onkeydown="return validate(event)"/>
You can achieve your requirement by copying the old value of input and using setAttribute and getAttribute methods in order to store the values.
function myFunction(input){
input.setAttribute('current-value',"");
input.oninput=function(){
let currentValue=input.getAttribute('current-value');
if(input.value!='' || (currentValue>=1 && currentValue<=9))
input.setAttribute('current-value',input.value);
input.value=input.getAttribute('current-value');
}
}
<input type="number" oninput="myFunction(this)"/>
<input type="number" oninput="myFunction(this)"/>
<input type="number" oninput="myFunction(this)"/>
<input type="number" oninput="myFunction(this)"/>
<input type="number" oninput="myFunction(this)"/>
When you call oninput, the <input> element first calls its internal methods to handle the value. This prevents your function from seeing any actual erroneous characters, namely e+-. - all used by JavaScript to format numbers.
You can see this by adding console.log calls before and after changing this.value.
console.log(this.value);
this.value=this.value.replace(/[^\d]/g, '');
console.log(this.value);
There is never any difference!
If you try, for example:
console.log(this.value);
this.value+=1; // or *=2 for numerical fun
console.log(this.value);
you can see a difference.
So your function is hastening the normal internal calls <input type='number'/> would normally make when handling illegal input.
Can't quite see why the field is left blank and not 1 though.
I would switch to a cancelable event like keydown.
That way you can prevent the character from being typed in the first place:
var cancelEvent = function (e) {
e.preventDefault();
return false;
},
restrictToInteger = function restrictToInteger(e) {
var acceptableInput = /[0-9]/g,
clipboardKeys = /[zxcv]/ig,
field = e.key || e.char,
isClipboardOperation = (clipboardKeys.test(field) && e.ctrlKey),
inputIsAcceptable = field ? (
acceptableInput.test(field)
|| field.length > 1
|| isClipboardOperation
) : true;
if (!inputIsAcceptable) {
cancelEvent(e);
}
},
ensureIntegerValueOnPaste = function ensureIntegerValueOnPaste(e) {
var data = e.clipboardData || e.dataTransfer,
text = data.getData('text'),
int = parseInt(this.value + text, 10);
if (isNaN(int)) {
cancelEvent(e);
} else {
window.setTimeout(function () {
e.target.value = int;
}, 0);
}
},
input = document.getElementById("integer");
input.addEventListener('keydown', restrictToInteger);
input.addEventListener('drop', ensureIntegerValueOnPaste);
input.addEventListener('paste', ensureIntegerValueOnPaste);
<input type="number" id="integer" />
Updated fiddle: https://jsfiddle.net/838pa8hv/2/
Disclaimers:
Only tested in Chrome.
The test for field.length > 1 is to catch non-numeric keys that are valid as the up/down arrows have a value of ArrowUp and ArrowDown respectively. This also allows for keys like Shift (or Home, Backspace, Delete, etc.) to be pressed as well.
Edit:
To handle pastes (and drops), you can do the same thing in those respective events. Updated fiddle and code snippet above.
Edit:
If the expected usability is to be able to paste/drop partial numbers into the field and to not allow negative integers, then you can just change how int is defined in the ensureIntegerValueOnPaste function. Updated fiddle and code snippet above.
You don't need regular expression, you can use parseFloat() function. Your input type remains unchanged, there are still "arrows" to increase/decrease number and also it makes sure that your input will not start with zero.
document.getElementById("integer").addEventListener('input', restrictToInteger);
function restrictToInteger() {
this.value = parseFloat(this.value);
}
<input type="number" id="integer" />
You have to check if the value is not a number and then stop user.
document.getElementById("integer").addEventListener('input', restrictToInteger);
function restrictToInteger(e)
{
if(isNaN(e.data)){
alert("only numbers allowed");
}
}
<input type="number" id="integer" />

Html and javascript input validation

I am trying to have my input only accept Numbers and the '.', it is working great but it doesn't allow for number pad number keys. I cant seem to find the exact answer online.
HTML
<input type="text" id="ItemTotal#i#" name="ItemTotal#i#" value="#qPriceAct#" onkeypress="return isNumeric(event)" onkeydown="return keyispressed(event);">
JavaScript
//prevent , and $ from being input
function keyispressed(e){
var charval= String.fromCharCode(e.keyCode);
if(isNaN(charval) && (e.which != 8 ) && (e.which != 190 )){
return false;
}
return true;
}
//is input numeric
function isNumeric (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();
}
}
Thanks for the help!
The best way I believe would be to add a class to all the inputs that only allow numbers. Then you can restrict any input that doesn't match the pattern or a number/decimal.
function numberVerfication(value) {
var pattern=/^[0-9]*(\.)?[0-9]*$/;
if (value.match(pattern) != null){
return value
}
else {
var p=/[0-9]*(\.)?[0-9]*/;
return value.match(p)[0];
}
}
$('.numbersOnly').keyup(function(e) {
e.target.value = numberVerfication(e.target.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class='numbersOnly' type="text" id="ItemTotal#i#" name="ItemTotal#i#" value="#qPriceAct#">
Simple using REGEXP
HTML
<input type="text" class='numbersOnly' id="ItemTotali" name="ItemTotal#i" value="qPriceAct">
JQUERY
$('.numbersOnly').keyup(function (e) {
this.value = this.value.replace(/[^0-9\.]/g, '');
});
JAVA SCRIPT
function numValidate(that){
that.value = that.value.replace(/[^0-9\.]/g, '');
}
<input type="text" onkeypress='numValidate(this)' onkeyup='numValidate(this)' class='numbersOnly' id="ItemTotali" name="ItemTotal#i" value="qPriceAct"/>
Demo
function numberVerfication(value){
return value.replace(/[^0-9.\-+]/g, '');
}
$('.numbersOnly').keyup(function(e){
e.target.value=numberVerfication(e.target.value);
});

Why this function for input with number only doesnt work actually with input type:number?

$('input').on('keyup',function(){
this.value = this.value.replace(/[^0-9\.]/g,'');
});
From : https://stackoverflow.com/a/891816/622813
After I tested with <input type="number">
When I type something like 1234a so value is blank
But not with <input type="text"> when I type 1234a value is still 1234
Just wonder why ?
Demo : http://jsfiddle.net/PV2fQ/
Update :
<input type="tel"> this work good ... http://jsfiddle.net/PV2fQ/10/ Why?
If you do a console.log(this.value); before your replace statement, you will see that for non-number inputs <input type="number"> gets a blank value itself i.e this.value = '';
This seems to be the internal implementation of this input type.
An alternative: http://jsfiddle.net/PV2fQ/12/
$('input').keypress(function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
});

Limit number of characters in input type number

Im trying to limit to X number the characters in a input (type of number). ive tried a lot of options and none seems to work. I dont want to use the option tel as it needs the numeric keyboard on a mobile device (yes, with ., and all the symbols) I tried also the pattern solution but it only worked for iOS, didnt work in android (displayed the normal keyboard).
The best way would be that if the user hits the limit dont let him type anymore, if he wants to highlight the text and re-type a different number he is allow to. Just not let him type more than the specified number of characters.
So, any help is appreciated.
Note: charCode is non-standard and deprecated, whereas keyCode is simply deprecated.
Check this code
JavaScript
<script>
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;
}
function checkLength()
{
var fieldLength = document.getElementById('txtF').value.length;
//Suppose u want 4 number of character
if(fieldLength <= 4){
return true;
}
else
{
var str = document.getElementById('txtF').value;
str = str.substring(0, str.length - 1);
document.getElementById('txtF').value = str;
}
}
and HTML input with number type below
onInput //Is fired also if value change from the side arrows of field in Chrome browser
<input id="txtF" type="number" onKeyPress="return check(event,value)" onInput="checkLength()" />
Fiddle Demo
Update -- Little bit generic code example
Change above function into this one
function checkLength(len,ele){
var fieldLength = ele.value.length;
if(fieldLength <= len){
return true;
}
else
{
var str = ele.value;
str = str.substring(0, str.length - 1);
ele.value = str;
}
}
In HTML use like this
<!-- length 4 -->
<input id="txtF" type="number" onKeyPress="return check(event,value)" onInput="checkLength(4,this)" />
<!-- length 5 -->
<input type="number" onKeyPress="return check(event,value)" onInput="checkLength(5,this)" />
<!-- length 2 -->
<input type="number" onKeyPress="return check(event,value)" onInput="checkLength(2,this)" />
Demo
Another option - the tel input type abides by the maxlength and size attributes.
<input type="tel" size="2" maxlength="2" />
<input type="tel" size="10" maxlength="2" />
May be it will be useful.
Here is field to input Patient Age. It allows to input 3 numbers only.
HTML
<input autocomplete="off" class="form-control" id="Patient_Age" max="150" maxlength="3" name="PatientAge" placeholder="Age" size="3" type="number" value="0">
JS
<script>
$(function () {
$("#Patient_Age").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter
if ($(this).val().length <= 2 || $.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
// Allow: Ctrl+A
// (e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
else {
event.preventDefault();
}
// Ensure that it is a number and stop the keypress
if ($(this).val().length <= 2 || (e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
else {
event.preventDefault();
}
});
}); // end of $
</script>
The HTML5 number type input has min and max attributes.
If you wanted to limit the number of characters to 1 you could set a min of 0 and a max of 9.
You can also set the step attribute, which is 1 by default, but would come in use if you wanted the ability to select decimals or other rounded numbers.
<input type="number" maxlength="1" max="9" min="1" size="1" />
Here's the full demo
please review this code
<script language="javascript" type="text/javascript">
function limitText(limitField, limitCount, limitNum) {
if (limitField.value.length > limitNum) {
limitField.value = limitField.value.substring(0, limitNum);
} else {
limitCount.value = limitNum - limitField.value.length;
}
}
</script>
<form name="myform">
<input name="limitedtextfield" type="text" onKeyDown="limitText(this.form.limitedtextfield,this.form.countdown,15);"
onKeyUp="limitText(this.form.limitedtextfield,this.form.countdown,15);" maxlength="15"><br>
<font size="1">(Maximum characters: 15)<br>
You have <input readonly type="text" name="countdown" size="3" value="15"> characters left.</font>
</form>
I think this requires the onkeyup event handler.
Use this handler to keep on entering numbers till 5 keyup's are encountered. After this , don't let the the number to be entered by returning a 0, unless key pressed is backspace or delete .
You can try thiss jQuery code :
In HTML
<input type="number" id="number" />
In JS
$(document).ready(function () {
var element = document.getElementById('number');
$("#number").keydown(function (event) {
// Allow only backspace and delete
if($(this).val().length <= 9 || event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 )
{
if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9) {
// 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();
}
}
}else{
event.preventDefault();
}
});
});
I have not any idea wheather its working on IOS N Android but its work on all browser.
DEMO
For Decimal values, lets say "25.2" code is as under.
if(thisObj.value.indexOf(".") >=0)
{
if(fieldLength <= 4)
{
return true;
}
else
{
var str = thisObj.value;
str = str.substring(0, str.length - 1);
thisObj.value = str;
}
}
else
{
if(fieldLength <= 2)
{
return true;
}
else
{
var str = thisObj.value;
str = str.substring(0, str.length - 1);
thisObj.value = str;
}
}
You can easily do it like this,
<input type="text" pattern="\d*" maxlength="4">
Proper way 2020 for type number is to check on keydown validation and it should work like this: onkeypress="checkValidation(fieldValue);" <-- on input in html and in js:
checkValidation(a) {
if (`${a}`.length < 8) {
return true;
} else {
return false;
}
}
Use the maxlength property like this.
<input type="text" maxlength="5"/>
Dude why go for javascript? Just try
<input type="text" maxlength="4" size="4">
maxlength will anyways define a maximum length for the input field.
Hope this solved the problem :)
EDIT: Since you specifically want numbers, why dont you use the above and then run a jquery validation to check for numbers? That will also work..
EDIT: Okay, try
<input type="number" name="pin" min="1000" max="9999">
Did you try the property maxlength ?
<input type="text" maxlength="5" name="user" >

Categories

Resources