Entry restriction for character set when displaying these characters

I saw in several fields the "username" in which you enter the username, and under it is something like a span, it adds it to the URL. Very similar to what happens when I type this in StackOverflow below.

I would like to show only valid characters from the list, ignore any input of characters that are not on this list.

I am really new to JS. In this case, I use jQuery, and I have some work with some parts, but I do not have other parts, or I haven’t gotten there yet.

Desire: The input form field accepts only characters from the list, others are ignored. Get the new key as entered and add it to the item.

Here is the mess I still have:

<script type="text/javascript" charset="utf-8">
 $(document).ready(function() {
      $('#cart-name').keyup(function(e) {
           var entered = $('#cart-name').val();
           entered     = entered.toUpperCase();

           var allowed = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_';

           // fromCharCode always returns uppercase?
           var entered_char = String.fromCharCode(e.which);
           console.log('You entered: ' + entered_char);

           var pos = allowed.indexOf(entered_char);
           console.log('position is: ' + pos);


           if (pos <= 0) {
                console.log('does not contain');
           } else {
                console.log('contains');
           }

           $('#live').text(entered);
           console.log(entered);
      });
 });
</script>

In html, I have:

 <input type="text" name="cart_name" value="" id="cart-name" autocomplete="off" />
 <br />
 http://example.com/
 <span id="live"></span>
 <br />
+3
2

- ?

entered = entered.replace(/[^a-zA-Z 0-9]+/g,'');
+3

, Key:

keyup ( keydown) , , keypress , - fromCharCode.

- URL-:

<script type="text/javascript" charset="utf-8">
  $(document).ready(function() {
    $('#cart-name').keypress(function(e) {
      var entered = $('#cart-name').val();

      // Regular Express to perform match on all alphanumeric characters,
      // and - and _
      var matchPattern = /[\w/_/-]/g;

      var entered_char = String.fromCharCode(e.which);
      console.log('You entered: ' + entered_char);

      if (entered_char.match(matchPattern)) {
        $('#live').text(entered + entered_char);
      }
      else if (enteredKey == " ") {
        // Replace spaces with hyphens for SEO
        $('#live').text(entered + "-");
      }    

    });
 });
</script>

.

0

Source: https://habr.com/ru/post/1717099/


All Articles