JS validation allow letters and specific symbol only + change input - javascript

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.

Related

Keyup prevent default not working angular6

I want to stop entering any number after validating a custom regular expression , the issue is condition got true but event.preventDefault is not preventing the input , The reg ex is to input value in percentage between 1-100 with decimals
/^(100(\.0{1,2})?|[1-9]?\d(\.\d{1,2})?)$/
this is my input
<input type='text' (keyup)="preventPercentage($event)" [(ngModel)]="value">
ts
preventPercentage(event){
var p = event.target.value
var s= p.match(/^(100(\.0{1,2})?|[1-9]?\d(\.\d{1,2})?)$/) != null
if(!s && p){
event.preventDefault();
}
}
user can still enter any value even the condition is true
input anything between 100 above it still working and event is not preventing values
<input type='text' (keydown)="preventPercentage($event)" [(ngModel)]="value">
I used key down but it allows to enter 123 i.e three digit numbers
and I cannot then remove that number using backspace what exactly I am doing wrong can anyone suggest a sol any help will be appreciated
Try this. I think there is a change required in the regex as per your requirement.
preventPercentage(event){
var p = event.target.value + event.key;
var s = p.match(/^(100(\.0{1,2})?|[1-9]?\d(\.\d{1,2})?)$/) != null;
if (!s && event.keyCode !== 8) {
event.stopPropagation();
return false;
}
}
Use this with keydown:
<input type='text' (keydown)="preventPercentage($event)" [(ngModel)]="value">
preventPercentage(event: any) {
function stopProgram() {
event.stopPropagation();
return false;
}
if (event.keyCode === 8) {
return true;
}
var p = event.target.value;
if ((event.keyCode === 190 && p.indexOf('.') > -1) || p === '100') {
return stopProgram();
}
p = p + event.key;
var s = p.match(/^(100(\.0{1,2})?|[1-9]?\d(\.\d{1,2})?)$/) != null;
if (!s && event.keyCode !== 190) {
return stopProgram();
}
}
This is because it's necessary to use keydown event, not keyup.
It considers that the keyboard action is already done and you cannot cancel it.

Clear text field when keyup function is triggered

I’m trying to clear a text field after a keyup function is triggered.
I used a simple val('') to clear but it’s not working. Also if ever. I want my text field to not allow entering period or . on the first place, like .12.
Here is my keyup function:
$('#gross-mass').keyup(function(event) {
var currentVal = $(this).val();
if (parseFloat(currentVal) == 0.00 && (event.which == 48 || event.which == 96)) {
//currentVal = currentVal.slice(0, 3);
currentVal.val(' ');
}
$(this).val(currentVal);
});
currentVal isn't a function, it's a string. You can set its value like this:
currentVal = ' '
First of all, you need to use $(this).val(""), not currentVal.val(' '); (in my example it's just el.val("") because I have stored var el = $(this)). And you should remove this row before the end of the method: $(this).val(currentVal);, because it sets input's value back to currentVal. Here is the working example, try to type 0 for example, input's value will be cleared after keyup event:
$('#gross-mass').keyup(function(event) {
var el = $(this)
var currentVal = el.val();
if (parseFloat(currentVal) == 0.00 && (event.which == 48 || event.which == 96)) {
el.val("");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="gross-mass">

Replacing if the first number is a zero and the number is greater than 2 places

I have a calculator I'm working on and came across a problem. To combat so that users can't leave a field blank, I'm forcing a zero if the field is left empty. That's all fine, but the problem is that when the text in the field is deleted to remove the zero and enter a new number, it automatically enters zero so my new number looks like this: 05
How do i run a replace where if there is more than 2 places in the number and the first number is zero, replace the zero? Here's the code i'm using for my calculator.
$(function(){
calculate();
$('.input').keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
});
$('.input').on('keyup',function(){
if($(this).val()==''){
$(this).val('0');
}
calculate();
});
});
function calculate(){
var d6 = parseFloat(($('#d6').val()).replace(/,/g,''));
var d20 = parseFloat(($('#d20').val()).replace(/,/g,''));
var b20 = d6;
var e20 = parseFloat(($('#e20').val()).replace(/,/g,''));
var f20 = d20*e20;
var f22 = b20/f20;
var f23 = (52-f22)*f20;
$('#f20').html(formatCurrency(f20));
$('#f22').html(f22.toFixed(2));
$('#f23').html(formatCurrency(f23));
}
function formatCurrency(x) {
return '$'+x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",");
}
If you are essentially trying to turn it into a formatted number you could try type coercion:
'' + new Number('') // "0"
'' + new Number('0') // "0"
'' + new Number('05') // "5"
'' + new Number('0000.2') // "0.2"
Change the zeroing code to use the blur() event, i.e when the field loses focus.
$('.input').blur(function(){
if($(this).val()=='')
{
$(this).val('0');
}
});
I'm assuming that the text is removed from pressing the backspace key.
If that is the case then you keyup handler would fire when you backspace on the zero, which would detect no input, then add the zero.
First of all, you are doing it a hard way. And try this... if the user clicks on the input then it will be cleared and the user can write whatever number he wants...
$( ".input" ).focus(function() {
(this).val('');
});
In case you are using an HTML5 form you can avoid that piece of code like this:
<input type="number" placeholder="Type a number" required>
The required attribute is a boolean attribute.
When present, it specifies that an input field must be filled out.
Instead of using keyup and keypress event for checking and replacing blank to zero, use change event.
$(function(){
calculate();
$('.input').keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
});
$('.input').on('keyup',function(){
calculate();
});
$('.input').on('change',function(){
if($(this).val()==''){
$(this).val('0');
}
});
});
function calculate(){
var d6Val = ($('#d6').val() !== "")? $('#d6').val() : '0';
var d20Val = ($('#d20').val() !== "")? $('#d20').val() : '0';
var e20Val = ($('#e20').val() !== "")? $('#e20').val() : '0';
var d6 = parseFloat((d6Val).replace(/,/g,''));
var d20 = parseFloat((d20Val).replace(/,/g,''));
var b20 = d6;
var e20 = parseFloat((e20Val).replace(/,/g,''));
var f20 = d20*e20;
var f22 = b20/f20;
var f23 = (52-f22)*f20;
$('#f20').html(formatCurrency(f20));
$('#f22').html(f22.toFixed(2));
$('#f23').html(formatCurrency(f23));
}
function formatCurrency(x) {
return '$'+x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",");
}
One more thing. Change event only fires when you focus-out from that input.
Please let me know if you will face any issue.

How to specify which characters are allowed in a textbox with jQuery?

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/

Allow text box only for letters using jQuery?

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;
}
}

Categories