34

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>
steveax
  • 17,527
  • 6
  • 44
  • 59
John
  • 4,820
  • 21
  • 62
  • 92

13 Answers13

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();
Flimm
  • 136,138
  • 45
  • 251
  • 267
fdiv_bug
  • 855
  • 1
  • 6
  • 7
  • 18
    That's display only. I think we can assume the OP wants to *change* the case, not momentarily modify how it looks. – Jared Farrish Jan 01 '13 at 00:19
  • 3
    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 Oct 03 '13 at 04: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 Apr 09 '15 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 Apr 17 '16 at 19:20
  • The CSS solution with a backend solution as well should be the best/accepted answer. – Greg Blass Apr 17 '16 at 19:21
  • 1
    And just a reminder, if you can't do it server side, do it with Javascript on submit, click, or whatever. – Prof. Falken Nov 29 '19 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();
}​
jchapa
  • 3,876
  • 2
  • 25
  • 38
  • 6
    This would of course need to be enforced on the server as well. – steveax Jan 01 '13 at 00:37
  • @steveax do you mean in the database? – John Jan 01 '13 at 01: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 Jan 01 '13 at 01:10
  • 5
    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 Apr 17 '16 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 Apr 18 '16 at 17:02
  • Using the input event fixed these issues for me. So oninput instead of onkeyup – JJJ Apr 20 '18 at 07:53
  • This works fine for me, even when I select all and delete. Did browser behavior change?! – TheStoryCoder Sep 20 '20 at 08:11
25

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.

Flimm
  • 136,138
  • 45
  • 251
  • 267
Miguel Carvajal
  • 1,785
  • 19
  • 23
  • 3
    This won't work: `autocapitalize="none"` means 'do not automatically capitalize word/chars'. It doesn't mean 'forbid the use of capitalized characters'. – Nander Speerstra May 11 '17 at 09:26
  • Also it won't work for first letter in input, it will be uppercase even if you add autocapitalize. – ban17 May 22 '19 at 19:49
  • Reading https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/autocapitalize it should work. Checking with https://caniuse.com/#search=autocapitalize there is not much support. – Clemens Tolboom Nov 18 '19 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 Jul 13 '21 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 Nov 10 '21 at 22:00
  • * had a nasty habit (applied to older mobile browsers) – Luke Nov 10 '21 at 22:12
12

Using jquery assuming that the input ID is username this can help:

Footnote: Thanks to @Flimm comment, I modified the original answer by adding two extra lines to prevent jumping of the cursor to the end of input if the cursor was not at the end position.

$(document).ready(function(){
    $("#username").on('change keyup paste',function(e){
     
      //preserving the position of the cursor
      var start = e.target.selectionStart;
      
      //Converting text to lowercase
      $(this).val($(this).val().toLowerCase());
      
      //Jumping back to the old position of the cursor
      e.target.selectionStart = e.target.selectionEnd = start;
    })
})
Ali Sheikhpour
  • 10,475
  • 5
  • 41
  • 82
  • 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 Jun 26 '23 at 20:00
  • Than you @Flimm I modified the answer to cover your case too. – Ali Sheikhpour Jun 26 '23 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()});​
JJJ
  • 490
  • 4
  • 9
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.

moto
  • 946
  • 10
  • 27
  • If you enter an uppercase letter in the middle of the field, the cursor is moved to the end of the field, unexpectedly. – Flimm Jun 26 '23 at 20:01
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.

Community
  • 1
  • 1
2

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.

Luke
  • 4,825
  • 2
  • 30
  • 37
1

I use this simple code :

<input type="text" onkeyup="this.value = this.value.toUpperCase();">
D.JCode
  • 386
  • 2
  • 12
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"
>
Clemens Tolboom
  • 1,872
  • 18
  • 30
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">
Flimm
  • 136,138
  • 45
  • 251
  • 267
-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.

SwiftNinjaPro
  • 787
  • 8
  • 17
-3

Using jquery assuming that the input ID is username:

$(document).ready(function(){
    $("#username").on('input', function(){
        $(this).val( $(this).val().toLowerCase() );
    })
});