Forcing form text to be lower-case

前端 未结 11 1176
面向向阳花
面向向阳花 2021-02-02 10:16

How could I force the text in the \"username\" text input to be lower-case regardless of what user types?

相关标签:
11条回答
  • 2021-02-02 10:53

    Using jquery assuming that the input ID is username

    $(document).ready(function(){
        $("#username").on('change keyup paste',function(){
        $(this).val($(this).val().toLowerCase());
         })
    })
    
    0 讨论(0)
  • 2021-02-02 10:53

    This is my suggestion, it's based on the answer from @fdiv-bug & @ali-sheikhpour:

    1. Add text-transform: lowercase; for this field.
    input[type="email"] {
        text-transform: lowercase;
    }
    
    1. catch "change" event on this field and transform value to lowercase by (String)toLowerCase function.
    var upperCaseMatch = /[A-Z]/;
    var events = {
        CHANGE: 'change'
    };
    
    $(function() {
        $(document).on('change', 'input[type="email"]', function() {
            var value = $(this).val();
            if (!upperCaseMatch.test(value)) {
                return;
            }
            $(this).val(value.toLowerCase());
        });
    });
    

    Hope its useful for you.

    0 讨论(0)
  • 2021-02-02 11:03

    I use this simple code :

    <input type="text" onkeyup="this.value = this.value.toUpperCase();">
    
    0 讨论(0)
  • 2021-02-02 11:07

    in CSS:

    form input[type="text"] {
        text-transform: lowercase;
    }
    

    otherwise in JS:

    var text="this is my text.";
    var lowercase=text.toLowerCase();
    
    0 讨论(0)
  • 2021-02-02 11:08

    Combining a bit of everyone's answer to here simplify things.

    1. Use CSS to avoid any flashing and for display purposes.

      input[type="username"] {
        text-transform: lowercase;
      }
      

    Now, because this ONLY effects DISPLAY of the text in the browser, we need to also change the value of the input.

    1. Add an event listener to the input.

      const usernameInput = document.querySelector('input[type="username"]');
      usernameInput.addEventListener("input", function(e){
        e.target.value = e.target.value.toLowerCase();
      });
      

    We can send this to the sever like normal and, like others have mentioned, check server-side to make sure a malicious user didn't send us UpPPercaSe input.

    0 讨论(0)
  • 2021-02-02 11:10

    Using jquery assuming that the input ID is username:

    $(document).ready(function(){
        $("#username").on('input', function(){
            $(this).val( $(this).val().toLowerCase() );
        })
    });
    
    0 讨论(0)
提交回复
热议问题