如果txtbox验证,则禁用按钮

时间:2015-06-04 11:51:39

标签: html asp.net vb.net

修改

解决!感谢@Peter Campbell指出我正确的方向(然后做大部分腿部工作让我到那里)。代码改为:

If String.IsNullOrEmpty(output) Then
        exists = False
    Else
        exists = True
    End If
    If String.IsNullOrEmpty(output) Then Return String.Empty
    Dim c As GPCUser

    If TypeOf HttpContext.Current.Session("Customer") Is GPCUser Then
        c = CType(HttpContext.Current.Session("Customer"), GPCUser)

        If c.AccountNo > 0 Then Return ""
    End If

通过将设置'exists'布尔值的if语句移动到任何return语句之前,它们仍然可以正确触发并正确验证电子邮件,但也会正确地禁用该按钮。

结束修改

我有一个页面检查客户的电子邮件地址,看它是否在我们的数据库中。如果是,页面应该要求客户使用该电子邮件登录,而不是继续使用新帐户,但实际上并不会阻止他们继续使用。

我想禁用继续按钮,如果电子邮件地址已经在系统中但我无法弄清楚在哪里(我是商店的新网站开发人员,并且没有文档可以帮助我使用现有网站)

下面的代码,

<%@ Page Language="VB" MasterPageFile="~/Standard-no-menu.master"    AutoEventWireup="false" CodeFile="billing-details.aspx.vb" Inherits="billing_details" %>

“); - &gt; “); - &gt;                     

