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.
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
Remove numeric'
So my problem is that I have written a little charset function, that takes all numbers from 0-9, and atm I have just console.log'ged them, but when I have tried to remove the numeric' keys from 0-9 when typed into my input, it won't work. This code will show it as a return false.
function reg(e) {
const char = e.which;
if (char >= 48 && char <= 57) { return false }
}
return (
<>
<form onSubmit={validate}>
<input type="text"
onKeyDown={reg}
value={usernameValue}
placeholder="name"
onChange={setUsernameValue} />
Instead of returning false, you should prevent the default event behaviour. This is a very common trick in JS event handlers.
It looks like this:
function reg(e) {
const char = e.which;
if (char >= 48 && char <= 57) { e.preventDefault() }
}
I am using a JS solution to allow letters and backspace only.
I want to add more options to the input, but can't see to find the right solution.
My Code:
<input id="inputTextBox">
$(document).ready(function(){
$("#inputTextBox").keypress(function(event){
var inputValue = event.which;
if(!(inputValue >= 65 && inputValue <= 123) && (inputValue != 32 && inputValue != 0)) {
event.preventDefault();
}
console.log(inputValue);
});
});
This give me the correct result of only letter input and use of backspace.
For the correct user experiece I need to add the following.
Allow input '?' , '*' and 'spacebar'.
And if possible, change the input in the form when the user typ.
So if a user typ a '?' or 'spacebar', it changes into the value '*' automatic.
Thanks in advance.
Slightly modified from this solution:
How to allow only numeric (0-9) in HTML inputbox using jQuery?
EDIT: added code to preserve position when ? and spaces are replaced
// Restricts input for the set of matched elements to the given inputFilter function.
// Modified to pass element to callback function
(function($) {
$.fn.inputFilter = function(inputFilter) {
return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function() {
if (inputFilter(this)) {
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty("oldValue")) {
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
} else {
this.value = "";
}
});
};
}(jQuery));
$(document).ready(function(event) {
$("#inputTextBox").inputFilter(function(el) {
var oldSelectionStart = el.selectionStart;
var oldSelectionEnd = el.selectionEnd;
var oldValue = el.value;
el.value = el.value.replace(/[* ]/g, '?'); //replace * space with ?
el.value = el.value.replace(/[^a-zA-Z?]/g, '');
if (oldValue != el.value)
el.setSelectionRange(oldSelectionStart-(oldValue.length-el.value.length), oldSelectionEnd-(oldValue.length-el.value.length));
return /^[a-zA-Z?]+?$/.test(el.value); // alphabet question only
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="inputTextBox">
Simply added a keyup function to replace the character '?' and space to *
and also added envent ids of space and '?' in your keypress function.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="inputTextBox">
<script>
$(document).ready(function(){
$("#inputTextBox").keypress(function(event){
var inputValue = event.which;
if(!(inputValue >= 65 && inputValue <= 123) && (inputValue != 32 && inputValue != 0 && inputValue != 63 && inputValue != 42 && inputValue != 32)) {
event.preventDefault();
}
});
$("#inputTextBox").keyup(function(){
var inputTxt = $('#inputTextBox').val();
inputTxt = inputTxt.replace('?', '*').replace(' ', '*')
$('#inputTextBox').val(inputTxt);
});
});
</script>
You have an issue with your code already since the 65 - 123 contains letters, but it also contains [] _ to name a few.
so you probably want 65-90 for A-Z then 97-122 for a-z 48-57 for 0-9. then check each character you want to allow, they probably wont be in a range.
If you look at the ascii chart here https://theasciicode.com.ar/ascii-printable-characters/question-mark-ascii-code-63.html you will see all the numbers you need to include (or exclude)
On the keyUp event, you could look at the value and then change the last character to the * if you wish, but remember that will change the actual value, not just mask it.
If you want it masked, you should use an <input type="password"> field, which has that behaviour by default.
http://jsfiddle.net/WhP8q/
I'm trying to restrict input to alpha numeric, 0-9, A-Z,a-z.
The ASCII table i'm referencing: http://www.asciitable.com/
Here is what I have so far
$(function() {
$("input").bind("keydown paste", function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
var c = code;
var letterAllowed = ((c > 47 && c < 58) || (c > 64 && c < 90) || (c > 96 && c < 123))
if (code > 32 && !letterAllowed) {
return false;
}
});
});
right now, the tilde (~) character is prevented from getting input into the field, but other special / shift characters such as !##$% all get entered into the text field.
I'm pretty sure my logic is sound, but my issue is with some misunderstanding of javascript bindings? idk
Preventing character input for only some cases is very complicated in javascript, as in the keypress event (the one you'd want to prevent) you do not know the afterwards value of your input, but only the keycode of the pressed key (and not even the resulting char for sure). Also, you will need to care about special keys like or .
I'd recommend something like this:
$("input").on("keypress keyup paste", function(e) {
this.value = this.value.replace(/[^a-zA-Z0-9]/g, '');
});
In case of restrict the character you enter, You can replace the character which is not alphanumberic.
<input type='text' id="txtAlphaNumeric"/>
<input type='text' id="txtNumeric"/>
<input type='text' id="txtAlphabet"/>
<script type="text/javascript">
$(function() {
$('#txtNumeric').keyup(function() {
if (this.value.match(/[^0-9]/g)) {
this.value = this.value.replace(/[^0-9]/g, '');
}
});
$('#txtAlphabet').keyup(function() {
if (this.value.match(/[^a-zA-Z]/g)) {
this.value = this.value.replace(/[^a-zA-Z]/g, '');
}
});
$('#txtAlphaNumeric').keyup(function() {
if (this.value.match(/[^a-zA-Z0-9]/g)) {
this.value = this.value.replace(/[^a-zA-Z0-9]/g, '');
}
});
});
</script>
Answer taken from: jquery allow only alphanumeric
Turns out, I need to do the following:
$("input").keypress(function(e){
var code = e.charCode;
charCode will give the actual character code of the typed letter, rather than the ascii code of the last pressed key
see http://api.jquery.com/keypress/
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(); }
});