Asp.net无法获得焦点损失

问题描述 投票:0回答:1

我目前正在用asp.net制作一个表单,这是我的第一个网页,所以我试图让OnBlur事件工作,但我无法做到。

这是我的代码:-

联系人.aspx

<%@ Page Language="C#" MasterPageFile="MasterPage.master" AutoEventWireup="true" CodeFile="contact.aspx.cs" Inherits="contact" Title="Contact Us" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<title>Sugarsnooper | Contact Us</title>
<meta name="keyword" content=""/>
<meta name="Description" content=""/>
<meta name="key-phrases" content=""/>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<section class="content-page"><div class="container"><div class="row">
<div class="col-md-12"><h1>Contact Us</h1></div>
<div class="col-md-8">
<h4>Enquiry Form</h4>
<form id="form1" runat="server">

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

        <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always" ChildrenAsTriggers="true">
        <ContentTemplate>
<div class="col-lg-12 form-group">

        <div class="row">
        <input name="name" runat="server" type="text" id="name2" class="form-control" placeholder="Enter Your Name">
        <asp:Label ID="invalidname" runat="server" Text=""/>
        </div>
      </div>
<div class="col-lg-12 form-group">
        <div class="row">
        <input name="website" runat="server" type="text" id="cont2" class="form-control" placeholder="Enter Mobile Number">
<asp:Label ID="invalidmobile" runat="server" Text=""/>    
    </div>
      </div>
<div class="col-lg-12 form-group">
        <div class="row">
       <input onblur="validate()" name="email" runat="server" type="text" id="email3" class="form-control" placeholder="Enter Your Email ID">
    <asp:Label ID="invalidemail" runat="server" Text=""/>
        </div>
      </div>
<div class="col-lg-12 form-group">
        <div class="row">
        <textarea name="message" runat="server" id="msg2" class="form-control" placeholder="Enter Your Message.." rows="6"></textarea>
        <asp:Label ID="invalidmessage" runat="server" Text=""/>
        </div>
      </div>
<div class="col-lg-12 form-group">
        <div class="row">
          <input type="submit" class="btn btn-primary" id="enquiry_post" value="Send"             
       runat="server" onserverclick="enquiry_post_click"/>
     <asp:Label style="margin: 60" ID="message" runat="server" Text=""/>

        </div>


      </div>

       </ContentTemplate>
    </asp:UpdatePanel>

      </form>
</div>
<div class="col-md-4"><h4>Contact Info</h4>
<table class="table">
<tr>
<td>Email</td>
<td><a href="mailto:[email protected]">[email protected]</a></td>
</tr>
<tr style="display:none;">
<td>Helpline No.</td>
<td>xxx xxx xxxx</td>
</tr>
</table>
</div>
</div></div></section>
</asp:Content>

联系人.aspx.cs

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text.RegularExpressions;
using System.Drawing;

public partial class contact : System.Web.UI.Page
{


    //private Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");


    int i = 0;

    private static Regex EmailValidation()
    {
    const string pattern = @"^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$";
    const RegexOptions options = RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture;

    // Set explicit regex match timeout, sufficient enough for email parsing
    // Unless the global REGEX_DEFAULT_MATCH_TIMEOUT is already set
    TimeSpan matchTimeout = TimeSpan.FromSeconds(2);

    try
    {
        if (AppDomain.CurrentDomain.GetData("REGEX_DEFAULT_MATCH_TIMEOUT") == null)
        {
            return new Regex(pattern, options, matchTimeout);
        }
    }
    catch
    {
        // Fallback on error
    }

    // Legacy fallback (without explicit match timeout)
    return new Regex(pattern, options);
    }


    private bool IsValidPhoneNumber(string num)
    {
        var phoneNumber = num.Trim()
            .Replace(" ", "")
            .Replace("-", "")
            .Replace("(", "")
            .Replace(")", "");
        return Regex.Match(phoneNumber, @"^\+\d{5,15}$").Success || Regex.Match(phoneNumber, @"^\d{5,15}$").Success;
    }

