Use JavaScript to allow only specific characters in HTML input - javascript

I have written some JavaScript and jQuery code that accepts only numeric input in a textbox.
But this is not enough; I need to limit the input to certain numbers.
This textbox needs to deal with SSN numbers (Swedish SSN), and it has to start with 19 or 20. I want to force it to start with these numbers, but I can't manage to limit it to these.
$('input.SSNTB').keydown(function (event) {
var maxNrOfChars = 12;
var ssnNr = $('input.SSNTB').val();
if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 ||
// 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.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105))) {
console.log("if-1");
event.preventDefault();
}
if (event.shiftKey == true) {
console.log("if-3");
event.preventDefault();
}
//rules to make sure the textbox starts with correct number
if (event.keyCode != 49 || event.keyCode != 50 || event.keyCode != 97 || event.keyCode != 98) {
console.log("if-4, Keycode:" + event.keyCode);
event.preventDefault();
}
}
});
The last if-case is executed to for testing this it is. It is executed as planed but it wont limit the input chars as its built for.
any tips or ideas?

You can use regex to limit the user to only inputting numbers and dashes. Using regex has the advantage that users can more naturally interact with the input, for instance they can paste into the text input and it will be validated successfully:
//bind event handler to the `keyup` event so the value will have been changed
$('.SSNTB').on('keyup', function (event) {
//get the newly changed value and limit it to numbers and hyphens
var newValue = this.value.replace(/[^0-9\-]/gi, '');
//if the new value has changed, meaning invalid characters have been removed, then update the value
if (this.value != newValue) {
this.value = newValue;
}
}).on('blur', function () {
//run some regex when the user un-focuses the input, this checks for the number ninteen or twenty, then a dash, three numbers, a dash, then four numbers
if (this.value.search(/[(20)(19)](-)([0-9]{3})(-)([0-9]{4})/gi) == -1) {
alert('ERROR!');
} else {
alert('GOOD GOING!');
}
});
Here is a demo: http://jsfiddle.net/BRewB/2/
Note that .on() is new in jQuery 1.7 and in this case is the same as using .bind().

Thought I would post the solution that came to the end. I actually kept the similar code that I posted above and did not covert this it RegExp. What was done was to verify the number after focus on this textbox is lost. It it is incorret the user will be informed and forced to fill in a valid number.
$('input.SSNTB').focusout(function () {
var ssnNr = $('input.SSNTB').val();
var ssnNrSub = ssnNr.substring(0, 2);
//console.log(ssnNrSub);
//checks for correct lenggth
if (ssnNr.length < 12) {
$('div.SSNHelp label.Help').html('SSN to short. Please fill in a complete one with 12 numbers');
setTimeout(function () {
$('input.SSNTB').focus();
}, 0);
validToSave = false;
return;
}
//checks so it starts correct
if (ssnNrSub != "19" && ssnNrSub != "20") {
$('div.SSNHelp label.Help').html('The SSN must start with 19 or 20. Please complete SSN.');
setTimeout(function () {
$('input.SSNTB').focus();
}, 0);
validToSave = false;
return;
}
$('div.SSNHelp label.Help').html('');
validToSave = true;
});
Works for me. : ]

You have to use regex. Regex is of help in these kind of situations.
Learn more about it from https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp

Related

Problem with match function in javascript for numeric validation

