how to validate textbox to have limited characters

how to validate textbox to have limited characters

how to validate textbox to have limited characters ??

the number of charcters are coming from backend..............if its more then maxlenth hoe to clean textbox

for ex:max characters=10.........when textbox opens already have 20 characters how to remove extras and make it 10.and if less den 10 allow to enter only 10 characters......

maxlength is coming from server.

 $(function () {

            alert("maxWords");

            // to count charecters in CompanyProfile

            $('#txtCompanyProfile').keyup(function () {

                var maxWords = document.getElementById('<%= hiddenProfileMaxValue.ClientID%>').value;

                

                var cs = $(this).val().length;

                $('#characters').text(cs);

                    $('#txtCompanyProfile').keypress(function (e) {

                    if (e.which < 0x20) {

                        return;     // Do nothing

                    }

                    

                    if (this.value.length == maxWords || this.value.length > maxWords)

                    {

                        e.preventDefault();

                        alert("Only " + maxWords + " characters are allowed.");

                    } else if (this.value.length > maxWords) {

                        // Maximum exceeded


                        this.value = this.value.substring(0, max);


                    }

                });

            });

        });