Using Onblur in Asp.Net with problems!

3

I need to format and validate a date field by using the OnBlur property of Javascript within the codebehind C #. The problem is that it performs the javascript function and does not return the value for the field. In relation to this I have two questions:

1st - What can be happening?
2 - Is there another way to format asp: Textbox without going to the server?

Follow the code:

Page_Load

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.txtData.Attributes.Add("onblur", "formataData(this.value = this.value, event)");
            }

        }
  <asp:TextBox ID="txtData" MaxLength="10" runat="server" class="form-control" Width="118px" EnableViewState="false" AutoPostBack="true"></asp:TextBox>

Javascript

     function formataData(campo, evt) {
            var xPos = PosicaoCursor(campo);
            //dd/MM/yyyy
            evt = getEvent(evt);
            var tecla = getKeyCode(evt);
            campo = validaData(campo)
            if (!teclaValida(tecla))
                return;
            vr = campo = filtraNumeros(filtraCampo(campo));
            tam = vr.length;

            if (tam >= 2 && tam < 4)
                campo = vr.substr(0, 2) + '/' + vr.substr(2);
            if (tam == 4)
                campo = vr.substr(0, 2) + '/' + vr.substr(2, 2) + '/';
            if (tam > 4)
                campo = vr.substr(0, 2) + '/' + vr.substr(2, 2) + '/' + vr.substr(4);
            MovimentaCursor(campo, xPos);
            return campo
        }

        function validaData(strdata) {

            //strdata = strdata;
            var dia = strdata.substring(0, 2);
            var mes = strdata.substring(2, 4);
            var ano = strdata.substring(4, 8);
            //var date = new Date();
            //console.log(date instanceof Date && !isNaN(date.valueOf())​)​;

            if (strdata.length == 0) {
                return false;//exit function
            }

            if (strdata.indexOf("/") == 3 && strdata.lastIndexOf("/") == 6) {
                return false;//exit function
            }

            if (strdata.length != 8) {
                alert("Data deve ser escrita da forma DDMMAAAA.");
                return false;
            }

            strdata = strdata.replace("/", "");

            if (dia > 31 || mes > 12) {
                alert("Data inválida.");
                return false;
            }

            if ((mes == 4 || mes == 6 | mes == 9 | mes == 11) && dia > 30) {
                alert("Data inválida.");
                return false;
            }

            if (mes == 2) {
                if ((((strdata %= 4) == 0 && ((strdata %= 100) != 0 || (strdata %= 400) == 0)) == false) || dia > 28) {
                    alert("Data inválida.");
                    return false;
                }
            }
            return strdata;

        }

        //descobre qual a posição do cursor no campo
        function PosicaoCursor(textarea) {
            var pos = 0;
            if (typeof (document.selection) != 'undefined') {
                //IE
                var range = document.selection.createRange();
                var i = 0;
                for (i = textarea.length; i > 0; i--) {
                    if (range.moveStart('character', 1) == 0)
                        break;
                }
                pos = i;
            }
            if (typeof (textarea.selectionStart) != 'undefined') {
                //FireFox
                pos = textarea.selectionStart;
            }
            if (pos == textarea.length)
                return 0; //retorna 0 quando não precisa posicionar o elemento
            else
                return pos; //posição do cursor
        }
        // move o cursor para a posição pos
        function MovimentaCursor(textarea, pos) {
            if (pos <= 0)
                return; //se a posição for 0 não reposiciona
            if (typeof (document.selection) != 'undefined') {
                //IE
                var oRange = textarea.createTextRange();
                var LENGTH = 1;
                var STARTINDEX = pos;
                oRange.moveStart("character", -textarea.length);
                oRange.moveEnd("character", -textarea.length);
                oRange.moveStart("character", pos);
                //oRange.moveEnd("character", pos);
                oRange.select();
                textarea.focus();
            }
            if (typeof (textarea.selectionStart) != 'undefined') {
                //FireFox
                textarea.selectionStart = pos;
                textarea.selectionEnd = pos;
            }
        }