I have written following function to restrict only numbers with the limit of 2 numbers (below 100).
The first part checks special charters and letters. I got stuck in else part.
And Now I am trying to restrict with only 2 digits numeric number (without decimal). But it doesn't work the logic in below code. I am not allowed to use input type =number in HTML. The html input type is text
$(".allownumericTwo").on("input", function (evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46)
return false;
else {
$(this).val($(this).val().match(\d{0,2});
}
return true;
});
The input event is not cancelable. It also doesn't have a value for key code. What you could do instead is to check if the value is valid and if not reset it to its previous value. You also need to enclose your regex pattern between slashes, i.e. /^\d{0,2}$/.
e.g.
var oldValue = $(".allownumericTwo").val();
$(".allownumericTwo").on("input", function(evt) {
if (this.value.length > 0 && this.value.match(/^\d{0,2}$/) == null) {
this.value = oldValue;
} else {
oldValue = this.value;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class='allownumericTwo'>
you can use isNumeric()
if($(this).val().length < 3)
{
if($.isNumeric($(this).val())){
//do something
}
}
This May help.
Do remember the match returns an array.
function printFirstTwoNumbers(val) {
var regex = /^\d{0,2}/g;;
console.log(val.match(regex));
return true;
}
printFirstTwoNumbers('288.80');
printFirstTwoNumbers('2.80');
printFirstTwoNumbers('29898.80');
printFirstTwoNumbers('300');

Why does returning false in onkeydown method not work in Chrome on Android?

I've got a bit of code that works perfectly fine in my desktop browser:
document.getElementById('oneshot-timer-input').onkeydown = function(KeyboardEvent) {
if (KeyboardEvent.key == "Backspace") {
data.splice(-1,1);
} else if (KeyboardEvent.key.length == 1 && !isNaN(Number(KeyboardEvent.key))) {
if (data.length < 6) {
if (data.length > 0 || KeyboardEvent.key != "0") {
data.push(KeyboardEvent.key);
}
}
}
updateInputField();
return false;
}
The value of the input field is set in another function by:
document.getElementById('oneshot-timer-input').value = timeOutput;
It basically withholds the default action, and sets the value of the input field if some conditions are met (Only numbers and backspace are accepted). The base value is 00h 00m 00s. When entering a number, it replaces a zero, starting from the right.
This works just fine in my desktop browser, but when I open the page on my phone, it adds the latest number to the end of the base value, so it reads 00h 00m 01s1 for example. It's never more than 1 extra number though, so another example could be 12h 34m 56s6. Is there something Android related I'm missing here?
So I was missing the obvious: Android returns an unidentified key with keyCode 229 for every single key, at least when looking at the onkeydown method.
I added another EventListener on 'textInput', which handles the input perfectly. However, backspace is still an issue, since this doesn't trigger a keyevent at all. Sadly, this means that the text in the inputfield does get removed, but not as it's intended.
Implementation:
var ua = navigator.userAgent.toLowerCase();
var isAndroid = ua.indexOf("android") > -1;
if (!isAndroid) {
document.getElementById('oneshot-timer-input').onkeydown = function(KeyboardEvent) {
var keyCode = KeyboardEvent.keyCode;
if (keyCode == 8 || (keyCode >= 48 && keyCode <= 57) || (keyCode >= 96 && keyCode <= 105)) {
KeyboardEvent.preventDefault();
handleKeyCode(KeyboardEvent.keyCode, KeyboardEvent.key);
} else if (KeyboardEvent.key == "Escape") {
setTimerState(TimerStateEnums.unlock, true);
} else if (KeyboardEvent.key == "Enter") {
document.getElementById("play-pause").checked = true;
play_pause(document.getElementById("play-pause"));
}
}
} else {
document.getElementById("oneshot-timer-input").addEventListener('textInput', function(TextEvent) {
TextEvent.preventDefault();
console.log(TextEvent);
var char = TextEvent.data;
var keyCode = char.charCodeAt(0);
handleKeyCode(keyCode, char);
return false;
});
}

Firefox - keypress bug. Can't use backspace with only letter input script

I've an input box that I only want to allow letters, hyphen, space and backspace. All is good on chrome but on Firefox backspace (or charcode 8) does not work. - https://jsfiddle.net/npo7y7fr/
$(document).ready(function () {
$('.textInput').keypress(function (key) {
if ((key.charCode < 97 || key.charCode > 122) && (key.charCode < 65 || key.charCode > 90) && (key.charCode != 45)) return false;
});
});
I've tried adding && (key.charCode != 8) also changes keypress to others like 'keydown, keyup' etc...
Can anybody get this working in Firefox (40.0.3) or something that I can use instead?
Since Space will send keycode 32 and backspace will send 0 in Mozilla so that's why it is not working in mozilla.
change your script as below
$(document).ready(function () {
$('.textInput').keypress(function (key) {
if ((key.charCode < 97 || key.charCode > 122) && (key.charCode < 65 || key.charCode > 90) && (key.charCode != 45) && (key.charCode != 32) && (key.charCode != 0) ) return false;
});
});
hope this helps..!!
Instead of hardcoding some special keys, just skip the filtering for all of them. With the accepted solution, you still cancel arrow keys, Home, End, etc., which is a bad thing for the user.
As all special keys have a key field longer than 1 character, you can safely do this:
$(document).ready(function () {
$('.textInput').keypress(function (event) {
return event.key.length > 1 || event.ctrlKey || !!event.key.match(/[a-zA-Z \-]/);
});
});
The pressed key is accepted if it's a special key, it's been pressed simultaneously with the Ctrl key (to allow copying and pasting) or if it matches the regular expression (letters, space and hyphen).
As the user can paste invalid content, you should still remove illegal characters with the oninput event (probably something like ctrl.value.replace(/[^a-zA-Z \-]+/g, '')).
Rather than trying to control what the browser can enter into the input, it might be easier to just filter the contents of the textbox on keyup.
Consider the following:
$('.textInput').keyup(function() {
$(this).val( $(this).val().replace(/[^a-zA-Z]/,''));
});
Hope this helps.

Trying to validate a function in HTML

For my html, I'm trying to validate a form with a postcode input.
But this input is not working (or not being recognized). For my postcode input, I want to text box to only accept numbers.
Postcode input:
var Postcode = document.forms["Rego"]["postcode"].value;
var e = Postcode;
var code = e.keyCode;
if (code > 47 && code < 58) || code == 40 || code == 41 || code == 43) {
return true;
}
alert("Invalid Postcode. Please enter numbers only.");
return false;
What am I doing wrong?
In your condition if in line 4 after 58 why you close the ) ???
You are doing quite a few things wrong. You are not setting an event handler, you are actually binding to the value in the input box. You have to first get the DOM element representing the text box, then bind an event handler to the DOM element. Try this:
var Postcode = document.getElementById('post');
Postcode.onclick = function(e) {
console.log(e);
var code = e.keyCode;
if (code > 47 && code < 58 || code == 40 || code == 41 || code == 43) {
return true;
}
alert("Invalid Postcode. Please enter numbers only.");
e.preventDefault()
return false;
}
Fiddle: http://jsfiddle.net/S47gV/
To only accept numbers, you can use (for HTML5):
<input type="number" name="whatever">
Plus, if you want to validate it with js (doing so in browser is not recommended as anyone can modify your js file and push the contents to the server) or server code, here's some insight:
Try to convert the string passed to the server into a number. For example, in python you can do: int(whatever). If the conversion fails, that means the string isn't a number.
Hope that helps :)
If you use HTML5 you can set this automatically.
<input type="number" name="quantity" min="47" max="58">
By using below code textbox/inputbox allow only numeric value
$j('#inputbox_id').keydown(function (e) {
if (e.shiftKey || e.ctrlKey || e.altKey) {
e.preventDefault();
} else {
var key = e.keyCode;
if (!((key == 8) || (key == 46) || (key >= 35 && key <= 40) || (key >= 48 && key <= 57) || (key >= 96 && key <= 105))) {
e.preventDefault();
}
}
});
and if you want to set length of textbox/input box then set "maxlength=5"
I think i have found what you are doing wrong:
You are reading postcode value from input type and then comparing its keycode.
However‚ it may work only when your input has single number and when you type more characters in it your postcode variable becomes something for example 5436 and then when you use keycode function on this in wont work as expected.

