37

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

<div class="register">
   <label for="username">Select username:</label>
</div> 
<div class="registerform">
    <input name="username" class="registerfont" type="text"
           id="username" maxlength="15" style="height:35px; width:300px">
</div>
1
  • 1
    Do you want it to be lower case as their typing? or do you want to submit it all lower case?
    – kennypu
    Commented Jan 1, 2013 at 0:20

13 Answers 13

63

To make it appear like the text is lowercase, without changing the value of the field in reality when submitted to the server or when copy-pasted, use this CSS:

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

If you want to lowercase a string in JavaScript, use this code:

var text = "This Is My Text.";
var lowercase = text.toLowerCase();
6
  • 20
    That's display only. I think we can assume the OP wants to change the case, not momentarily modify how it looks. Commented Jan 1, 2013 at 0:19
  • 4
    This is actually the best solution aesthetically, providing you combine it with a server-side conversion on submit. The accepted answer will flash uppercase letters briefly every time the user presses a key.
    – claviska
    Commented Oct 3, 2013 at 4:50
  • 2
    Upvoting because data validation and "fixing up" should be done on the server side only. Relying solely on js to evaluate form data opens yourself up to hacking. For instance, disable the js and one could create an account with the username 'Admin' (capital A) and start phishing other users. Also editing a form field while it's being typed into could cause problems with cursor placement in some browsers or asian keyboards that require 1-3 keystrokes per character.
    – IAmNaN
    Commented Apr 9, 2015 at 17:54
  • 1
    The CSS version is better than the javascript version, as long as you do it on the backend too. Otherwise the js stuff is really wonky. See my comment above, it breaks select all/delete, and the transformation on keyup is jarring.
    – Greg Blass
    Commented Apr 17, 2016 at 19:20
  • 1
    And just a reminder, if you can't do it server side, do it with Javascript on submit, click, or whatever. Commented Nov 29, 2019 at 14:52
41

You have to use javascript. I have an example here: http://jsfiddle.net/xCfdS/3/

HTML: <input type="text" id="txt" onkeyup="return forceLower(this);"/>​

Javascript:

function forceLower(strInput) 
{
strInput.value=strInput.value.toLowerCase();
}​
7
  • 6
    This would of course need to be enforced on the server as well.
    – steveax
    Commented Jan 1, 2013 at 0:37
  • @steveax do you mean in the database?
    – John
    Commented Jan 1, 2013 at 1:05
  • 5
    @John somewhere on the server, whether that's enforced by the database or something else is up to you, but you cannot rely solely on client side scripting as it is easily circumvented.
    – steveax
    Commented Jan 1, 2013 at 1:10
  • 6
    This is wonky. First off, the user enters a capital letter, and then on keyup it is transformed. Good enough I guess - until the user tries to select all and delete. It only deletes the last letter. Way too wonky for my taste, and not production worthy.
    – Greg Blass
    Commented Apr 17, 2016 at 19:19
  • Agreed - I personally prefer the CSS solution below, and is how I solve this problem. Either way, you have to validate on the server if you intend on storing the transformed data, so all your UI is doing is display. CSS is for display.
    – jchapa
    Commented Apr 18, 2016 at 17:02
28

To turn off the automatic capitalization of words on the virtual keyboards of mobile browsers, use this code:

<input autocapitalize="none" ></input>

It should work in the latest mobile browsers. For more details check this link.

This will not prevent a user from deliberately choosing to enter capital letters.

6
  • 3
    This won't work: autocapitalize="none" means 'do not automatically capitalize word/chars'. It doesn't mean 'forbid the use of capitalized characters'. Commented May 11, 2017 at 9:26
  • Also it won't work for first letter in input, it will be uppercase even if you add autocapitalize.
    – ban17
    Commented May 22, 2019 at 19:49
  • Reading developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/… it should work. Checking with caniuse.com/#search=autocapitalize there is not much support. Commented Nov 18, 2019 at 10:31
  • This answer is just wrong and has nothing to do with question. I do not know how this has so many votes.
    – norr
    Commented Jul 13, 2021 at 19:07
  • @norr you're right - it doesn't answer the question. BUT, in the context of users entering uppercase characters (specifically in email addresses / usernames), it is useful in that it deals with the fact that mobile browsers have a nasty habit of auto-capitalising the first letter of input fields. This results in issues where there likely wouldn't have been under normal circumstances. e.g. Users registering for an account with a capitalised email address. Majority of users won't manually capitalise their email address and equally most won't take the time to rectify it if it is auto-capitalised.
    – Luke
    Commented Nov 10, 2021 at 22:00
14

For preserving the cursor position while converting:

Using jquery:

