1

This is my code, it is not working properly. It can be duped with "+++" or "---". I can prevent that but it is just increasing the validation. Is there any better way? Can the code be optimized?

var regexNumber = /^\$?(((\d)\,?)+)?((\d)+)(\.(\d)+)?$/;
$("#" + element).keydown(function (event) {

                        // Allow only backspace, delete, dot, arrow key, tab, shift+tab
                        if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 190 || (event.keyCode>=37 && event.keyCode<=40) || event.keyCode==9 || event.keyCode==16) {
                            // let it happen, don't do anything                           
                        }
                        else {
                            // Allow copy, paste, select all only numbers 
                            if (((event.keyCode == 65 || event.keyCode == 86 || event.keyCode == 67) && (event.ctrlKey === true || event.metaKey === true))) {
                                if (event.originalEvent.clipboardData.getData('Text').match(regexNumber) == null) {
                                    event.preventDefault();
                                }
                            }
                            // Ensure that it is a number and stop the keypress

                            if (event.keyCode < 48 || event.keyCode > 57) {
                                event.preventDefault();
                            }
                        }
                    });

It should not allow: 1. Letters 2. Pasting data having letters

It should allow: 1. Digits with comma 2. Float 3. Tab, Shift+Tab 4. Ctrl + A, C, X, V 5. Backspace, Delete 6. Arrow keys 7. Pasting of data with comma and float

I think a regex to check letters and special characters except (.(dot) and ,(comma)) in a string and not allow them would work fine? But I don't what the regex should be?

I don't have much idea about regex.

I looked for similar questions, they were missing some cases from my validation.

1 Answers1

1

This is my solution:

 <html>
  <head>
   <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
   <script>
    var blackList=/[a-zA-Z]+/g;
    var whiteList=/[\d,\.]+/g;
    $( document ).ready(function() {
     $("#inputBox").keypress(function (event) {
      return (event.key.match(whiteList)!=null)
     });
     $("#inputBox").on("paste", function(e){
      var pasteData = e.originalEvent.clipboardData.getData('text');
      return (pasteData,pasteData.match(blackList)==null);
     });
    });
    
   </script>
  </head>
  <body>
   <textarea>
   Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborumLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
   </textarea><br>
   <textarea id="inputBox">
   </textarea>
   <div id="result">
   Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
   </div>
  </body>
 </html>

I capture "onkeypress" event to check keystroke. Furthermore, I capture the "onpaste" event to prevent the user input character from the clipboard.

It is because I do not block the input character by key code, so the special character (e.g. ctrl-c) should not be affected.

According to the jQuery documentation,

The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger keydown events but not keypress events. Other differences between the two events may arise depending on platform and browser.

The KNVB
  • 3,588
  • 3
  • 29
  • 54