ASP.NET Tutorial/Validation/RequiredFieldValidator — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Текущая версия на 11:57, 26 мая 2010

A simple use of the RequiredFieldValidator server control (C#)

<%@ Page Language="C#" %>
<script runat="server">
    protected void Button1_Click(Object sender, EventArgs e) {
       Label1.Text = "Page is valid!";
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>RequiredFieldValidator</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" Runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" 
                                    Runat="server" 
                                    ErrorMessage="Required!" 
                                    ControlToValidate="TextBox1">
        </asp:RequiredFieldValidator>
        <asp:Button ID="Button1" 
         Runat="server" 
         Text="Submit" 
         OnClick="Button1_Click" />
        <asp:Label ID="Label1" Runat="server"></asp:Label>    
    </div>
    </form>
</body>
</html>


asp:RequiredFieldValidator will be converted to JavaScript Code after loading in client side

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="MyPage" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Your name:
        <asp:TextBox ID="name" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="name"
            ErrorMessage="You must provide your name."></asp:RequiredFieldValidator><br />
        <br />
        <asp:Button ID="btnSubmit" runat="server" Text="Click Me" />
        <br />
        <br />
        <asp:Label ID="results" runat="server"></asp:Label></div>
    </form>
</body>
</html>
File: Default.aspx.vb

Partial Class MyPage
    Inherits System.Web.UI.Page
    Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
        If Page.IsValid Then
            results.Text = "Input is valid..."
        Else
            results.Text = "Input is <b>not</b> valid..."
        End If
    End Sub
End Class


Disabling client-side validations in a validation control

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" Runat="server"
  ErrorMessage="*" ControlToValidate="TextBox1" EnableClientScript="false">


EnableClientScript=false, Display=Static

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>Sample Validation Tester</title>
</head>
<body>
   <form id="form1" runat="server">
      <div>
         User
         <asp:TextBox ID="txtUserName" runat="server" />
         <asp:RequiredFieldValidator ID="reqUser" 
            runat="server" 
            ControlToValidate="txtUserName"
            EnableClientScript="false" 
            Display="Static"
            Text="Please enter a User Name" />
         <br />
         <asp:Button ID="btnTest" runat="server" Text="submit" />
         <br />
      </div>
   </form>
</body>
</html>


Hard code error message

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Login" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Simple Login Page</title>
</head>
<body>
    <form id="form1" runat="server">
    Username:<br />
          <asp:TextBox id="usernameTextBox" runat="server" />
          <asp:RequiredFieldValidator id="usernameReq"
              runat="server"
              ControlToValidate="usernameTextBox"
              ErrorMessage="Username is required!"
              SetFocusOnError="True" />
    Password and Confirmation:<br />
          <asp:TextBox id="passwordTextBox" runat="server"
              TextMode="Password" />
          <asp:RequiredFieldValidator id="passwordReq"
              runat="server"
              ControlToValidate="passwordTextBox"
              ErrorMessage="Password is required!"
              SetFocusOnError="True" />
          <asp:TextBox id="confirmPasswordTextBox" runat="server"
              TextMode="Password" />
          <asp:RequiredFieldValidator id="confirmPasswordReq"
              runat="server" ControlToValidate="confirmPasswordTextBox"
              ErrorMessage="Password confirmation is required!"
              SetFocusOnError="True" />
          <asp:Button id="submitButton" runat="server"
              Text="Submit" 
              OnClick="submitButton_Click" />
    </form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Login : System.Web.UI.Page
{
    protected void submitButton_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            submitButton.Text = "Valid";
        }
        else
        {
            submitButton.Text = "Invalid!";
        }
    }
}


Placing values between nodes

<%@ Page Language="VB" %>
<script runat="server">
   Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Label1.Text = "Page is valid!"
   End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>RequiredFieldValidator</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" Runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" 
                                    Runat="server" 
                                    ControlToValidate="TextBox1">
            Required!
        </asp:RequiredFieldValidator>
        <br />
        <asp:Button ID="Button1" Runat="server" Text="Submit" 
         OnClick="Button1_Click" />
        <br />
        <br />
        <asp:Label ID="Label1" Runat="server"></asp:Label>    
    </div>
    </form>
</body>
</html>


RequiredFieldValidator Dynamic Display

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Login" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Simple Login Page</title>
</head>
<body>
    <form id="form1" runat="server">
     Username:
          <asp:TextBox id="usernameTextBox" runat="server" />
          <asp:RequiredFieldValidator id="usernameReq"
              runat="server"
              ControlToValidate="usernameTextBox"
              ErrorMessage="Username is required!"
              SetFocusOnError="True" />
     Password and Confirmation:<br />
          <asp:TextBox id="passwordTextBox" runat="server"
              TextMode="Password" />
          <asp:RequiredFieldValidator id="passwordReq"
              runat="server"
              ControlToValidate="passwordTextBox"
              ErrorMessage="Password is required!"
              SetFocusOnError="True" 
              Display="Dynamic" />
          <asp:TextBox id="confirmPasswordTextBox" 
              runat="server"
              TextMode="Password" />
          <asp:RequiredFieldValidator id="confirmPasswordReq"
              runat="server" 
              ControlToValidate="confirmPasswordTextBox"
              ErrorMessage="Password confirmation is required!"
              SetFocusOnError="True" 
              Display="Dynamic" />
          <asp:Button id="submitButton" 
                      runat="server"
                      Text="Submit" 
                      OnClick="submitButton_Click" />
    </div>
    </form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Login : System.Web.UI.Page
{
    protected void submitButton_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            submitButton.Text = "Valid";
        }
        else
        {
            submitButton.Text = "Invalid!";
        }
    }
}


