31

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,126
  • 6
  • 42
  • 59
John
  • 4,620
  • 19
  • 60
  • 91

12 Answers12

60

in CSS:

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

otherwise in JS:

var text="this is my text.";
var lowercase=text.toLowerCase();
Sergei Basharov
  • 47,526
  • 63
  • 186
  • 320
fdiv_bug
  • 825
  • 1
  • 6
  • 7
  • 14
    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
  • 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
40

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,728
  • 2
  • 24
  • 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
  • 4
    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
22

You can use something as

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

and it should work in the latest browsers For more details check this link

Miguel Carvajal
  • 1,510
  • 16
  • 22
  • 1
    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
  • This is super handy. Thanks. – Jamie Popkin Jun 21 '17 at 00:13
  • This is actually just what I was looking for - thank you! – NickyTheWrench Jun 23 '17 at 15:10
  • 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
10

Using jquery assuming that the input ID is username

$(document).ready(function(){
    $("#username").on('change keyup paste',function(){
    $(this).val($(this).val().toLowerCase());
     })
})
Ali Sheikhpour
  • 9,470
  • 5
  • 35
  • 73
7

@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
  • 460
  • 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
  • 855
  • 10
  • 23
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

I use this simple code :

<input type="text" onkeyup="this.value = this.value.toUpperCase();">
D.JCode
  • 389
  • 1
  • 12
0

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
  • 669
  • 5
  • 15
0

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,664
  • 17
  • 28
0

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
  • 3,774
  • 29
  • 35
-2

Using jquery assuming that the input ID is username:

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