Validation of Webforms fields

Asked

Viewed 651 times

-1

I’m putting together a registration page with webforms, I need to validate the fields, but I don’t know if it’s better to do it by the method itself onclick of the recording button (via c#) or if there is some way to call a function javascript to validate before allowing recording by this my method onclick.

What should I do?

  • A good validation is always on the server or in your C#, but client-side validations make the application more intuitive, since you don’t need to go to the server to check that the field is correct before you make an exception. So I do both sides if possible.

  • recommend to do a "flag" for validation in script even, playing all conditions (if) if it does not pass in any it returns false, if it passes in all ifs (the fields shown) it returns true and applies the rest of the write process...

  • Use Validation Controls. https://msdn.microsoft.com/en-us/library/debza5t0.aspx You can validate from required fields to regular expressions. A good article, in English: http://www.codeproject.com/Articles/49527/How-to-Use-the-ASP-NET-Validation-Control-to-Valid

2 answers

1

Good afternoon, You can put a validation by clicking a button, the event of the button is the OnClick(); by clicking the button is validated each field. EX:

//Se não estiver nulo ou vazio.

IF  (String.IsNullOrEmpty(Textbox1.Text)){

//Mensagem de aviso que avisando que está vazio.

}

In the case of a client-side validation, the method may be used, OnLostFocus(); for each data input field. When losing the focus of control a check is made.

1

This script was from a little test project that I created a while ago, but it should help a little I believe.

Validation script (Email, Cpf, checkbox, Date, password, phone and etc)

function valida()
{
        var info = "";
        corErro ="#ccff99";
    corAcerto="#FFFFFF";

        // Validação de Nome
    var nome = document.getElementById("nome");
    var strNome = nome.value;
    if ((strNome.length < 6) || (strNome.length > 30)) {
        info += " - O nome deve ter entre 6 e 30 caracteres. \n"; 
                nome.style.backgroundColor = corErro;
                nome.focus();
    } else {
    nome.style.backgroundColor = corAcerto;
    }

        // Validação de Data
        var aData = document.getElementById("data");
    strData = aData.value;
    vetData = strData.split("/");

    if (vetData.length != 3){
        info += " - Erro na data, não possui dia/mês/ano. \n";
                aData.style.backgroundColor = corErro;
                aData.focus();
    } else {
        dia = vetData[0];
        mes = vetData[1];
        ano = vetData[2];
        if (isNaN(dia) || isNaN(mes) || isNaN(ano)) {
            info += " - Existem erro nos valores para dia/mês/ano. \n";
                        aData.style.backgroundColor = corErro;
                        aData.focus();
        } else {

            intAno = parseInt(ano);
            intMes = parseInt(mes);
            intDia = parseInt(dia);

            if ((intAno < 1900) || (intAno > Date().getFullYear)){
                info += " - O ano deve estar entre 1900 e hoje. \n";
                                aData.style.backgroundColor = corErro;
                                aData.focus();
            } else {
                if((intMes < 1) || (intMes) > 12){
                    info += " - O mês deve estar entre 1 e 12. \n"; 
                                       aData.style.backgroundColor = corErro;
                                       aData.focus();
                                    } else {

                    var bissexto = ((intAno % 4) == 0);
                    var intFim = 30;
                    switch (intMes){
                        case 1, 3, 5, 7, 8, 10 ,12:
                                                    intFim = 31;
                                                        break;
                        case 4, 6, 9, 11:
                                                    intFim = 30;
                                                        break;
                        case 2:
                                                    if(bissexto){
                                                        intFim = 29;
                                                                } else{
                                                                intFim = 28;
                                                                      }
                                                                break;
                                                        }
                                            if((intDia < 1) || (intDia> intFim)) {
                                                    info += " - O dia deve estar entre 1 e " + intFim + " para o mês/ano. \n";
                                                        aData.style.backgroundColor = corErro;
                                                        aData.focus();
                                                    } else {
                                                        aData.style.backgroundColor = corAcerto;
                                                                                    }//d5
                                        }//d4
                                }//d3
                        }//d2   
                }//d1

                 //Validação de CPF
                 var cpf = document.getElementById("cpf");
                 strcpf = cpf.value;
                 strcpf = strcpf.replace(".","");
                 strcpf = strcpf.replace(".","");
                 strcpf = strcpf.replace("-","");

                 if (isNaN(strcpf)){
                     info+= " - CPF inválido.(contém letras) \n"
                     cpf.style.background = corErro;
                     cpf.focus();
                 } else {
                 if (strcpf == '' || strcpf.length != 11)
                 {
                     info+= " - É obrigatório o preenchimento do CPF.(Caso preenchido, verifique se há caracteres ou números digitados de forma incorreta) \n";
                     cpf.style.backgroundColor = corErro;
                     cpf.focus();
                 } else {
                if (   strcpf == "00000000000"
                    || strcpf == "11111111111"
                    || strcpf == "22222222222"
                    || strcpf == "33333333333"
                    || strcpf == "44444444444"
                    || strcpf == "55555555555"
                    || strcpf == "66666666666"
                    || strcpf == "77777777777"
                    || strcpf == "88888888888"
                    || strcpf == "99999999999")
                 {
                   info += " - CPF inválido. \n";
                   cpf.style.backgroundColor = corErro;
                   cpf.focus();
                    } else { 
                        var Soma;
                        var Resto;
                        Soma = 0;
                        for (i = 1; i <= 9; i++)
                            Soma = Soma + parseInt(strcpf.substring(i-1, i)) * (11 - i);
                        Resto = (Soma * 10) % 11;
                        if (Resto != parseInt (strcpf.substring(9, 10)))
                        {
                            info+= " - CPF inválido. \n";
                            cpf.style.backgroundColor = corErro;
                            cpf.focus();
                        } else {
                            Soma = 0;
                            for (i = 1; i <= 10; i++)
                                Soma = Soma + parseInt(strcpf.substring(i-1, i)) *(12 - i);
                                Resto = (Soma * 10) % 11;
                                if (Resto != parseInt (strcpf.substring(10, 11)))
                                    {
                                    info+=" - CPF inválido. \n";
                                    cpf.style.backgroundColor = corErro;
                                    cpf.focus();
                                        } else {
                                            cpf.style.backgroundColor = corAcerto;
                                                }//d5
                                }//d4
                            }//d3
                        }//d2
                    }//d1

        //Validação de Telefone
        var tel = document.getElementById("tel");
        strtel = tel.value;
        strtel = strtel.replace ("-","");
        if (isNaN(strtel)){
            info+= " - Telefone inválido. \n ";
            tel.style.backgroundColor = corErro;
            tel.focus();
                } else {
                        if (strtel == '' || strtel.length < 8){
                            info+= " - É obrigatório o preenchimento do telefone. \n";
                            tel.style.backgroundColor = corErro;
                            tel.focus();
                            } else {
                                tel.style.backgroundColor = corAcerto;
                                   }
                        }

        // Validação do E-mail
        var email = document.getElementById("email");
        var contnum;
        var contlet;
        stremail = email.value;
        if (stremail == '')
        {
            info+= " - Preencha o campo do email. \n"
            email.style.backgroundColor = corErro;
            email.focus();
        } else {
            email.style.backgroundColor = corAcerto;
        }

        //Validação de Senha
        var senha = document.getElementById("senha");
        var numeros = "0123456789";
        var letras = "abcdefghijklmnopqrstuvxyz";
        var contlet;
        var contnum;
        strsenha = senha.value;
        strsenha = strsenha.toLowerCase();
        contlet = 0;
        contnum = 0;
        if ( '' != strsenha ){
                    for (i = 0; i < strsenha.length; i++)
                    {
                        if(numeros.indexOf(strsenha.charAt(i),0)!= -1)
                        {
                        contnum++;
                        }
                        if(letras.indexOf(strsenha.charAt(i),0)!= -1)
                        {
                        contlet++;
                        }
                        }
                    }
        if (strsenha = "" || contnum < 2 || contlet < 4)
        {
            info+= " - Obrigatório o preenchimento da senha. (Caso preenchido, verificar o mínimo requerido: 4 letras e 2 números \n";
            senha.style.backgroundColor = corErro;
            senha.focus();
        } else {
            senha.style.backgroundColor = corAcerto;
        }

        // Validação do checkList
        var op1 = document.getElementById("op1");
    var op2 = document.getElementById("op2");
    var op3 = document.getElementById("op3");
    var op4 = document.getElementById("op4");
    if(
        ( ! op1.checked)
        &&
        ( ! op2.checked)
        &&
        ( ! op3.checked)
        &&
        ( ! op4.checked)
        ){
        info += " - Deve ser selecionado uma preferencia pelo menos.\n";
                op1.focus();
            }

        // Final descrevendo os Erros listados em Alert
        if (info.length > 0){
        alert("Erros detectados: \n\n" + info);
                    return false;
                            } else {
                                return true;
                                    }
}   

html needs to contain this at least

<form onsubmit="return valida();" id="form1" method="get" action="CadastroConfirmado.html">
//Campos das validações aqui!
<button type="submit" id="btninclui" value="">Pronto!</button>
</form>

The button after clicked, plays the onsubmit that is in the form and then runs the validation Function. Validation is done in stages, checking field by field, if any field is not correct it stores the error information and at the end of Function it checks. If there is any information it returns false "nullifying" the Ubmit and informs the error, if it has no error information it returns true and ends the onsubmit execution.

I prefer it this way. The example was just a demonstration, not being necessary to understand everything I mentioned, but only a reference that I think valid to show to make it clear how it would be in script.

Browser other questions tagged

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