RequiredFieldValidator for login page

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Simple Login Page</title>
</head>
<body>
    <form id="form1" runat="server">
    Username:
          <asp:TextBox id="usernameTextBox" runat="server" />
          <asp:RequiredFieldValidator id="usernameReq"
              runat="server"
              ControlToValidate="usernameTextBox"
              ErrorMessage="Username is required!"
              SetFocusOnError="True" />
    Password:<br />
          <asp:TextBox id="passwordTextBox" 
              runat="server"
              TextMode="Password" />
          <asp:RequiredFieldValidator id="passwordReq"
              runat="server"
              ControlToValidate="passwordTextBox"
              ErrorMessage="Password is required!"
              SetFocusOnError="True" />
          <asp:Button id="submitButton" runat="server"
              Text="Submit" />
    </form>
</body>
</html>


RequiredFieldValidator requires a user to enter a value into a form field before submitting the form.

Two important properties when using the RequiredFieldValdiator control:
ControlToValidate: The ID of the form field being validated.
Text:              The error message.
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Show RequiredFieldValidator</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Label
        id="lblFirstName"
        Text="First Name:"
        AssociatedControlID="txtFirstName"
        Runat="server" />
    <asp:TextBox
        id="txtFirstName"
        Runat="server" />
    <asp:RequiredFieldValidator
        id="reqFirstName"
        ControlToValidate="txtFirstName"
        Text="(Required)"
        Runat="server" />
    <asp:Label
        id="lblLastName"
        Text="Last Name:"
        AssociatedControlID="txtLastName"
        Runat="server" />
    <br />
    <asp:TextBox
        id="txtLastName"
        Runat="server" />
    <asp:RequiredFieldValidator
        id="reqLastName"
        ControlToValidate="txtLastName"
        Text="(Required)"
        Runat="server" />
    <asp:Button
        id="btnSubmit"
        Text="Submit"
        Runat="server" />
    </div>
    </form>
</body>
</html>


RequiredFieldValidator with server side validation

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Login" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Simple Login Page</title>
</head>
<body>
    <form id="form1" runat="server">
    Username:<br />
          <asp:TextBox id="usernameTextBox" runat="server" />
          <asp:RequiredFieldValidator id="usernameReq"
              runat="server"
              ControlToValidate="usernameTextBox"
              ErrorMessage="Username is required!"
              SetFocusOnError="True" />
    Password:<br />
          <asp:TextBox id="passwordTextBox" 
              runat="server"
              TextMode="Password" />
          <asp:RequiredFieldValidator id="passwordReq"
              runat="server"
              ControlToValidate="passwordTextBox"
              ErrorMessage="Password is required!"
              SetFocusOnError="True" />
          <asp:Button id="submitButton" 
              runat="server"
              Text="Submit" 
              OnClick="submitButton_Click" />
    </form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Login : System.Web.UI.Page
{
    protected void submitButton_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            submitButton.Text = "Valid";
        }
        else
        {
            submitButton.Text = "Invalid!";
        }
    }
}


Specify ErrorMessage for asp:RequiredFieldValidator

<%@ Page Language="VB" AutoEventWireup="false" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator 
            ID="RequiredFieldValidator1" 
            runat="server" 
            ControlToValidate="TextBox1"
            ErrorMessage="error"></asp:RequiredFieldValidator>
        This text appears right after a textbox.
        <br />
        <br />
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="TextBox2"
            Display="Dynamic" ErrorMessage="error"></asp:RequiredFieldValidator>
        This text appears right after a textbox.
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" Text="Button" /></div>
    </form>
</body>
</html>


Text field of RequiredFieldValidator server control (VB)

<%@ Page Language="VB" %>
<script runat="server">
   Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Label1.Text = "Page is valid!"
   End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>RequiredFieldValidator</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" Runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" 
                                    Runat="server" 
                                    Text="Required!"
                                    ErrorMessage="Required!" 
                                    ControlToValidate="TextBox1">
        </asp:RequiredFieldValidator>
        <br />
        <asp:Button ID="Button1" Runat="server" Text="Submit" 
         OnClick="Button1_Click" />
        <br />
        <br />
        <asp:Label ID="Label1" Runat="server"></asp:Label>    
    </div>
    </form>
</body>
</html>


Use asp:RequiredFieldValidator to check the input of an asp:TextBox (VB.net)

