Computer lessons

How to prohibit the entry of certain characters or replace them in a field or textarea JS? How to disable certain characters in input.

One of the most common tasks. You either want to protect the form from typing quotes and slashes, or you want instant transliteration. So how else can you put the contents of the form in the desired order on the client side?

How to prohibit the entry of certain characters or replace them in a field or textarea JS? The logic is simple - we create the first array with the characters that we want to replace, and then the second - with those that we insert instead of the first ones. Total: two arrays with the same(!) number of elements.


var transChars = new Array(""",""");


{

var from = nameForm;

Var to = "";
var len = from.length;
var character, isRus;
for (var i = 0; i< len; i++)
{

isRus = false;
for (var j = 0; j< rusChars.length; j++)
{

{
isRus = true;
break;
}
}

}

}
You can fill arrays with your own replacement symbols. Everything you need! Below are examples.

If we want to replace, for example, the Cyrillic alphabet with Latin characters, or, more simply put, to carry out instant transliteration) Look below:

Var rusChars = new Array("A","a","B","b","C","c","D","g","D","d","E", "e", "Ё", "e", "Zh", "zh", "Z", "z",


"Sh", "sh", "Shch", "shch", "E", "e", "Yu", "yu", "Ya", "ya", "Y", "y", "b" ","b");



"sh","sh","csh","csh","e","e","u","u","ya","ya","i","i","" ,"");
If we want to replace certain characters in a field - single and double quotes with an apostrophe, which, when saved in the database, will not allow us to receive incorrect data).

Var rusChars = new Array(""","\"");
var transChars = new Array(""",""");

How to call the function to replace characters in a field? Add the following at the end of input or textarea. The first value is the form identifier, the second is the field with the entered characters, the third - if we want to display characters in another field, then we indicate the identifier of the second field. You can leave the same ID)

Onblur="convert("form name", "where we change it from", "where we insert the replaced one");"
Well, below is an example of working with files and demo viewing!

Several demo examples of replacing characters in input fields






Replace certain characters in the input field using JS


var rusChars = new Array("A","a","B","b","C","c","D","g","D","d","E", "e", "Ё", "e", "Zh", "zh", "Z", "z",
"I", "i", "Y", "y", "K", "k", "L", "l", "M", "m", "N", "n", "O" ","o", "P", "p",
"R", "r", "S", "s", "T", "t", "U", "u", "F", "f", "X", "x", "H" ","ch", "Ts", "ts",
"Sh", "sh", "Shch", "shch", "E", "e", "Yu", "yu", "Ya", "ya", "Y", "y", "b" ","b",""","\"");
var transChars = new Array("a","a","b","b","v","v","g","g","d","d","e", "e","jo","jo","zh","zh","z","z",
"i","i","y","y","k","k","l","l","m","m","n","n","o ","o","p","p",
"r","r","s","s","t","t","u","u","f","f","h","h","ch ","ch","ts","ts",
"sh","sh","csh","csh","e","e","u","u","ya","ya","i","i","" ,"","","");

Function convert(the_form, conv_froms, conv_to)
{
var nameForm = document.forms.value;
var from = nameForm;

Var to = "";
var len = from.length;
var character, isRus;
for (var i = 0; i< len; i++)
{
character = from.substr(i,1);
isRus = false;
for (var j = 0; j< rusChars.length; j++)
{
if (character == rusChars[j])
{
isRus = true;
break;
}
}
to += (isRus) ? transChars[j] : character;
}
document.forms.value = to;
}


Immediately in one field

From one to another



How to disable certain characters in input?

The script below will allow you to check that the field is entered correctly. This will restrict the entry of certain characters into the text input field.

Character checking in a text input field can be done both during the input itself and during a specific event. The script can be used in registration fields, login forms, etc. You can prohibit specific characters or a group of characters. For example, you can completely prohibit entering numbers, prohibit space characters, tabs, and prohibit the Cyrillic or Latin alphabet.

200?"200px":""+(this.scrollHeight+5)+"px");">


