I am doing validation on an input type='text' element. I have wired up the 'paste' and the 'keydown' events to trap the input and restrict it to just numbers. The keydown seems to work without a hitch, however, I could not seem to get any of the browsers to actually NOT PASTE the text into the field (I see that there is a beforepaste event, which may be the ticket -- however it appears to not be supported by firefox. In the end, I resulted to just blanking out the input if the value was not a number. This causes a momentary flicker, but seems to work.
Is there a cleaner way to do this? Am I missing something? Is there anyway to prevent the flicker? I know the HTML5 has a type='number', but I'm not ready to go there yet.
<input type="text" id="number" />
<script type="text/javascript">
$(document).ready(function () {
enableNumericOnlyEntry("#number");
function enableNumericOnlyEntry(object) {
$(object).bind('paste', numericOnlyPaste);
$(object).bind('keydown', null, numericOnlyKeyDown);
function numericOnlyPaste(event) {
var inputText = "";
var element = event.target;
setTimeout(function () {
var text = $(element).val();
if (isNaN(text)) {
$(element).val("")
return false;
}
}, 0);
}
function numericOnlyKeyDown(event) {
// Allow: backspace, delete, tab, escape, and enter
if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
// Allow: Ctrl+A/a
(event.keyCode == 65 || event.keyCode == 97) && (event.ctrlKey === true) ||
// Allow: Ctrl+C/c
(event.keyCode == 67 || event.keyCode == 99) && (event.ctrlKey === true) ||
// Allow: Ctrl+V/v
(event.keyCode == 86 || event.keyCode == 118) && (event.ctrlKey === true) ||
// Allow: Ctrl+X/x
(event.keyCode == 88 || event.keyCode == 120) && (event.ctrlKey === true) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
// let it happen, don't do anything
return true;
}
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)) {
return false;
}
}
}
}
});
I've used this project to create a field that is a masked edit box, you could remove the underscore to it also so it doesn't look like a masked edit. Really easy to use: http://digitalbush.com/projects/masked-input-plugin/
then you'd use something like $("#box").mask("9999999"); and your good to go, works great!
HTML5's <input type="number"> is really where you want to go with this. If you're working with browsers that support it (basically everything except Safari and old versions of IE), it does everything you want.
That said, why not register an onpaste handler so you can reduce pasted content to just numbers after the user pastes?
Related
How can I make contenteditable elements only allow entry of numeric values?
I tried to use something like:
onkeypress='return event.charCode >= 48 && event.charCode <= 57'
...on elements that are contenteditable, but it still allows entry of alphabetic characters.
Thanks!
Why not just use an input?
<input type="number">
If you still want to use contenteditable, you can add an event listener like so:
$("#myeditablediv").keypress(function(e) {
if (isNaN(String.fromCharCode(e.which))) e.preventDefault();
});
This will block all characters that are not numbers (0-9)
Salaam
This will allow only numbers
$('[contenteditable="true"]').keypress(function(e) {
var x = event.charCode || event.keyCode;
if (isNaN(String.fromCharCode(e.which)) && x!=46 || x===32 || x===13 || (x===46 && event.currentTarget.innerText.includes('.'))) e.preventDefault();
});
I have also tested decimals. There are three major conditions to get allowed
Is a Number and Not delete button
Not Space
Not Enter Button
Allow Decimal point only once
Let me know if you face any bug in comments
Thank you
If you want to enter only 0-9 in contenteditable div then you can use this code. This code also prevent user to copy paste into the field
<div contenteditable id="myeditablediv" oncopy="return false" oncut="return false" onpaste="return false">10</div>
Javascript
$("#myeditablediv").keypress(function(e) {
if (isNaN(String.fromCharCode(e.which))) e.preventDefault();
});
if you want to enter decimal points instead of a number then you can use this javascript code
$("#myeditablediv").keypress(function(e) {
var x = event.charCode || event.keyCode;
if (isNaN(String.fromCharCode(e.which)) && x!=46) e.preventDefault();
});
Allowing numbers, the point, the backtracking
<div
on:keydown={(event) => {
if (
event.code.includes('Digit') ||
event.code === 'Backspace' ||
event.code === 'Period'
) {
console.log(e)
} else {
event.preventDefault()
}
}}
>
foo
</div>
If you want to allow only numbers, you can use :
if (e.which < 48 || e.which > 57) e.preventDefault();
If you want to enable pad numbers, use this code :
if (!e.key.match(/^[0-9]/g) && e.keyCode !== 8 && e.keyCode !== 46) {
e.preventDefault();
}
The regex starts with '^' to prevent F5 to works for example. We add e.keycode 8 and 46 to avoid the prevent default on backspace/delete
This method doesn't allow decimals, you'll need to modify regex for it
Just expanding on ElChino3312's answer to include some additional accepted keys (numpad, arrows and delete) and excludes period as I'm not allowing decimals in my case:
if (!(event.code.includes('Digit') || event.code.includes('Numpad')
|| event.code === 'ArrowLeft' || event.code === 'ArrowRight'
|| event.code === 'Backspace' || event.code === 'Delete'))
{
event.preventDefault()
}
With the code below, is there anyway of preventing the user from entering special characters that are generated by pressing CTRL + ALT + 4 for example?
That produces the euro currency sign. All the below code works perfectly, I just need to prevent any special characters that are generated from CTRL + ALT
Prevent the user from using their mouse to right click and paste the content in
Working with IE8
`
$("#txtboxToFilter").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: Ctrl+C
(e.keyCode == 67 && e.ctrlKey === true) ||
// Allow: Ctrl+X
(e.keyCode == 88 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});`
If you want to allow only certain keyboard shorcuts, you can disable anything but whatever you let pass. You can also decide to list everything that you want disabled, and allow everything else to execute. A simple way I see this can go is to disable the Ctrl key and the Alt key if they are pressed simultaneously, as such:
$("#txtboxToFilter").keydown(function (e) {
if (e.ctrlKey === true && e.altKey === true) {
return;
}
else {
//Do whatever;
if (e.key === "Tab") {
//Tab was pressed
}
else if (e.key === "H") {
//Shift H was pressed
}
else if (["Home", "End", "PageUp", "PageDown"].includes(e.key) === true) {
//Navigational Keys Were Pressed
}
else if (["ArrowUp", "ArrowDown", "ArrowRight", "ArrowLeft"].includes(e.key) === true) {
//Directional Arrows Were Pressed
}
}
});
And may I recommend that you use e.key instead of e.keyCode, e.which, or code, because it is more supported, and it is way easier to understand. Just take a look at the code snippet above, there are examples of e.key. Besides, there is no confusion with numbers, because the key names are used. If you wanted to use the Windows Key on Windows, the Search key on Chromebooks, e.key === "Meta" is the way to go.
Hope this extra information helps!!!
If all of the text in a form field is selected and then the Backspace or Delete key are used, I want to be able to run some additional code. I have tried using change, blur, keypress, keydown. None seem to work.
Example that doesn't work:
$('input[id^=txtDate_]').on('keydown', function() {
enableSaveChanges();
});
Here is one way - http://jsfiddle.net/jayblanchard/6Uq85/
$('textarea[name="foo"]').keyup(function(e) {
var currentText = $(this).val();
if( 0 == currentText.length && (e.keyCode = 46 || e.keyCode == 8)) {
console.log('empty');
}
});
I should add that I am a fan of keyup() here as the event order for keypress,keydown and keyup are different. You can test to see which makes more sense for you. The reason that I use keyup here is because the textarea (or input) isn't actually empty when you press the key.
Use the key codes for 'delete' and 'backspace'
delete = 46
backspace = 8
example:
HTML:
<input type="text" id="input">
jQuery:
jQuery('#input').keyup(function(e) {
var str = jQuery('#input').val();
if( (e.keyCode == 46 || e.keyCode == 8) && str == "" ) {
alert("Hey");
}
});
EDITED: check for empty input field
Try this way for
<input type="txt" id="txt"/>
$('#test').keyup(function(e){
if($('#test').val() == '' && e.keyCode == 46 || e.keyCode == 8)){
console.log('Input is emptied');
}
});
I'm working on a textfield working with the kind of validation that wouldn't let you enter other than numeric values. As so, my initial code looked quite simple and similar to this:
$(textField).onKeyPress(function(e) {
if (e.which < 48 && e.which > 57)
e.preventDefault();
});
This is fairly strightforward, but turns that (in the latest version of all browsers) Firefox will make this also prevent movement with the arrow keys and delete/backspace keys, whereas the other browsers would not.
Looking around I found that I would need to also check for these keys, and check for different properties exposed in the e event reference.
My final code looks something like this:
$(textField).onKeyPress(function(e) {
var code = e.which || e.keyCode;
if (code > 31 // is not a control key
&& (code < 37 || code > 40) // is not an arrow key
&& (code < 48 || code > 57) // is not numeric
&& (code != 46) // is not the delete key
)
e.preventDefault();
});
However, this feels to be too much to solve a fairly simple problem as just preventing non-numeric.
What am I doing wrong? Which is the best practice in terms of this kind of validation?
We'll respond to both keypresses, and the blur event. When somebody press a key, we check to see if the key entered is a number. If it is, we permit it. Otherwise, we prevent it.
If the field is blurred, we remove any non-numerical values, and all those values that follow. This will prevent the user from pasting in non-numerical strings:
$("#textfield").on("keypress blur", function(e){
if ( e.type === "keypress" )
return !!String.fromCharCode(e.which).match(/^\d$/);
this.value = this.value.replace(/[^\d].+/, "");
});
Demo: http://jsfiddle.net/jonathansampson/S7VhV/5/
Working demo http://jsfiddle.net/Pb2eR/23/ Updated Copy/Paste demo: http://jsfiddle.net/Pb2eR/47/ (In this demo wit you copy paste string with characters it won't allow else it will allow number to be copy pasted: tested in safari)
Demo for arrow key to work http://jsfiddle.net/gpAUf/
This will help you.
Note: in this version even if you copy paste it will set it to empty input box, tested in safari lion osx :)
Good Link: [1] How to allow only numeric (0-9) in HTML inputbox using jQuery?
code
$(".hulk").keyup(function(){
this.value = this.value.replace(/[^0-9\.]/g,'');
});
html
<input type="text" class="hulk" value="" />
Update for copy paste stuff
$(".hulk").keyup(function(){
this.value = this.value.replace(/[^0-9\.]/g,'');
});
$(".hulk").bind('input propertychange', function() {
this.value = this.value.replace(/[^0-9\.]/g,'');
});
code from another demo
$(".hulk").bind('input propertychange', function(event) {
if( !(event.keyCode == 8 // backspace
|| event.keyCode == 46 // delete
|| (event.keyCode >= 35 && event.keyCode <= 40) // arrow keys/home/end
|| (event.keyCode >= 48 && event.keyCode <= 57) // numbers on keyboard
|| (event.keyCode >= 96 && event.keyCode <= 105)) // number on keypad
) {
event.preventDefault(); // Prevent character input
}
this.value = this.value.replace(/[^0-9\.]/g,'');
});
this will allow both int.
it also removes text if user copy and paste with mouse.
$(document).ready(function () {
$('#textfield').bind('keyup blur', function (e) {
if (e.type == 'keyup') {
if (parseInt($(this).val()) != $(this).val()) {
$(this).val($(this).val().slice(0, $(this).val().length - 1));
}
} else if (e.type == 'blur') {
$(this).val('');
}
});
});
I need to validate a form textfield that's bound to a property of a model using EmberJS.
I want the user to only be able to type valid, positive numbers.
I know of jQuery.isNumber(), but I don't know how to wire it to the field.
I tried writing explicit getter/setter functions on the model's property using Ember.computed(...), but it didn't work.
Is there something similar to WinForms onChanging() event that I can hook up to?
There are a number of ways to do this sort of thing. Here we can accomplish this using bindings and observers.
First lets create a function that will always return a number.
var onlyNumber = function(input) {
return input.toString().replace(/[^\d.]/g, "");
};
Using that we can do the following
App = Ember.Application.create();
App.person = Ember.Object.create({
age: 42
});
App.NumberField = Ember.TextField.extend({
valueBinding: Ember.Binding.from("App.person.age").transform(onlyNumber),
_cleanValue: function() {
this.set('value', onlyNumber(this.get('value')));
}.observes('value')
});
1) We are creating a Binding to the Person's age, but anything that passes through this binding can only be a number. See Ember.Binding to/from transforms for more details.
2) We are observing the text field's value and setting it to be only a number when it changes. If the user enters '42a' we will immediately set it back to '42'. Note that even though '42a' was in the text input for a brief second it would not have been able to pass through the binding because of our transform.
Here is a fiddle showing this example: http://jsfiddle.net/nDBgC/
You could add a keyDown event handler on your TextField, see http://jsfiddle.net/pangratz666/SKJfF/:
App.NumberTextField = Ember.TextField.extend({
// implementation of this function, see http://stackoverflow.com/a/995193/65542
keyDown: function(event) {
// Allow: backspace, delete, tab, escape, and enter
if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
// Allow: Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
// let it happen, don't do anything
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();
}
}
}
});
Code (handles only numeric input and allows binding of number rather than string, if desired):
App.NumberFieldComponent = Ember.TextField.extend({
tagName: "input",
type: "number",
numericValue: function(key, value) {
if (arguments.length === 1) {
return parseFloat(this.get("value"));
} else {
return this.set("value", (value !== void 0 ? "" + value : ""));
}
}.property("value"),
didInsertElement: function() {
return this.$().keypress(function(key) {
if ((key.charCode !== 46) && (key.charCode !== 45) && (key.charCode < 48 || key.charCode > 57)) {
return false;
}
});
}
});
Template:
{{number-field numericValue=someNumericProperty}}
This is an updated answer (from #neverfox) for the latest Ember version (Ember-cli 2.0). It is written in coffeescript, and a bit altered to match the becomeFocus example (http://guides.emberjs.com/v1.10.0/cookbook/user_interface_and_interaction/focusing_a_textfield_after_its_been_inserted/)
Generate the component:
ember g component number-field
Change the blueprint code (app/components/number-field.coffee) to
`import Ember from 'ember'`
NumberFieldComponent = Ember.Component.extend
tagName: "input"
type: "number"
numericValue: ( (key, value) ->
if arguments.length == 1
parseFloat(this.get('value'))
else
return this.set("value", (value? ? "" + value : ""))
).property('value')
assignFilter: ( ->
this.$().keypress (key) ->
if ((key.charCode != 46) && (key.charCode != 45) && (key.charCode < 48 || key.charCode > 57))
false
).on('didInsertElement')
`export default NumberFieldComponent`