how to make a validation code for ASP.NET form wit

2019-09-08 05:50发布

问题:

im trying to build a form+attachment that needs to be send to email. Im using a VB background code (attachementemail.aspx.vb) and my front (b-16.aspx)

I want the page to check that the user entered a email, name, phonenumber and attachment.

what command do I put in the axp.vb and what on the .aspx

tried just about anything.

回答1:

At it's basic level you could use RequiredFieldValidator and CustomValidation in your form. You can use some regex logic for email, I use this but there are many out there:

Regex(@"\w+([-+.]\w+)@\w+([-.]\w+).\w+([-.]\w+)*")

Personally I use client side javascript before it hits the server and then I re-validate the entries once it hits the server. If your using the postback events then you'll need update panels and a scriptmanager (not sure if you are aware of this already, so apologies if teaching you to suck eggs!).

Here is an example:

<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
    ErrorMessage="RequiredFieldValidator" ControlToValidate="TextBox1"></asp:RequiredFieldValidator>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>

Code behind (sorry this is in c#)

protected void Button1_Click(object sender, EventArgs e)
{
    if (RequiredFieldValidator1.IsValid)
    {
        Label1.Text = "Has content";
    }
    else
    {
        Label1.Text = "Not valid";
    }
}

Note that the required field validator has it's own methods to display a "hey you haven't entered content here my friend" message, but i have added that to the label instead.



回答2:

The simplest way is to use validators eg RequiredFieldValidator for mandatory fields. You can also implement CustomValidators for custom logic.

See http://msdn.microsoft.com/en-us/e5a8xz39.aspx for the available validators