I would like have always only float value with dot (not comma) in my inputs.
<input type="text" class="dot"> <br />
<input type="text" class="dot"> <br />
<input type="text" class="dot"> <br />
$('.dot').keydown(function(){
$(this).val($(this).val().toString().replace(/\,/g, '.'));
})
this replace comma to dot, but this should not be have > 1 dot and others... This should be accept only [0-9] and .
if i type a different value than other [0-9] and . then this value should be remove - ''.
How can i make it?
http://jsfiddle.net/ZtkBW/
Hiya demo http://jsfiddle.net/9Ry9t/ or http://jsfiddle.net/ZtkBW/2/ or http://jsfiddle.net/HJnLD/
Bit different from your solution but if you keen to use this, it will not allow any characters to type in the text box.
The solution does full validation for numbers and for float it will not take (dot)
code sample
$('.number').keypress(function(event) {
if(event.which < 46
|| event.which > 59) {
event.preventDefault();
} // prevent if not number/dot
if(event.which == 46
&& $(this).val().indexOf('.') != -1) {
event.preventDefault();
} // prevent if already dot
});
Here's a really terrible if statement to circumvent the fact that parseFloat can parse the first number it finds in a string and indexOf only returns the first index of a character (not all indexes).
It would probably be smarter to store the value of $(this).val() in a variable but I'll leave that as an exercise to the reader. (don't have time right now)
if(!isNaN(parseFloat($(this).val()) && $(this).val().indexOf(".") > -1 && $(this).val().indexOf(".") == $(this).val().lastIndexOf(".")) {
// do something, your value is a valid float
}
You can try this :
http://jsfiddle.net/ZtkBW/5/
var parseInput = function(val) {
var floatValue = parseFloat(val);
return isNaN(floatValue) ? '' : floatValue;
}
$('.number').keyup(function(){
var value = $(this).val()+'';
if (value[value.length-1] !== '.') {
$(this).val(parseInput(value));
}
}).focusout(function(){
$(this).val(parseInput($(this).val()+''));
})
I used keyup to avoid displaying the character if invalid.
As mentionned in comments, I also used focusout.
I do not parse if the last entered character is '.' because you will not be able to enter a decimal value.
$('.dot').keydown(function(){
$(this).val($(this).val().toString().replace(/^[0-9]\./g, ',')
.replace(/\./g, ''));
})
How it behave
I'm not really sure what you want to do
but how about this
$(this).val(parseFloat($(this).val()) || 0);
I had the same problem - needed a text input to accept only an integer or a decimal input (only one .)
Had to mix a few solutions, but this is working now:
$(".dot").keyup(function(event){
this.value=this.value.replace(/[^0-9.]/g,'');
var parts=this.value.split(".");
var decimal=false;
for(var part in parts)
{
if(part==0) this.value=parts[part];
if(part==1) this.value=this.value+"."+parts[part];
}
});
Try this :
$("#txtSellerPrice").keydown(function (e) {
if (e.keyCode == 110 && this.value.split('.').length == 2)
{
e.preventDefault();
}
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 190,110]) !== -1 || (e.keyCode == 65 && ( e.ctrlKey === true || e.metaKey === true ) ) || (e.keyCode >= 35 && e.keyCode <= 40)) { return; } if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105))
{ e.preventDefault(); }
});
Related
When using type="number" on an input field, regex validation does not appear to work.
<input type="number" step="any" min="0" max="24" value="0">
The new broswer based validation using step, min, max works as expected. However this is not consistent accross browsers?
http://jsfiddle.net/EkL3k/1/
QUESTION
How to make a number field validate using regular expression?
I'm also interested in other factors that differentiate a number and text field if anyone has information.
NOTES
I have discovered that checking for an empty string causes validation to fire IF the conditions on the number field are not met.
A number field performs its own validation, if it contains a non-numerical character, the value will automatically be removed until a correct value is given. You can see this with a console.log(value).
So you could also check for an empty string
function check(value, msg) {
var valid = ((value != '') && /^\d*\.?\d*$/.test(value));
if (valid) {
document.getElementById(msg).style.display = "none";
} else {
document.getElementById(msg).style.display= "inline";
}
return valid;
}
http://jsfiddle.net/EkL3k/6/
RegEx does not work because the returned value is a number, not a string. It works 'as expected' when you force the returned value to string format:
var valid = /^\d*\.?\d*$/.test(String(value));
You might want to read How to get the raw value an <input type="number"> field? as it suggests you don't have to validate a type=number input.
add this code and add an id to your input.
$(document).ready(function() {
$("#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: 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();
}
});
});
http://codepen.io/anon/pen/IDEGu
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()
}
I'm trying to creat a mask for comma separated values for my inputs, but I'm having dificulties.
Can you guys help me?
Here is my current mask:
<script>
$(document).on("keyup keydown keypress", "commaseparated", function (e) {
if (!$(this).val().match(/^([0-9]{0,1})(,[0-9]{1,}){1,}?$/g)) {
e.preventDefault();
}
});
</script>
<input type="text" class="commaseparated" />
<!-- example input would be
1235 <- single number
or
2654,524874,5456 <- many numbers
-->
Thanks in advance :)
EDIT
Well, this is not exactly a mask. What I want is that the user can only insert numbers and commas, e.g:
123 -> allowed
123,123 -> allowed
123,, -> not allowed
123,letters -> not allowed
You can use RegExp /(,|\D)(?=\1)|^[,\D]|[^,\d]$/g to match comma or non-digit character followed by comma or non-digit character or comma or non-digit at beginning of string or last character of string is not a digit or comma, replace match with empty string.
$(".commaseparated").on("input", function(e) {
$(e.target).prop("value", function(_, val) {
return val.replace(/(,|\D)(?=\1)|^[,\D]|[^,\d]$/g, "");
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input type="text" class="commaseparated"/>
Please, give a try to the below jquery.
//We need to capture the keypress event, as this is triggered before the value is displayed in the text box.
$(document).on("keypress", ".commaseparated", function (e) {
var currentValue = $(this).val();
//If the value is empty, let user enter numerals.
if(currentValue == "" && e.keyCode >= 48 && e.keyCode <= 57) {
return true;
}
else {
//If some value is there, get the last character.
var lastChar = currentValue.substr(currentValue.length - 1);
//If the last character is comma, let user enter numerals.
if(lastChar == "," && e.keyCode >= 48 && e.keyCode <= 57){
return true;
}
//If the last character is comma, deny entering comma again.
else if(lastChar == "," && e.keyCode == 44){
return false;
}
//If the control reaches here and as last character could only be numeral, let user enter only comma or numerals.
else if (e.keyCode == 44 || (e.keyCode >= 48 && e.keyCode <= 57)) {
return true;
}
// for everything else, return false.
else{
return false;
}
}
});
Find the jsfiddle here.
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 want to make a text box allow only letters (a-z) using jQuery.
Any examples?
<input name="lorem" onkeyup="this.value=this.value.replace(/[^a-z]/g,'');">
And can be the same to onblur for evil user who like to paste instead of typing ;)
[+] Pretty jQuery code:
<input name="lorem" class="alphaonly">
<script type="text/javascript">
$('.alphaonly').bind('keyup blur',function(){
var node = $(this);
node.val(node.val().replace(/[^a-z]/g,'') ); }
);
</script>
Accepted answer
The accepted answer may be short, but it is seriously flawed (see this fiddle):
The cursor moves to the end, no matter what key is pressed.
Non-letters are displayed momentarily, then disappear.
It is problematic on Chrome for Android (see my comment).
A better way
The following creates an array of key codes (a whitelist). If the key pressed is not in the array, then the input is ignored (see this fiddle):
$(".alpha-only").on("keydown", function(event){
// Allow controls such as backspace, tab etc.
var arr = [8,9,16,17,20,35,36,37,38,39,40,45,46];
// Allow letters
for(var i = 65; i <= 90; i++){
arr.push(i);
}
// Prevent default if not in array
if(jQuery.inArray(event.which, arr) === -1){
event.preventDefault();
}
});
Note that this allows upper-case and lower-case letters.
I have included key codes such as backspace, delete and arrow keys. You can create your own whitelist array from this list of key codes to suit your needs.
Modify on paste only
Of course, the user can still paste non-letters (such as via CTRL+V or right-click), so we still need to monitor all changes with .on("input"... but replace() only where necessary:
$(".alpha-only").on("input", function(){
var regexp = /[^a-zA-Z]/g;
if($(this).val().match(regexp)){
$(this).val( $(this).val().replace(regexp,'') );
}
});
This means we still have the undesired effect of the cursor jumping to the end, but only when the user pastes non-letters.
Avoiding autocorrect
Certain touchscreen keyboards will do everything in their power to autocorrect the user wherever it deems necessary. Surprisingly, this may even include inputs where autocomplete and autocorrect and even spellcheck are off.
To get around this, I would recommend using type="url", since URLs can accept upper and lower case letters but won't be auto-corrected. Then, to get around the browser trying to validate the URL, you must use novalidate in your form tag.
To allow only lower case alphabets, call preventDefault on the event object if the key code is not in the range 'a'..'z'. Check between 65..90 or 'A'..'Z' too if upper case should be allowed.
Or, alternatively use one of the many input mask plugins out there.
See example.
$(<selector>).keypress(function(e) {
if(e.which < 97 /* a */ || e.which > 122 /* z */) {
e.preventDefault();
}
});
// allow only Alphabets A-Z a-z _ and space
$('.alphaonly').bind('keyup blur',function(){
var node = $(this);
node.val(node.val().replace(/[^A-Za-z_\s]/,'') ); } // (/[^a-z]/g,''
);
// allow only Number 0 to 9
$('.numberonly').bind('keyup blur',function(){
var node = $(this);
node.val(node.val().replace(/[^0-9]/,'') ); } // (/[^a-z]/g,''
);
Demonstrated below to allow only letters [a-z] using Jquery:
$(function() {
$('#txtFirstName').keydown(function(e) {
if (e.shiftKey || e.ctrlKey || e.altKey) {
e.preventDefault();
} else {
var key = e.keyCode;
if (!((key == 8) || (key == 32) || (key == 46) || (key >= 35 && key <= 40) || (key >= 65 && key <= 90))) {
e.preventDefault();
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<input id="txtFirstName" value="">
Solution described by #dev-null-dweller is working absolutely.
However, As of jQuery 3.0, .bind() method has been deprecated. It was superseded by the .on() method for attaching event handlers to a document since jQuery 1.7, so its use was already discouraged.
Check deprecated methods list for jQuery 3.0 here: http://api.jquery.com/category/deprecated/deprecated-3.0/
So the solution is to use .on() method instead .bind().
If you need to bind existing elements then the code will be :
$('.alphaonly').on('keyup blur', function(){
var node = $(this);
node.val( node.val().replace(/[^a-z]/g,'') );
});
If you need to bind to dynamic elements the code will be :
$(document).on('keyup blur', '.alphaonly', function(){
var node = $(this);
node.val(node.val().replace(/[^a-z]/g,'') );
});
You need to bind the event to document or some other element that already exist from the document load.
Hope this is helpful for new version of jQuery.
$("#test").keypress(function(event){
var inputValue = event.charCode;
//alert(inputValue);
if(!((inputValue > 64 && inputValue < 91) || (inputValue > 96 && inputValue < 123)||(inputValue==32) || (inputValue==0))){
event.preventDefault();
}
});
$("#test1").keypress(function(event){
var inputValue = event.charCode;
//alert(inputValue);
if(!((inputValue > 47 && inputValue < 58) ||(inputValue==32) || (inputValue==0))){
event.preventDefault();
}
});
$("#test3").keypress(function(event){
var inputValue = event.charCode;
//alert(inputValue);
if(!((inputValue > 64 && inputValue < 91) || (inputValue > 96 && inputValue < 123)||(inputValue==32)||(inputValue > 47 && inputValue < 58) ||(inputValue==32) || (inputValue==0))){
event.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
For letters:<input type="text" id="test"> <br>
<br>
For Numbers: <input type="text" id="test1">
<br>
<br>
For Alphanumeric: <input type="text" id="test3">
Thanks to the first answer.. made this..
<input name="lorem" class="alpha-only">
<script type="text/javascript">
$(function()
{
$('.alpha-only').bind('keyup input',function()
{
if (this.value.match(/[^a-zA-Z áéíóúÁÉÍÓÚüÜ]/g))
{
this.value = this.value.replace(/[^a-zA-Z áéíóúÁÉÍÓÚüÜ]/g, '');
}
});
});
</script>
This has some improvements like letters with accents, and changing "blur" for "input" corrects the Non-letters displayed momentarily, also when you select text with the mouse and dragging is corrected..
JQuery function to allow only small and Capital Letters:
Text Field:
<input id="a" type="text" />
JQuery Function:
$('#a').keydown(function (e) {
if (e.ctrlKey || e.altKey) {
e.preventDefault();
} else {
var key = e.keyCode;
if (!((key == 8) || (key == 32) || (key == 46) || (key >= 35 && key <= 40) || (key >= 65 && key <= 90))) {
e.preventDefault();
}
}
});
Supports backspace:
new RegExp("^[a-zA-Z \b]*$");
This option will not check mobile. So you can use a jQuery Mask Plugin and use following code:
jQuery('.alpha-field, input[name=fname]').mask('Z',{translation: {'Z': {pattern: /[a-zA-Z ]/, recursive: true}}});
$("#txtName").keypress(function (e) {
var key = e.keyCode;
if ((key >= 48 && key <= 57) || (key >= 33 && key <= 47) || (key >= 58 && key <= 64) || (key >= 91 && key <= 96) || (key >= 123 && key <= 127)) {
e.preventDefault();
}
var text = $(this).val();
$(this).val(text.replace(" ", " "));
});
if (!isValidName(name)) {
//return fail message
} else {
//return success message
}
function isValidName(name) {
var regex = new RegExp("^[a-zA-Z ]+$");
if (regex.test(name)) {
return true;
} else {
return false;
}
}