$(document).ready(function(){
  $("#username").on('input',function(e){

    // Store the current selection range
    var start = this.selectionStart;
    var end = this.selectionEnd;

    // Convert text to lowercase
    $(this).val($(this).val().toLowerCase());

    // Restore the selection range
    this.setSelectionRange(start, end);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<input id="username">

Vanilla JS:

document.addEventListener('DOMContentLoaded', function() {
  var usernameInput = document.getElementById('username');

  usernameInput.addEventListener('input', function(e) {
    var start = this.selectionStart;
    var end = this.selectionEnd;

    // Convert text to lowercase
    this.value = this.value.toLowerCase();

    // Restore the selection range
    this.setSelectionRange(start, end);
  });
});
<input id="username">

2
  • If you type in the field, then go back to the begging of the field, and type a capital letter, the cursor suddenly moves to the end of the string with this solution.
    – Flimm
    Commented Jun 26, 2023 at 20:00
  • Than you @Flimm I modified the answer to cover your case too. Commented Jun 26, 2023 at 23:39
9

@fdiv_bug's answer is good except for the issues mentioned in the comments of their answer. Using the input event instead of the keyup event fixed those issues for me.

HTML:

<input oninput="this.value=this.value.toLowerCase()"/>​

Javascript:

element.addEventListener('input',function(){this.value=this.value.toLowerCase()});​
1
  • 2
    If i go back to any position of the string and enter a key in uppercase the cursor teleports to the end of the string. Commented Mar 3, 2020 at 13:16
5

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.

1
  • If you enter an uppercase letter in the middle of the field, the cursor is moved to the end of the field, unexpectedly.
    – Flimm
    Commented Jun 26, 2023 at 20:01
4

Old question. New answer.

With HTML5 Form Validation now (2021) supported across all major browsers, it is relatively simple to force lowercase text on an input field, client side, using the pattern attribute. (The pattern attribute is supported by all but Opera Mini at the time of writing).

HTML:

<label>Field Name (lowercase letters only)</label>
<input type="text" pattern="[a-z]" placeholder="Field Name (lowercase letters only)">

Note: The below follows from, but gets semi out of scope of, the question.

Forcing lowercase on an email address field (which is what brought me to this question) seems to be more risky as using pattern/rejex to validate email addresses is fairly complicated and there are potential issues associated with implementing pattern in conjunction with type="email".

The above aside, for my use case, the following pattern was sufficient:

<label>Email Address (lowercase letters only)</label>
<input type="email" pattern="[^A-Z]+" placeholder="Email Address (lowercase letters only)">

The rejex expression [^A-Z]+ allows any characters that aren't capitals. I leave the actual email address validation to the browser via type="email". I tested this on desktop in Chrome, Firefox, Edge and IE11 and all worked fine.

2

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
2

I use this simple code :

<input type="text" onkeyup="this.value = this.value.toUpperCase();">
1

Use onchange instead

<input name="username"
  onchange="this.value = this.value.toUpperCase();"
  style="text-transform: lowercase; height:35px; width:300px"

  class="registerfont"
  type="text"
  id="username"
  maxlength="15"
>
1
  • This makes the text uppercase, not lowercase. But it is displayed as lowercase.
    – Flimm
    Commented Jun 26, 2023 at 20:01
0

This JavaScript will convert the text to lowercase as the user is entering it. It will remember the cursor position, to avoid the cursor being set to the end if the user enters a character in the middle of the existing text.

I also set autocapitalize to off so that uppercase letters are not automatically displayed on the virtual keyboard in mobile browsers.

var element = document.querySelector("input");
element.addEventListener('input', function(e) {
  const position = e.target.selectionStart;

  // Lowercase the text, which happens to also reset the selection:
  e.target.value = e.target.value.toLowerCase();

  // Restore the cursor position to where it was:
  e.target.setSelectionRange(position, position);
});
<input type="text" autocapitalize="off">

-2

setInterval() will run if the user pastes something in

setInterval(function(){
  let myinput = document.getElementById('myinput');
  //make lowercase
  myinput.value = myinput.value.toString().toLowerCase();
  //remove spaces (if you want)
  myinput.value = myinput.value.toString().replace(' ', '');
  //force specific characters
  myinput.value = myinput.value.toString().replace(/[^a-z0-9\/\-_]/, '');
}, 10);

because this is a loop function using .replace(), replacing only first occurrence at a time, but still looping all of them, this appears to animate removing spaces on pasted text.

-3

Using jquery assuming that the input ID is username:

$(document).ready(function(){
    $("#username").on('input', function(){
        $(this).val( $(this).val().toLowerCase() );
    })
});
1
  • Unless the author asks so, it is better not to be dependent on external libraries Commented Oct 8, 2020 at 20:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.