["0-9",":"] - characters that will be prohibited for entering in this field. Added in quotation marks, separated by commas.

Character groups

"0-9" or "\d" - numeric values
"a-ya" - lowercase letters of the Cyrillic alphabet
"A-Z" - capital letters of the Cyrillic alphabet
"A-ya" - all letters of the Cyrillic alphabet
"a-z" - lowercase Latin letters (First letter is Latin)
"A-Z" - capital letters of the Latin alphabet (First letter of Latin)
"A-z" - all Latin letters (First letter is Latin)
"A-ya" - all letters (First letter is Latin)
"\w" - all letters, numbers and the symbol "_"
"\s" - space, tab and paragraph characters

Attention! Copying this material is prohibited without providing a link to the website
Source/ Borat

The essence of the scripts, which we will consider further, is to catch the visitor’s actions on the fly and prohibit him from entering anything in a certain field, except for numbers. That is, when the cursor is focused on the field, when you try to press letters on the keyboard, nothing will happen in the field, at the same time you can enter numbers and some symbols, such as + - () and so on, which may be needed for fields phone number or other digital number.

For this script to work, you will first need the field for entering the number. For example, you have a field inside a form that looks something like this:

The first script uses jQuery, so you need to add a connection to the jQuery library in the header of your site before the closing head or in the footer before the closing body. If you did this or the content management system (site engine) does it, then you don’t need to do this. You can look at the source code of the site and if there is a similar line somewhere, then this step needs to be skipped. If there is no connection, then you need to add the following line:

Now it’s the turn of the script itself. We add it to a separate file and include it after the library or enclose it in tags:

/// CODE HERE...

Well, the actual code itself:

