[html] Can I specify maxlength in css?

Can I replace the maxlength attribute with something in CSS?

<input type='text' id="phone_extension" maxlength="4" />

This question is related to html css

The answer is


Not with CSS, no.


You can use jQuery like:

$("input").attr("maxlength", 4)

Here is a demo: http://jsfiddle.net/TmsXG/13/


I don't think you can, and CSS is supposed to describe how the page looks not what it does, so even if you could, it's not really how you should be using it.

Perhaps you should think about using JQuery to apply common functionality to your form components?


As others have answered, there is no current way to add maxlength directly to a CSS class.

However, this creative solution can achieve what you are looking for.

I have the jQuery in a file named maxLengths.js which I reference in site (site.master for ASP)

run the snippet to see it in action, works well.

jquery, css, html:

_x000D_
_x000D_
$(function () {_x000D_
    $(".maxLenAddress1").keypress(function (event) {_x000D_
_x000D_
        if ($(this).val().length == 5) { /* obv 5 is too small for an address field, just want to use as an example though */_x000D_
            return false;_x000D_
        } else {_x000D_
            return true;_x000D_
        }_x000D_
_x000D_
    });_x000D_
});
_x000D_
.maxLenAddress1{} /* this is here mostly for intellisense usage, but can be altered if you like */
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
_x000D_
<input type="text" class="maxLenAddress1" />
_x000D_
_x000D_
_x000D_

The advantage of using this: if it is decided the max length for this type of field needs to be pushed out or in across your entire application you can change it in one spot. Comes in handy for field lengths for things like customer codes, full name fields, email fields, any field common across your application.


Not with CSS, but you can emulate and extend / customize the desired behavior with JavaScript.


Use $("input").attr("maxlength", 4) if you're using jQuery version < 1.6 and $("input").prop("maxLength", 4) if you are using jQuery version 1.6+.


No.

maxlength is for behavior.

CSS is for styling.

That is why.