<script language="javascript" type="text/javascript">
 function validateForm()
{
if(document.getElementById('<%= lstPaymentOptions.ClientID %>').selectedIndex == "0")
{
    alert("Please select  \"payment method\".");
    document.getElementById('<%= lstPaymentOptions.ClientID  %>').focus();
    return (false);
}

if (aForgotPwd.style.display != null && aForgotPwd.style.display.toString() != "none") {
    var emailEle = document.getElementById("<%= txtEmail.ClientID %>");
    emailEle.focus();

    return false;
}


 if(document.getElementById('<%= txtEmail.ClientID %>').value=="")
{
    alert("Please enter a value in the field \"Email\".");
    document.getElementById('<%= txtEmail.ClientID %>').focus();
    return (false);
}

validemail=0;
var checkStr = document.getElementById('<%= txtEmail.ClientID %>').value;
for (i = 0; i < checkStr.length; i++)
{
    if(checkStr.charAt(i)=="@")
        validemail |= 1;
    if(checkStr.charAt(i)==".")
        validemail |= 2;
}
if(validemail != 3)
{
    alert("Please enter a valid email address.");
    document.getElementById('<%= txtEmail.ClientID %>').focus();
    return (false);
}


if(document.getElementById('<%= txtFirstName.ClientID %>').value=="")
{
    alert("Please enter a value in the field \"First Name\".");
    document.getElementById('<%= txtFirstName.ClientID %>').focus();
    return (false);
}

if(document.getElementById('<%= txtLastName.ClientID %>').value=="")
{
    alert("Please enter a value in the field \"Last Name\".");
    document.getElementById('<%= txtLastName.ClientID %>').focus();
    return (false);
}</script>
<asp:Panel runat="server" DefaultButton="btnContinue">

    <div class="billing-row">
<div class="cart-process-image"><img alt="" src="images/list_tick.gif"/></div>
<div class="cart-process-text">Shopping Cart</div>
<div class="cart-process-image"><img alt="" src="images/rightArrow.jpg"/></div>
<div class="cart-process-text"><strong>Personal and Shipping Details</strong></div>
<div class="cart-process-image"><img alt="" src="images/rightArrow.jpg"/></div>
<div class="cart-process-text">Payment Details</div>
</div>
<div class="billing-column-left">
    <div class="billing-holder">
        <div class="billing-row">
            <p><strong>Payment Method</strong></p>
            <div class="billing-column-mandatory">*</div>
            <div class="billing-column-label">How would you like to pay?</div>
            <div class="billing-column-textbox"><asp:DropDownList ID="lstPaymentOptions" runat="server" AppendDataBoundItems="True" CssClass="drop-down-list"></asp:DropDownList></div>
            <div><asp:RequiredFieldValidator ID="paymentValidator" runat="server"
            ControlToValidate="lstPaymentOptions" ErrorMessage="Please select a payment method" ForeColor="Red" InitialValue="Please Select">
        </asp:RequiredFieldValidator></div>            
        </div>
        </div>
        <div class="billing-row">
    </div>

    <div class="billing-holder">
        <p><strong>Your Contact Details</strong></p>
        <div class="billing-row">
            <div class="billing-column-mandatory">&nbsp;</div>
            <div class="billing-column-label">Company / Account Name: </div>
            <div class="billing-column-textbox"><asp:TextBox name="txtAccountName" ID="txtAccountName" MaxLength="60" Width="270" runat="server" CssClass="textbox"></asp:TextBox></div>
        </div>
        <div class="billing-row">
            <div class="billing-column-mandatory">*</div>
            <div class="billing-column-label">Email: <asp:RequiredFieldValidator ID="emailValidator" runat="server"
            ControlToValidate="txtEmail" ErrorMessage=" Required" ForeColor="Red">
        </asp:RequiredFieldValidator></div>
            <div class="billing-column-textbox"><asp:TextBox ID="txtEmail" MaxLength="60" 
                    Width="270" runat="server" CssClass="textbox" AutoPostBack="True"></asp:TextBox><b><a id="aForgotPwd" href="/forgotten-password.aspx" style="display:none">&nbsp;We have this email address already in our database. Click here to retrieve password?</a></b></div>
        </div>
        <div class="billing-row">
        <div class="billing-column-mandatory">*</div> 
        <div class="billing-column-label">First Name: <asp:RequiredFieldValidator ID="firstNameValidator" runat="server"
            ControlToValidate="txtFirstName" ErrorMessage=" Required" ForeColor="Red">
        </asp:RequiredFieldValidator></div>
        <div class="billing-column-textbox"><asp:TextBox name="txtFullName" ID="txtFirstName" MaxLength="30" Width="270" runat="server" CssClass="textbox"></asp:TextBox></div>
        </div>
        <div class="billing-row">
        <div class="billing-column-mandatory">*</div>
        <div class="billing-column-label">Last Name: <asp:RequiredFieldValidator ID="lastNameValidator" runat="server"
            ControlToValidate="txtLastName" ErrorMessage=" Required" ForeColor="Red">
        </asp:RequiredFieldValidator></div>
        <div class="billing-column-textbox"><asp:TextBox name="txtFullName" ID="txtLastName" MaxLength="30" Width="270" runat="server" CssClass="textbox"></asp:TextBox></div>
        </div>
    <div class="billing-holder">
        <p><strong>Additional Information relating to this order.</strong></p>
        <div class="billing-column-textfield"><asp:TextBox TextMode="MultiLine" Width="463" Height="212" runat="server" ID="txtAdditionalInfo" CssClass="textbox"></asp:TextBox></div>
        </div>
</div>
<asp:Panel ID="pnlVerticalResponse" runat="server" Visible="false">
<div class="billing-oos-background">
<div class="billing-row">
<asp:Label ID="lblSubscribe" runat="server" Text="<p><strong>You are not subscribed to our Newsletter:</strong>"></asp:Label></div>
<div class="billing-row"><asp:CheckBox ID="chkSubscribe" runat="server" />   I would like to receive information and promotional material from Global PC</div></div>
</asp:Panel>
<asp:Panel ID="pnlOutOfStockBlurb" runat="server" Visible="false" >
<div class="billing-oos-background"><div class="billing-row"><asp:Label ID="lblOutOfStockMessage" runat="server" Text="<strong>Items out of Stock:</strong><p>You have ordered one or more items that are currently out of stock. Normal procedure is for Global PC to hold the order until all items are in stock and ship entire order at once. However, if you wish you can elect to have your order split into two shipments with the out of stock items arriving at a later date. Would you like your order split into two shipments?</p>"></asp:Label></div>
<div class="billing-row"><asp:RadioButtonList ID="radlistSplit" runat="server" CellSpacing="5" AutoPostBack="true" CausesValidation="True" OnSelectedIndexChanged="radlistSplit_SelectedIndexChanged" CssClass="textbox" Borderwidth="0px"><asp:ListItem Value="0" Text="Yes, I want to recieve my order as two separate deliveries"></asp:ListItem><asp:ListItem Value="1" Text="No, I want to wait and receive all my items at once"></asp:ListItem></asp:RadioButtonList>
<asp:RequiredFieldValidator ID="splitvalidator" runat="server"
            ControlToValidate="radlistSplit" ErrorMessage="Please select one Shipping Option" ForeColor="Red">
        </asp:RequiredFieldValidator>
</div></div></asp:Panel>

<div class="billing-row">
    <div class="billing-button-cart">
        <div class="green-button">
            <a href="cart.aspx">Back To Cart</a>
        </div>
    </div>
    <div class="billing-button-checkout">
        <div class="green-button">
            <asp:linkButton text="Checkout" OnClientClick="return validateForm();" runat="server" ID="btnContinue" />
        </div>
    </div>
</div>
</asp:Panel>


</asp:Content>

VB.NET

Imports DataAccessLayer
Imports System.Net
Imports System.Data
Imports System.Net.Mail
Imports com.verticalresponse.api


Partial Class billing_details
    Inherits System.Web.UI.Page
    Protected c As GPCUser
    Dim isMember As Boolean = False
    Dim beMember As Boolean = False
    Shared exists As Boolean = False


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Master.Page.Title += " - Checkout"

        Dim listID As Integer
        Dim sessionID As Integer
        Dim VRUser As New VRAPI()
        Dim newSession As New loginArgs()

        newSession.username = "******@********.co.nz"
        ' Your VerticalResponse username
        newSession.password = "**********"
        'Your VerticalResponse password
        ' objLA.impersonate_user = "subaccount@emailaddress.com"; // If accessing or acting as a subaccount, uncomment this and replace it with the applicable email address.
        newSession.session_duration_minutes = "120"
        Dim [date] As DateTime = DateTime.Now
        listID = 284662333


        If TypeOf Session("Customer") Is GPCUser Then
            c = CType(Session("Customer"), GPCUser)
        Else
            c = New GPCUser
        End If

        If c.CartObjects.Count <= 0 Then
            Response.Redirect("cart.aspx")
        End If



        If Not Page.IsPostBack Then



            ' Check shipping to see if delivery details need to be displayed
            If c.ShippingMethodName Like "*Pick-Up*" Then
                pnlShippingDetails.Visible = False
            End If

            'Check if customer has ordered out of stock items
            If c.intOutOfStockItems >= 1 Then
                pnlOutOfStockBlurb.Visible = True
            Else
                pnlOutOfStockBlurb.Visible = False
            End If

            txtEmail.Attributes.Add("onblur", CStr(IIf(c.AccountNo > 0, "", "CallMe(this.id,this.id);")))
            lstPaymentOptions.DataSource = SqlHelper.ExecuteDataset(System.Configuration.ConfigurationManager.AppSettings("dbConn"), "xw_GetPaymentTypes").Tables(0)
            lstPaymentOptions.DataTextField = "PTDESC"
            lstPaymentOptions.DataValueField = "PTNO"
            lstPaymentOptions.Items.Insert(0, "Please Select")
            'lstPaymentOptions.DataBind()

            If c.CustomerID > 0 Then
                'populate the table
                txtAccountName.Text = c.AccountName
                txtFirstName.Text = c.FirstName
                txtLastName.Text = c.LastName
                txtEmail.Text = c.Email
                txtAddress.Text = c.Address
                txtCityTown.Text = c.City
                txtSuburb.Text = c.Suburb
                txtPostcode.Text = c.PostCode
                txtPhone.Text = c.Phone
                txtMobile.Text = c.Mobile



                Try
                    sessionId = VRUser.login(newSession)
                Catch ex As System.Exception
                    'lblMessage.Text = ex.ToString()
                End Try
                Dim getMember As New getListMemberByEmailAddressArgs()
                getMember.session_id = sessionId
                getMember.list_id = listID
                getMember.email_address = txtEmail.Text
                Try
                    VRUser.getListMemberByEmailAddress(getMember)
                    isMember = True
                    pnlVerticalResponse.Visible = False
                Catch ex As System.Exception
                    isMember = False
                    pnlVerticalResponse.Visible = True
                End Try

                If (isMember = False) Then
                    pnlVerticalResponse.Visible = True
                End If


                Dim dt As Data.DataTable = GPCUser.GetAccount(c.AccountNo)
                If dt IsNot Nothing Then
                    If dt.Rows.Count > 0 Then
                        Dim dr As Data.DataRow = dt.Rows(0)
                        If dr("CREDITSTATUS") > "0" And dr("STOPCREDIT") = "N" And dr("CREDLIMIT") > "0" Then
                            lstPaymentOptions.Items.Remove("Please Select")
                            lstPaymentOptions.Items.Insert(0, New ListItem("My Global PC Account", "99"))
                            lstPaymentOptions.Items.Insert(0, "Please Select")
                        End If
                    End If
                End If
                dt.Dispose()

            End If
        End If
    End Sub

    'RadioButtons to set whether customer wants split shipping
    Protected Sub radlistSplit_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles radlistSplit.SelectedIndexChanged
        If radlistSplit.SelectedIndex = "0" Then
            c.Instructions = "**CUSTOMER HAS SELECTED SPLIT SHIPPING**"

        ElseIf radlistSplit.SelectedIndex = "1" Then
            c.Instructions = ""

        End If
    End Sub

    Protected Sub btnContinue_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnContinue.Click

        If TypeOf Session("Customer") Is GPCUser Then
            c = CType(Session("Customer"), GPCUser)
        Else
            Exit Sub
        End If

        If chkSubscribe.Checked = True Then
            Dim listID As Integer = 284662333
            Dim isMember As Boolean = False


            Dim newSession As New loginArgs()
            newSession.username = "austin@globalpc.co.nz"

            ' Your VerticalResponse username
            newSession.password = "global2012"

            'Your VerticalResponse password
            ' objLA.impersonate_user = "subaccount@emailaddress.com"; // If accessing or acting as a subaccount, uncomment this and replace it with the applicable email address.
            newSession.session_duration_minutes = "120"

            Dim [date] As DateTime = DateTime.Now



            ' This is generated by creating a Service Reference that points to the VerticalResponse WSDL. 
            Dim VRUser As New VRAPI()



            ' Let's try to log in. The login call will return a session ID, which we will use in all subsequent calls.
            Dim sessionId As String = Nothing
            Try
                sessionId = VRUser.login(newSession)


            Catch ex As System.Exception
                txtAdditionalInfo.Text = ex.ToString()
                Exit Sub
            End Try

            Dim getMember As New getListMemberByEmailAddressArgs()
            getMember.session_id = sessionId
            getMember.list_id = listID
            getMember.email_address = txtEmail.Text

            Try
                VRUser.getListMemberByEmailAddress(getMember)
                isMember = True
            Catch ex As System.Exception
                isMember = False
            End Try
            If (isMember = False) Then
                Dim nMember As New ListMember()
                nMember.list_id = listID


                Dim memberData As NVPair() = New NVPair(2) {}

                memberData(0) = New NVPair()
                memberData(0).name = "email_address"
                memberData(0).value = txtEmail.Text

                memberData(1) = New NVPair()
                memberData(1).name = "first_name"
                memberData(1).value = txtFirstName.Text

                memberData(2) = New NVPair()
                memberData(2).name = "last_name"
                memberData(2).value = txtLastName.Text

                nMember.member_data = memberData

                Dim objAL As New addListMemberArgs()

                objAL.list_member = nMember
                objAL.session_id = sessionId

                Try
                    VRUser.addListMember(objAL)

                Catch ex As System.Exception
                    txtAdditionalInfo.Text = ex.ToString()
                    Exit Sub
                End Try

            Else


            End If

        End If

        c.PaymentType = lstPaymentOptions.SelectedValue
        c.CustomerOrderNo = txtOrderNumber.Text
        c.Instructions += txtAdditionalInfo.Text
        c.CreateCustomerDetails(txtAccountName.Text, txtFirstName.Text, txtLastName.Text, txtEmail.Text, txtAddress.Text, txtSuburb.Text, txtCityTown.Text, txtPostcode.Text, txtPhone.Text, txtMobile.Text, lstCountry.SelectedValue)
        c.AddShippingDetails(txtShippingFullName.Text, txtShippingAddress.Text, txtShippingCityTown.Text, txtShippingSuburb.Text, txtShippingPostcode.Text, lstShippingCountry.SelectedValue)

        If c.CustomerID = 0 Then
            Dim strPassword As String = ""
            If c.GeneratedPassword <= "" Then
                strPassword = UCase(RandomPassword.Generate(8, 8))
                c.GeneratedPassword = strPassword
            Else
                strPassword = c.GeneratedPassword
            End If

            GPCUser.AddUpdateCustomer(c)


            Dim dt As DataTable = GPCUser.GetUser(c.Email, strPassword)
            If Not dt Is Nothing Then
                If dt.Rows.Count > 0 Then
                    c.UpdateUser(dt.Rows(0)("CustID"))
                    Dim obj As Object = Session("Customer")
                    Session("Customer") = c
                Else

                End If
            Else
            End If

            Session("Customer") = c
        End If

        SendUpdateAccountEmailMessage(c.EmailCount)

        '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''


        Response.Redirect("payment-details.aspx")
    End Sub


    'Email Validation
    <System.Web.Services.WebMethod()> _
    Public Shared Function ValidateEmail(email As String) As String
        Dim wbClient As WebClient = New WebClient()
        Dim strUrl As String = ConfigurationManager.AppSettings("WebsiteURLFull") + "/ajax/check_email_address.aspx?Email=" + email
        Dim reqHTML As Byte()
        reqHTML = wbClient.DownloadData(strUrl)
        Dim objUTF8 As UTF8Encoding = New UTF8Encoding()
        Dim output As String = objUTF8.GetString(reqHTML)
        If String.IsNullOrEmpty(output) Then Return String.Empty
        Dim c As GPCUser

        If TypeOf HttpContext.Current.Session("Customer") Is GPCUser Then
            c = CType(HttpContext.Current.Session("Customer"), GPCUser)
            exists = False
            If c.AccountNo > 0 Then

                exists = True
            End If
            Return ""
        End If



        Return output
    End Function

    'Method to send an email from GlobalPC
    Private Sub SendMessage(fromEmail As String, fromEmailName As String, _
   toEmails As String(), IsBodyHtml As Boolean, message As String, subject As String)
        Dim mail As MailMessage = New MailMessage
        mail.From = New MailAddress(fromEmail, fromEmailName)

        For Each toEmail As String In toEmails
            mail.To.Add(New MailAddress(toEmail))
        Next

        mail.Bcc.Add(fromEmail)
        mail.IsBodyHtml = IsBodyHtml
        mail.Subject = subject
        mail.Body = message
        Dim s As New SmtpClient(System.Configuration.ConfigurationManager.AppSettings("MailServer"))
        s.Send(mail)
    End Sub


    'Sends email to GlobalPC if customer updates account details.
    Private Sub SendUpdateAccountEmailMessage(emailCount As Integer)
        Dim subject As String = "ALERT : Website user has updated his details"
        Dim message As String
        message &= "Account number " & c.AccountNo & " with email address " & c.Email & " has updated his account. Via page billing-details" & vbCrLf & vbCrLf
        message += "Account Name : " & txtAccountName.Text & vbCrLf
        message += "First Name : " & txtFirstName.Text & vbCrLf
        message += "Last Name : " & txtLastName.Text & vbCrLf
        message += "Email : " & txtEmail.Text & vbCrLf
        message += "Address : " & txtAddress.Text & vbCrLf
        message += "Suburb : " & txtSuburb.Text & vbCrLf
        message += "City Town : " & txtCityTown.Text & vbCrLf
        message += "Country : " & lstCountry.SelectedValue & vbCrLf
        message += "Postcode : " & txtPostcode.Text & vbCrLf
        message += "Phone : " & txtPhone.Text & vbCrLf
        message += "Mobile : " & txtMobile.Text & vbCrLf
        message += vbCrLf & vbCrLf
        message += "Shipping Information" & vbCrLf
        message += "txtShippingFullName.Text : " & txtShippingFullName.Text & vbCrLf
        message += "txtShippingAddress.Text  : " & txtShippingAddress.Text & vbCrLf
        message += "txtShippingCityTown.Text : " & txtShippingCityTown.Text & vbCrLf
        message += "txtShippingSuburb.Text : " & txtShippingSuburb.Text & vbCrLf
        message += "txtShippingPostcode.Text : " & txtShippingPostcode.Text & vbCrLf
        message += "lstShippingCountry.SelectedValue : " & lstShippingCountry.SelectedValue & vbCrLf
        message += vbCrLf & vbCrLf
        message += "More Information" & vbCrLf
        message += "Order No: " & c.CustomerOrderNo & vbCrLf
        message += "Payment Type: " & c.PaymentType & vbCrLf
        message += "Instructions: " & c.Instructions & vbCrLf
        message += vbCrLf & vbCrLf
        message += "Regards" & vbCrLf & vbCrLf & "GlobalPC Admin Team"

        SendMessage(ConfigurationManager.AppSettings("AccountDetailsUpdateEmail"), "Global PC", _
                                New String() {ConfigurationManager.AppSettings("AccountDetailsUpdateEmail")}, False, message, subject)
    End Sub



    Protected Sub txtEmail_TextChanged(sender As Object, e As System.EventArgs) Handles txtEmail.TextChanged

        Dim listID As Integer = 284662333
        Dim isMember As Boolean = False
        Dim newSession As New loginArgs()
        newSession.username = "austin@globalpc.co.nz"
        ' Your VerticalResponse username
        newSession.password = "global2012"
        'Your VerticalResponse password
        ' objLA.impersonate_user = "subaccount@emailaddress.com"; // If accessing or acting as a subaccount, uncomment this and replace it with the applicable email address.
        newSession.session_duration_minutes = "120"
        Dim [date] As DateTime = DateTime.Now
        ' This is generated by creating a Service Reference that points to the VerticalResponse WSDL. 
        Dim VRUser As New VRAPI()

        ' Let's try to log in. The login call will return a session ID, which we will use in all subsequent calls.
        Dim sessionId As String = Nothing

        Try
            sessionId = VRUser.login(newSession)
        Catch ex As System.Exception
            'lblMessage.Text = ex.ToString()
        End Try


        Dim getMember As New getListMemberByEmailAddressArgs()
        getMember.session_id = sessionId
        getMember.list_id = listID
        getMember.email_address = txtEmail.Text
        Try
            VRUser.getListMemberByEmailAddress(getMember)
            isMember = True
            pnlVerticalResponse.Visible = False
        Catch ex As System.Exception
            isMember = False
            pnlVerticalResponse.Visible = True
        End Try

    End Sub

    Protected Sub chkSubscribe_CheckedChanged(sender As Object, e As System.EventArgs) Handles chkSubscribe.CheckedChanged

        If chkSubscribe.Checked = True Then
            beMember = True
        Else
            beMember = False
        End If

    End Sub
End Class

1 个答案:

答案 0 :(得分:1)

根据此处的当前地址查看电子邮件

'Email Validation
    <System.Web.Services.WebMethod()> _
    Public Shared Function ValidateEmail(email As String) As String
        Dim wbClient As WebClient = New WebClient()
        Dim strUrl As String = ConfigurationManager.AppSettings("WebsiteURLFull") + "/ajax/check_email_address.aspx?Email=" + email
        Dim reqHTML As Byte()
        reqHTML = wbClient.DownloadData(strUrl)
        Dim objUTF8 As UTF8Encoding = New UTF8Encoding()
        Dim output As String = objUTF8.GetString(reqHTML)
        If String.IsNullOrEmpty(output) Then Return String.Empty
        Dim c As GPCUser

        If TypeOf HttpContext.Current.Session("Customer") Is GPCUser Then
            c = CType(HttpContext.Current.Session("Customer"), GPCUser)
            exists = False
            If c.AccountNo > 0 Then

                exists = True
            End If
            Return ""
        End If

所以存在是一个变量,它告诉你地址是否匹配。

尝试添加到Page_Load方法

 If Page.IsPostBack Then
   If exists Then
      btnContinue.enabled = false
   End If
 End If

当点击按钮后页面被回发到服务器时,这将检查是否存在是否为true以及是否禁用该按钮。

  

P.S。我会更改要使用的用户名/密码   ConfigurationManger.Appsettings并将您的用户名放在web.config中。

相关问题