简体   繁体   中英

How to make email address required and validate at the same time?

I am trying to validate and require a field in a email address from a textbox, but I can't use the RequiredFieldValidator and RequiredExpressionValidator because they aren't working.

I have a script that if the user does not enter something in the textbox, it will require the user to enter some text, and it will get red the textbox, and if the user enter text after that, it will get green. But the problem is that he gets green and don't display my message that the format of the email address is invalid.

ASP.NET :

 <FooterTemplate>
                                <asp:TextBox ID="txtbemail" runat="server"/>                     
                                 <asp:RegularExpressionValidator ID="regexEmailValid" runat="server" ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="txtbemail">
                                 <asp:RequiredFieldValidator ID="RequiredFieldValidator2" ControlToValidate = "txtbemail"
runat="server" ErrorMessage="*Necessário preencher"/>
                                     </asp:RegularExpressionValidator>

                                      <asp:LinkButton ID="LinkButton1" CommandName="AddNew" runat="server" CssClass="btn btn-large btn-info pull-right">
                                     <i class="glyphicon glyphicon-plus"></i> &nbsp; Adicionar
                                 </asp:LinkButton>
                            </FooterTemplate>

JavaScript :

 <script type="text/javascript">

    //Define o intervalo para verificar os validadores
    setInterval(function () { colorBorders() }, 100);

    function colorBorders() {
        if (typeof (Page_Validators) !== 'undefined') {

            //Faz um loop para verificar os validadores
            for (var i = 0; i < Page_Validators.length; i++) {
                var validator = Page_Validators[i];
                var control = document.getElementById(validator.controltovalidate);

                //Verifica se o controle existe
                if (control != null) {

                    // se o validador não for válido, coloque a borda vermelha, se for válida retornar à cor padrão
                    // elseif com a cor do rgb é necessário para impedir o desdobramento do cromo piscar
                    if (!validator.isvalid) {
                        control.style.borderColor = '#ff0000';
                    } else if (control.style.borderColor == "rgb(255, 0, 0)") {
                        control.style.borderColor = '#00ff00';
                    }
                }
            }
        }
    }
</script>

Screenshot of the problem :

The textbox from email gets green but it shouldn't because the email is not in a valid format. It should get red instead. So, how can I require and validate at the same time, and display the messages for required field, and for invalid format ?

You can accomplish that with ASP.NET validators. Try the following code snippet. I have used it in a project of mine and it works as it should. Hope it helps.

<asp:TextBox ID="txtbemail" runat="server" ValidationGroup="validation"/> 
<asp:RequiredFieldValidator ID="requiredEmail" ForeColor="#E00000"
    ControlToValidate = "txtbemail" ValidationGroup="validation"
    runat="server" ErrorMessage="Necessary field" Text="*"/>
<asp:RegularExpressionValidator ID="regexEmailValid" runat="server" ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="txtbemail" ValidationGroup="validation" ErrorMessage="Invalid e-mail format">*</asp:RegularExpressionValidator>

 <asp:LinkButton ID="LinkButton1" CommandName="AddNew" runat="server" CssClass="btn btn-large btn-info pull-right" ValidationGroup="validation">
      <i class="glyphicon glyphicon-plus"></i> &nbsp; Adicionar
 </asp:LinkButton>

 <asp:ValidationSummary ID="ValidationSummary" runat="server" ForeColor="#E00000" ValidationGroup="validation" />

You can switch to a CustomValidator and set the ValidateEmptyText to true.

<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="TextBox1"
    ClientValidationFunction="checkEmail" ValidateEmptyText="True" SetFocusOnError="true"></asp:CustomValidator>

<script type="text/javascript">
    function checkEmail(sender, element) {

        //these first 2 lines remove spaces and update the textbox
        var emailToCheck = element.Value.replace(/ /g, "");
        document.getElementById(sender.controltovalidate).value = emailToCheck;

        var filter = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        element.IsValid = filter.test(emailToCheck);
    }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM