Is it possible to prevent any kind of input in a text field using JavaScript? Especially including:
Typing text on the keyboard(can be caught viakeydownevent)Pasting text using context menu(can be caught viapasteevent)Cutting text using context menu(can be caught viacutevent)- Deleting text using context menu
- Replacing text using browser's built-in spellchecker via context menu
- Inserting emojis using context menu in Chrome for example
The readonly property is semantically the way to go but it doesn't work with built-in form validation if the field is set to required (or does it with extra JS logic?).
Capturing the focus event and triggering blur right away prevents selecting and copying text.
Storing the input's value on focus and setting it after each change event would sort of work, but the content would flash for a moment.
Any ideas?
Edit: Some people have asked why I need to do this and that it makes no sense. First of all, I know the value can be set via the browser developer tools and I also know that proper backend validation is required, it is there.
The idea behind the question is the following:
I have a file input field. In order to style it properly, the actual <input type="file"> is hidden and a Bootstrap input group is used with a text field and a browse button beside (the button is the hidden file field's label so clicking it really opens the select file dialog, that works in all browsers tested). As soon as the user selects a file, the text field is updated to show the filename(s). The text field displaying the filename(s) has the HTML5 attribute set to required so any form submission will have the browser check if the text field is empty and if so, display an error. If I set the text field to readonly or disabled, the field won't get validated by the browser on submit. I would like to have the browser perform the validation and not custom JS code so that the validation of the fields is performed in the order the fields appear on the page and so that all pre-submit errors have the same look and feel.
Edit 2: One more thing, since the actual file input field is hidden, setting it to required instead of the text field displaying the filename(s) leads to the following error by Chrome: "An invalid form control with name='myfancyname' is not focusable."