function filtraCampo(campo) {
            var s = "";
            var cp = "";
            vr = campo;
            tam = vr.length;
            for (i = 0; i < tam; i++) {
                if (vr.substring(i, i + 1) != "/"
                          && vr.substring(i, i + 1) != "-"
                          && vr.substring(i, i + 1) != "."
                          && vr.substring(i, i + 1) != "("
                          && vr.substring(i, i + 1) != ")"
                          && vr.substring(i, i + 1) != ":"
                          && vr.substring(i, i + 1) != ",") {
                    s = s + vr.substring(i, i + 1);
                }
            }
            return s;
            //return campo.replace("/", "").replace("-", "").replace(".", "").replace(",", "")
        }
        // limpa todos caracteres que não são números
        function filtraNumeros(campo) {
            var s = "";
            var cp = "";
            vr = campo;
            tam = vr.length;
            for (i = 0; i < tam; i++) {
                if (vr.substring(i, i + 1) == "0" ||
                          vr.substring(i, i + 1) == "1" ||
                          vr.substring(i, i + 1) == "2" ||
                          vr.substring(i, i + 1) == "3" ||
                          vr.substring(i, i + 1) == "4" ||
                          vr.substring(i, i + 1) == "5" ||
                          vr.substring(i, i + 1) == "6" ||
                          vr.substring(i, i + 1) == "7" ||
                          vr.substring(i, i + 1) == "8" ||
                          vr.substring(i, i + 1) == "9") {
                    s = s + vr.substring(i, i + 1);
                }
            }
            return s;
            //return campo.replace("/", "").replace("-", "").replace(".", "").replace(",", "")
        }
        // limpa todos caracteres que não são letras
        function filtraCaracteres(campo) {
            vr = campo;
            for (i = 0; i < tam; i++) {
                //Caracter
                if (vr.charCodeAt(i) != 32 && vr.charCodeAt(i) != 94 && (vr.charCodeAt(i) < 65 ||
                      (vr.charCodeAt(i) > 90 && vr.charCodeAt(i) < 96) ||
                          vr.charCodeAt(i) > 122) && vr.charCodeAt(i) < 192) {
                    vr = vr.replace(vr.substr(i, 1), "");
                }
            }
            return vr;
        }

 function teclaValida(tecla) {
            if (tecla == 8 //backspace
                //Esta evitando o post, quando são pressionadas estas teclas.
                //Foi comentado pois, se for utilizado o evento texchange, é necessario o post.
                   || tecla == 9 //TAB
                   || tecla == 27 //ESC
                   || tecla == 16 //Shif TAB 
                   || tecla == 45 //insert
                   || tecla == 46 //delete
                   || tecla == 35 //home
                   || tecla == 36 //end
                   || tecla == 37 //esquerda
                   || tecla == 38 //cima
                   || tecla == 39 //direita
                   || tecla == 40)//baixo
                return false;
            else
                return true;
        }
        // recupera o evento do form
        function getEvent(evt) {
            if (!evt) evt = window.event; //IE
            return evt;
        }
        //Recupera o código da tecla que foi pressionado
        function getKeyCode(evt) {
            var code;
            if (typeof (evt.keyCode) == 'number')
                code = evt.keyCode;
            else if (typeof (evt.which) == 'number')
                code = evt.which;
            else if (typeof (evt.charCode) == 'number')
                code = evt.charCode;
            else
                return 0;
            return code;
        }
    
asked by anonymous 25.06.2015 / 17:01

1 answer

2

1 - You can, and even recommend not using the server for this type of interaction on the client. To add the onblur event, simply use:

<asp:TextBox onblur="minhaFuncao()"></asp:TextBox>

This is for any Javascript event. To deal with textbox changes on the server side, use the OnTextChanged event.

2 - Change your code to the following and will work:

<asp:TextBox ID="txtData" MaxLength="10" runat="server" class="form-control" Width="118px" EnableViewState="false" AutoPostBack="true"
            onblur="formataData(this, event)"></asp:TextBox>
function formataData(elm, evt) {
    var campo = elm.value;
    var xPos = PosicaoCursor(campo);
    //dd/MM/yyyy
    evt = getEvent(evt);
    var tecla = getKeyCode(evt);
    campo = validaData(campo);
    if (!teclaValida(tecla))
        return;

    var vr = campo = filtraNumeros(filtraCampo(campo));
    var tam = vr.length;

    if (tam >= 2 && tam < 4)
        campo = vr.substr(0, 2) + '/' + vr.substr(2);
    if (tam == 4)
        campo = vr.substr(0, 2) + '/' + vr.substr(2, 2) + '/';

    if (tam > 4)
        campo = vr.substr(0, 2) + '/' + vr.substr(2, 2) + '/' + vr.substr(4);

    MovimentaCursor(campo, xPos);
    elm.value = campo;
}

The changes I made to work, were to pass the textbox element itself as a function parameter ( formataData(this, event) ) and in the function, instead of using return, the formatted date is assigned to the value property of the textbox , causing it to display the correct value.

    
25.06.2015 / 18:06