JQuery(document).ready(function($)( $.fn.forceNumbericOnly = function() ( return this.each(function() ( $(this).keydown(function(e) ( var key = e.charCode | | e.keyCode || 0; return (key == 8 || key == 9 || key == 46 ||(key >= 37 && key = 48 && key = 96 && key 57)) return false; ) ;

Personally, I use the first code, it’s more convenient for me. Which one you choose is up to you too.

That's all, thanks for your attention. 🙂

Table of virtual key codes for javascript, which was promised above.

Key

10th code

Key

10th code

Backspace 8
Tab 9 Enter 13
Shift 16 Ctrl 17
Alt 18 Pause 19
CapsLock 20 Esc 27
space 32 PageUp 33
PageDown 34 End 35
Home 36 left arrow 37
up arrow 38 right arrow 39
arrow to down 40 Insert 45
Delete 46 0 48
1 49 2 50
3 51 4 52
5 53 6 54
7 55 8 56
9 57 A 65
B 66 C 67
68 E 69
F 70 G 71
H 72 I 73
J 74 K 75
L 76 M 77
N 78 O 79
P 80 Q 81
R 82 S 83
T 84 U 85
V 86 W 87
X 88 Y 89
Z 90 left Windows key 91
right Windows key 92 Applications key 93
Numpad 0 96 Numpad 1 97
Numpad 2 98 Numpad 3 99
Numpad 4 100 Numpad 5 101
Numpad 6 102 Numpad 7 103
Numpad 8 104 Numpad 9 105
NumPad* 106 Numpad + 107
NumPad - 109 NumPad. 110
NumPad / 111 F1 112
F2 113 F3 114
F4 115 F5 116
F6 117 F7 118
F8 119 F9 120
F10 121 F11 122
F12 123 NumLock 144
ScrollLock 145 PrintScreen 154
Meta 157 ; 186
= 187 , 188
- 189 . 190
/ 191 ~ 192
[ 219 \ 220
] 221 " 222
parameter key name parameter key value, which can contain: the numbers “0-9”, one plus “+” or minus “-”, one character “e” or “E”, one dot “.”. You can enter letters, but the form will not be submitted when you click the submit button, but will show an error message. Most often it is not asked. The user can change it if the readonly and disabled attributes are not specified. user change blocked access, user change and data transfer of the current parameter are blocked the field cannot be empty

The increment, which can be a positive integer or fraction. The value value is a multiple of the step value, that is, it is divided by it without a remainder. Example of allowed values ​​for value with step="20" : …, -40, -20, 0, 20, 40, …. Defaults to 1. That is, it will show an error if you enter a decimal fraction. In order to remove restrictions, you need to assign any . minimum possible value required to submit the form maximum possible value required to submit the form tooltip stub tooltip on mouseover autocomplete. You can turn it off or make it more specific. list of recommended focus field values ​​(that is, the period between clicking on an element and clicking outside the element) obtained when loading the document

The field is not suitable for text strings consisting of 16 or more digits, for example, a plastic card number, since long numbers from 9007199254740991 may be rounded.

Quantity of goods
  • increasing and decreasing the value of a numeric field using the step change buttons,
  • error message when entering letters and fractional numbers,
  • minimum value 1.
  • pcs Even positive integers Odd positive integers Round numbers Decimal fraction with floating point Monetary price format: “rubles, kopecks” with two decimal places ₽ Limit the number of characters in the field to 5 Reduce length

    The minlength , maxlength and size attributes don't work.

  • The required number of characters in the field is determined by the min , max and step attributes:
  • Specify width in CSS (width property): #dva ( width: 6em; )
  • Arrows To have arrows initially, and not only at:hover and:focus in Chrome #pyat::-webkit-inner-spin-button ( opacity: 1; ) Remove arrows .raz ( -moz-appearance: textfield; ) . raz::-webkit-inner-spin-button ( display: none; ) CSS up/down arrow styling #raz ( position: relative; display: inline-block; ) #raz input ( font-size: 1em ; -moz-appearance: textfield; ) #raz input::-webkit-inner-spin-button ( display: none; ) #raz span ( position: absolute; ) @supports (clip-path: polygon(50% 30% , 10% 90%, 90% 90%)) ( #raz input ( padding-right: 1em; ) #raz span ( right: 0; width: 1em; height: 50%; background: rgb(70,70,70 ); cursor: pointer; ) #raz span:hover ( background: red; ) #raz span:nth-of-type(1) ( top: 0; clip-path: polygon(50% 30%, 10% 90% , 90% 90%); ) #raz span:nth-of-type(2) ( bottom: 0; clip-path: polygon(50% 70%, 10% 10%, 90% 10%); ) ) Disable input into the field so that you can only use the edit buttons - + .raz ( all: unset; -moz-appearance: textfield; width: 3em; text-align: center; ) .raz::-webkit-inner-spin-button ( display: none; ) - +

    I received a fairly standard task: to filter the characters entered by the user in the input, i.e. the user can enter a set of numbers and letters into a line, for example, “5s68d.4r55e.6t5”, and to the server I must send the correct amount in rubles for saving - "568.455" (rubles).

    I completed the task quite quickly by attaching a focusout event to the input, but my solution had a number of important shortcomings: where in this example does the amount in rubles end and the kopecks begin? If the user enters several minuses (negative values ​​are also correct in this case), then which of the minuses should be considered the beginning of the line? And so on.

    Therefore, a second version of the script with regular expressions for the keyup event appeared:

    $(e.currentTarget).val(($(e.currentTarget).val()).replace(/[^0123456789.-]/, ""))
    But as it turned out, this method had a noticeable drawback (I don’t mean that the user sees the character that he enters and then this character disappears), namely, if you place the cursor, for example, in the middle of the entered number in input, enter a letter, then the script will cut out the letter, but will move the courses to the end of the line.

    For this reason, a senior friend instructed me to write a function for the keypress event. After 30 minutes, the third version of the function was ready and it looked something like this:

    Function() ( return this.each(function() ( $(this).keydown(function(e) ( var key = e.charCode || e.keyCode || 0; // allow backspace, tab, delete, enter , arrows, numbers and keypad numbers ONLY // home, end, period, and numpad decimal return (key == 8 || key == 9 || key == 13 || key == 46 || key == 110 | | key == 190 || (key >= 35 && key = 48 && key = 96 && key