    private bool validateemailandupdate(){
    string emailid = email3.Value;
    if(emailid.Length > 0){
    Match match = EmailValidation().Match(emailid);
    if(!match.Success){
    invalidemail.ForeColor = Color.Red;
    invalidemail.Font.Bold = true;
    invalidemail.Text = "Email is Invalid";
    return false;
    }
    invalidemail.Text = "";
    return true;
    }
    else{
    invalidemail.ForeColor = Color.Red;
    invalidemail.Font.Bold = true;
    invalidemail.Text = "This Field is Required";
    return false;
    }
    }


    private bool validatemobileandupdate(){

    string mobile = cont2.Value;
    if(mobile.Length > 0){
    bool isalldigits = IsValidPhoneNumber(mobile);
    bool islengthenough = mobile.Length > 5;
    bool islengthless = mobile.Length < 16;
    bool isnumbervalid = isalldigits && islengthenough && islengthless;
    if(isnumbervalid){
    invalidmobile.Text = "";
    return true;
    }
    invalidmobile.ForeColor = Color.Red;
    invalidmobile.Font.Bold = true;
    invalidmobile.Text = "Please enter a Valid Phone Number";
    return false;
    }
    else{
    invalidmobile.ForeColor = Color.Red;
    invalidmobile.Font.Bold = true;
    invalidmobile.Text = "This Field is Required";
    return false;
    }

    }



    private bool validatenameandupdate(){
    string name = name2.Value;
    if(name.Length > 50){
    invalidname.ForeColor = Color.Red;
    invalidname.Font.Bold = true;
        invalidname.Text = "Name Too Long";
        return false;
    }
    if(name.Length < 1){
    invalidname.ForeColor = Color.Red;
    invalidname.Font.Bold = true;
        invalidname.Text = "This Field is Requred";
        return false;
    }
    invalidname.Text = "";
    return true;
    }



    private bool validatemsgandupdate(){
    string msg = msg2.Value;
    if(msg.Length > 0){
        invalidmessage.Text = "";
        return true;
    }
    else{
    invalidmessage.ForeColor = Color.Red;
    invalidmessage.Font.Bold = true;
        invalidmessage.Text = "This Field is Requred";
        return false;
    }
    }


    protected void Page_Load(object sender, EventArgs e)
    {
        //msg2.Attributes.Add("OnBlur", "return validate()");
    }


public void validate(){
    i++;
    //bool isemailvalid = validateemailandupdate();
    //bool ismobilevalid = validatemobileandupdate();
    //bool isnamevalid = validatenameandupdate();
    //bool ismsgvalid = validatemsgandupdate();
//UpdatePanel1.Update();
}


    protected void enquiry_post_click(object sender, EventArgs e){

    bool isemailvalid = validateemailandupdate();
    bool ismobilevalid = validatemobileandupdate();
    bool isnamevalid = validatenameandupdate();
    bool ismsgvalid = validatemsgandupdate();
    bool result = isemailvalid && ismobilevalid && isnamevalid && ismsgvalid;

        message.Text = i.ToString();
        if (result){
       cont2.Value = "";
       email3.Value = "";
       name2.Value = "";
       msg2.Value = "";
    }
    }

}

我试过使用onfocusout,但也没有用。我还试过使用 onblur="validate();"onblur="return validate();" 和2或3更多的变化,但没有工作Pls帮助Thanks在前进。

asp.net events onblur
1个回答
0
投票

首先你要使用一个像 asp:TextBox 而非 input-控制。

<asp:TextBox ID="email3" CssClass="form-control" AutoPostBack="true" runat="server"/>

如果你想对服务器端的变化做出反应,你可以在下面添加 AutoPostBack 并使用改变的事件--所以在你后面的代码中。

protected void Page_Init(object sender, EventArgs e)
{
    email3.TextChanged += Email3_TextChanged;
}

private void Email3_TextChanged(object sender, EventArgs e)
{
    validate();
}

如果你想添加一些验证,你可以在页面中添加一个验证器,如图所示。此处

<asp:RegularExpressionValidator ID="regexEmailValid" runat="server" ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="email3" ErrorMessage="Invalid Email Format"></asp:RegularExpressionValidator>
© www.soinside.com 2019 - 2024. All rights reserved.