<%@ Page Language="VB" %>
<script runat="server">
   sub Submit(Sender as Object, e as EventArgs)
      if Page.IsValid then
         lblMessage.Text = "You passed validation!"
      end if   
   end sub
</script>
<html>
<body>
   <form runat="server">
      <asp:Label id="lblMessage" runat="server" />
      Enter your name:
      <asp:TextBox id="tbFName" runat="server" /><br>
      <asp:RequiredFieldValidator runat="server" ControlToValidate="tbFName" ErrorMessage="First name required"/>
      <asp:Button id="tbSubmit" runat="server" Text="Submit" OnClick="Submit" />
   </form>
</body>
</html>


Use the RequiredFieldValidator"s InitialValue to set a default value

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    void btnSubmit_Click(Object sender, EventArgs e)
    {
        if (Page.IsValid)
            lblResult.Text = dropFavoriteColor.SelectedValue;
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Show Initial Value</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Label
        id="lblFavoriteColor"
        Text="Favorite Color:"
        AssociatedControlID="dropFavoriteColor"
        Runat="server" />
    <br />
    <asp:DropDownList
        id="dropFavoriteColor"
        Runat="server">
        <asp:ListItem Text="Select Color" Value="none" />
        <asp:ListItem Text="Red" Value="Red" />
        <asp:ListItem Text="Blue" Value="Blue" />
        <asp:ListItem Text="Green" Value="Green" />
    </asp:DropDownList>
    <asp:RequiredFieldValidator
        id="reqFavoriteColor"
        Text="(Required)"
        InitialValue="none"
        ControlToValidate="dropFavoriteColor"
        Runat="server" />
    <asp:Button
        id="btnSubmit"
        Text="Submit"
        Runat="server" OnClick="btnSubmit_Click" />
    <asp:Label
        id="lblResult"
        Runat="server" />
    </div>
    </form>
</body>
</html>


Using images for error notifications

<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
 Runat="server" ErrorMessage="<img src="error.gif">"
 ControlToValidate="TextBox1"></asp:RequiredFieldValidator>


Using sound for error notifications

<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
 Runat="server" ErrorMessage="<bgsource src="C:\Windows\Media\tada.wav">"
 ControlToValidate="TextBox1" EnableClientScript="False">
</asp:RequiredFieldValidator>


Using two RequiredFieldValidator controls for one form element

<%@ Page Language="VB" %>
<script runat="server">
   Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Label1.Text = "Page is valid!"
   End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>RequiredFieldValidator</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" Runat="server">My Initial Value</asp:TextBox>&nbsp;
            
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" 
                                    Runat="server" 
                                    ErrorMessage="Please change value" 
                                    ControlToValidate="TextBox1"
                                    InitialValue="My Initial Value"/>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" 
                                    Runat="server"
                                    ErrorMessage="Do not leave empty" 
                                    ControlToValidate="TextBox1">
        </asp:RequiredFieldValidator>
        <br />
        <asp:Button ID="Button1" Runat="server" Text="Submit" 
         OnClick="Button1_Click" />
        <br />
        <br />
        <asp:Label ID="Label1" Runat="server"></asp:Label>    
    </div>
    </form>
</body>
</html>


Validating Drop-Down Lists with the RequiredFieldValidator Control

<%@ Page Language="VB" %>
<script runat="server">
   Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Label1.Text = "Page is valid!"
   End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>RequiredFieldValidator</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList id="DropDownList1" runat="server">
           <asp:ListItem Selected="True">Select a profession</asp:ListItem>
           <asp:ListItem>Programmer</asp:ListItem>
           <asp:ListItem>Lawyer</asp:ListItem>
           <asp:ListItem>Doctor</asp:ListItem>
           <asp:ListItem>Artist</asp:ListItem>
        </asp:DropDownList>
        <asp:RequiredFieldValidator id="RequiredFieldValidator1" 
                                    runat="server" 
                                    ErrorMessage="Please make a selection"
                                    ControlToValidate="DropDownList1"
                                    InitialValue="Select a profession">
        </asp:RequiredFieldValidator>
        <br />
        <asp:Button ID="Button1" Runat="server" Text="Submit" 
         OnClick="Button1_Click" />
        <br />
        <br />
        <asp:Label ID="Label1" Runat="server"></asp:Label>    
    </div>
    </form>
</body>
</html>


Working with the InitialValue property

<%@ Page Language="VB" %>
<script runat="server">
   Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Label1.Text = "Page is valid!"
   End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>RequiredFieldValidator</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" Runat="server">My Initial Value</asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1"  
                                    Runat="server" 
                                    ErrorMessage="Please change the value of the textbox!" 
                                    ControlToValidate="TextBox1" 
                                    InitialValue="My Initial Value">
        </asp:RequiredFieldValidator>
        <br />
        <asp:Button ID="Button1" Runat="server" Text="Submit" 
         OnClick="Button1_Click" />
        <br />
        <br />
        <asp:Label ID="Label1" Runat="server"></asp:Label>    
    </div>
    </form>
</body>
</html>