I want to allow typing Latin Characters but I don't want user can type Korean Hangul characters.
Please help me answer. Thank you in advance.
Based on this article,
https://en.wikipedia.org/wiki/Korean_language_and_computers
You would want to do something like this (untested):
$(document).on('keypress', 'input', function (e) {
var key = event.which || event.keyCode;
// Hangul Syllables
if (key >= 0xAC00 && key <= 0xD7A3) {
e.preventDefault();
}
// Hangul Jamo
if (key >= 0x1100 && key <= 0x11FF) {
e.preventDefault();
}
// Hangul Compatibility Jamo
if (key >= 0x3130 && key <= 0x318F) {
e.preventDefault();
}
// Hangul Jamo Extended-A
if (key >= 0xA960 && key <= 0xA97F) {
e.preventDefault();
}
// Hangul Jamo Extended-B
if (key >= 0xD7B0 && key <= 0xD7FF) {
e.preventDefault();
}
});
However, this would not stop anyone from copying/pasting Hangul characters into the input field, you would need to find something separate for that.
A more simplified way is to use form validation (this is a more simplified approach):
<input type="text" pattern="[^가-힣]+">
What you should do is instead be testing for the characters on the server side and returning a form error.
Related
This question already has answers here:
How to limit typing number in text input
(4 answers)
Closed 4 years ago.
$(document).on('keyup keydown',function(key){
if(key.which >= 48 && key.which <= 57 && $('#sell').val() >= 9999 ) {
return false;
}
else {
if(key.which >= 48 && key.which <= 57 && $('#sell').val() <= 9999 ) {
return true;
}
}
});
Basically what I want to do is prevent someone from reaching higher than 9999 on an input.
But the problem is that if they type "55555" it would go through.
They couldn't type any higher than that and could delete it, but I don't want them to get higher than 9999.
Does anyone have a solution?
EDIT:
I need to somehow also prevent the input from working if it detects a higher number.
Try this:
var lastVal;
$("#sell").on('keydown', function(e){
if(e.which === 8){ // allow backspace
return;
} else if((e.which < 48 || e.which > 57) && (e.which < 96 || e.which > 105) ) { //only allow numbers & num pad numbers
return false;
}
if(e.target.value <= 9999) lastVal = e.target.value; //prevent key holding
});
$("#sell").on('keyup', function(e){
if(e.target.value > 9999){
e.target.value = lastVal;
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id=sell />
You could try something like this:
let sell = $('#sell');
let lastVal = 0;
sell.on('keyup keydown', function(key) {
let cc = key.which;
return (cc <= 57 && cc !== 32);
});
sell.on('input', function(evt) {
const newVal = sell.val();
if (newVal < 0 || newVal > 9999) {
sell.val(lastVal);
}
else {
lastVal = newVal;
}
});
Note that this only captures key events on the input itself, not the whole document. While this limits the user to typing digits (character below 48 (except space) are allowed because those are things like arrow keys and backspace), more work would be needed if you wanted to allow the user to perform actions like copy and paste.
The reason for not testing the val() of the input in the key event handler is a matter of timing: The key down event doesn't change the value of the input field, and the key up event comes after the value has been updated and it's too late to prevent the value change.
What this code does instead is let the value momentarily go out of range, but immediately reset it to the last valid value when that happens.
Plunker here: http://plnkr.co/edit/xsVQG1EzsDLMt8POCJUX?p=preview
Make the max length equal to 4 in HTML and use JS to force integer type, put max on input to prevent higher than 9999... Or do it manually for all of it . Up to you
With JS... on keydown: Strip non integers
if($("#inputID").val().length > 4){ KILL EXTRA LETTERS }
Once done.
If ($("#inputID").val() > 9999){ $("#inputID").val(9999); }
Remember, if this is for a form to validate the answer on the server side so the client can't override HTML and JS checks.
I try to do some programming:
I have this order form with different input fields (name, amountOfProductA, amountOfProductB, amountOfProduct...) and I submit this form, after some validation, with a jquery script.
I plan to reuse the code and the number of product fields may vary form time to time.
In the validation I make sure that at least one of the (type="number") product input fields is filled in.
If a user types a number in one of the product inputfields and by mistake a character (or a number and a character) in the other the form submits with this later field empty.
Because the wrong filled in field submits empty I cannot validate this.
Can you please give me a clue how validate this?
Should I just juse type="text" input fields? (How do I check if at least one product field is filled in then?)
This is my code:
jQuery(function ($) {
$('#bttn-submit').click(function () {
$('input').css('background', '#fff'); // reset BGcolor
var formOk = true;
var allProdFields = $('input[type=number]') // Selection of all Product('number') fields
var numberOfProdFields = allProdFields.length; // How many ('number') fields are there?
// How many product fields are empty?
var prodFieldsEmpty = 0;
for (i = 0; i < numberOfProdFields; i++) {
if( $(allProdFields[i]).val() == '' || $(allProdFields[i]).val() == 0){
prodFieldsEmpty++;
}
}
// Is there at least one product field filled?
if(prodFieldsEmpty == numberOfProdFields){
var formOk = false;
alert('Form not OK');
allProdFields.css('background', '#f30302');
}
// Is the name field filled?
if( $('#pesoonNaam').val() == '') {
$('#pesoonNaam').css('background', '#f30302');
var formOk = false;
}
if( formOk == true ) {
document.actieForm.submit();
}
})
})
The code below will not let the user enter character in your field only number. Because the type="number" is html5 and doesn't work in all the browsers.
$(document).on('keydown', '.numeric-input', function(event) {
var dot_split = $(this).val().split('.');
if ($.inArray(event.keyCode,[46,8,9,27,13]) !== -1 || (event.keyCode == 65 && event.ctrlKey === true) || (event.keyCode >= 35 && event.keyCode <= 39) && dot_split.length <= 2) {
// 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();
}
}
})
Then you can check with an .each if any of the fields is empty.
prodFieldsEmpty = 0;
$('.numeric-input').each(function(){
if($(this).val() != ""){
prodFieldsEmpty++;
}
})
I hope this helps you!
You can try smth like:
function checkInputs(){
result = false;
$('input[type="number"]').each(function(){
if($(this).val() != '' && isNumeric($(this).val())) result = true;
})
return result;
}
UPD: Fiddle
You should not attach validation to the submit button as the user can submit the form without pressing it, attach validation to the form's submit handler:
jQuery(function ($) {
$('#formID').submit(
...
jQuery has an each method for iterating, so:
$('input[type=number]').each( function(index) {
/* do validation */
});
Within each, the function's this is set to the current element, so you can do:
if (this.value == 0) {
prodFieldsEmpty++;
}
The value of a form control is always a string, so the test this.value == 0 will return true if the value is '0' or '' (empty string). If you don't like using type coercion, then do:
if (this.value === '0' || this.value === '') {
If you want to check that the value is an integer, then there are any number of answers here about that, the simplest is probably the accepted answer here:
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Note that this will allow all types of numbers, e.g. 2.34e3. If you just want to allow say positive integers, you can try:
function isPositiveInt(n) {
return /^\d+$/.test(n); // or return !/\D/.test(n)
}
Again, there are many ways to approach that.
Rather than count the number of fields and then the number that pass, if you only want to check that at least one passed, set a flag:
var passNumeric = false;
$('input[type=number]').each( function(index) {
if (isNumber(this.value)) {
passNumeric = true;
} else {
// do something with fails?
}
});
You can use the else branch to do something with the fails (or nothing).
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'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;
}
}