Jquery keypress except: {something}

Is there any shortcut( actually a function) in jQuery or Javascript to handle button press except something, or only something, e.g.:
$(input).keypress('nonfunctional' function(){
// do something
});
that will trigger only on [a-z][0-9] buttons pressed and ignoring single shift or ctrl but handling shift+a => A pressed?
P.S.i do know about if(key.code == 123) then ...
No, if you want to exclude specific keys that's what the event.keyCode / event.which properties are there for.
Or you can extend jquery keypress. Something like this I guess:
$.fn.keypressBut = function(codes, callback) {
$(this).keypress(function(e) {
~$.inArray(e.keyCode, codes) || callback.call(this, e);
});
}
// Lets ignore Enter and Space
$('input').keypressBut([13, 32], function(e) {
alert(e.keyCode);
})
You could do something like
Extend jquerys fn propertie with a function which takes params like
Some Data
A callback function
Write a validation Function which
Converts the keyCode to a String
Match it against a Regular Expression.
If the shiftKey was Pressed
Convert it to Upper Case
Check if other Conditions, like Ctrl/Alt key Pressed are met.
Returns the Result.
If the validation succeeds
execute the callback function
On the code site this could like
$.fn.selectedKey = function (cb, data) {
def.call(data, {
ctrlKey: 2, //0: musn't be pressed, 1: must be pressed, 2: both.
altKey: 2, // "
invert: 0, //inverts the filter
filter: /.*/, // A Regular Expression, or a String with a Regular Expression
preventDefault: false //Set to true to prevent Default.
}); //Sets the default Data for the values used,
function validate(e) {
var key = e.char = String.fromCharCode(e.keyCode || e.which); // Converts the pressed key to a String
if (e.shiftKey) key = key.toUpperCase(); //Handles Case Sensitivity.
var exp = new RegExp(e.data.filter.replace(/\\\\(\d)/g, String.fromCharCode("$1"))); //Creates a new RegExp from a String to e.g. allow "\2" to match the keyCode 2
var c = !! (e.data.ctrlKey ^ e.ctrlKey ^ 1 > 0); //c == true if the above stated conditions are met e.g Ctrl Key Pressed and `ctrlKey == 1` -> true
var a = !! (e.data.altKey ^ e.altKey ^ 1 > 0); //e.g Alt Key Pressed and `altKey == 0` -> false
return (exp.test(key) && (c && a)); //Returns the validation Result
}
function def(obj) { //a minimal helper for default values
for (var prop in obj) {
this[prop] = this[prop] || obj[prop];
}
}
this.keypress(data, function (e) {
if (e.data.preventDefault) e.preventDefault();
if (validate(e) != e.data.invert) cb(e); //Calls the callback function if the conditions are met
});
};
Which you could then use the following ways
With a regex
$("body").selectedKey(function (e) {
console.log("All lower characters Numbers and 'A': " + e.char);
}, {
filter: /[a-z]|[0-9]|A/,
ctrlKey: 2,
altKey: 2
});
This would be triggered if any [a-z] or [0-9] or the Shift key + A has been pressed, regardless of the state of ctrl and alt
Or a keycode
$("body").selectedKey(function (e) {
// do somet
console.log("KeyCode 2 " + e.char);
}, {
filter: "\\2", //Ctrl + b
ctrlKey: 1,
altKey: 2
});
Would be triggered if you press ctrl +b
You could also combine those both.
Heres an Example on JSBin, to fiddle around with.
There is a jQuery plugin for using classes and regex for filtering keypresses if you dont want to write a large if statement to detect the key code pressed, its called keyfilter. An example would be
$(selector).keyfilter(/[a-z]/);
For example this function below allow only numbers en handle this functions using the keydown event.
function OnlyNumbers(event) {
if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 || (event.keyCode == 65 && event.ctrlKey === true) || (event.keyCode >= 35 && event.keyCode <= 39)) { return; }
else { if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) { event.preventDefault(); } }
}
have you tried event.altKey/event.shiftKey/event.ctrlKey ??

Categories

Resources