Use Onblur in Asp.Net with problems!

Asked

Viewed 1,033 times

3

I need to format and validate a data field using the property OnBlur of Javascript within the codebehind C#. The problem is that it executes the javascript function and does not return the value to the field. I have two questions about this:

1st - What can be happening?
2º - There is another way to format Asp:Textbox without going to the server?

Follows 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;
        }
  • You can use Scriptmanager. Take a look here at how it should be done. http://stackoverflow.com/questions/4994040/scriptmanager-registerstartupscript-code-not-working-why

  • I thought it was just for Onclick!

  • The question helped something?

1 answer

2


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

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

This is for any Javascript event. To handle server-side textbox changes, use the event OnTextChanged.

2 - Change your code to the following and it 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 function parameter (formataData(this, event)) and in the function, instead of using return, the date formatted is assigned to the property value textbox, causing it to display the correct value.

  • @Macusvinicius Perfect! I spent a good time researching about it, until I decided to ask the question here. Thank you!

  • Could you help me with another question? http://answall.com/questions/70387/como-coloca-um-evento-onclick-chamando-uma-function-javascript-em-um-link-dentr/70394#70394

Browser other questions tagged

You are not signed in. Login or sign up in order to post.