Monday, August 25, 2008

How to validate length of input into a multi-line textbox

You can validate the length of input of an ordinary TextBox using the MaxLength attribute.  However, this doesn't work if the TextBox has a TextMode of Multi-line.  In those instances, use this piece of code.

<script type="text/javascript" language="javascript">

   

    function MaxLength()

    {

        var txt = $get("<%=ResponseNote_TextBox.clientid %>");

        var msg = $get("<%=Message_Label.clientid %>");

       

        if (txt.value.length > 500)

        {

            SelectText();

                                                           

            msg.className = "Failure";

            msg.innerHTML = "* Response has more than 500 characters";

        }

        else

        {

            if (msg.innerHTML == "* Response has more than 500 characters")

            {

                msg.innerHTML = "";

            }

        }

    }

   

    function SelectText()

    {

            var txt = $get("<%=ResponseNote_TextBox.clientid %>");

            var rng = txt.createTextRange();

 

            rng.moveStart("character", 501);

            rng.moveEnd("character", 0);

            rng.select();

    }

   

    function RemoveCRLFs()

    {

   // debugger;

    var txt = $get("<%=ResponseNote_TextBox.clientid %>");

    var str = window.clipboardData.getData("Text");

   

    str = str.replace(/(\s*(\r?\n|\r))+$/, '');

   

    txt.value = str ;

       

    }   

       

       

</script>        

 

Page_load:

ResponseNote_TextBox.Attributes.Add("onblur", "javascript:MaxLength()")

ResponseNote_TextBox.Attributes.Add("onpaste", "javascript:RemoveCRLFs()")

 

Read More

No comments: