Validate HTML Controls

From Guidance Share

Jump to: navigation, search

- J.D. Meier, Alex Mackman, Michael Dunner, Srinath Vasireddy, Ray Escamilla and Anandha Murukan

If you do not use server controls — that is, controls with the runat="server" attribute — and instead use regular HTML controls, you cannot use the ASP.NET validator controls. Instead, you can validate your Web pages' content by using regular expressions in the Page_Load event handler, as follows.

using System.Text.RegularExpressions;
. . .
private void Page_Load(object sender, System.EventArgs e)
{
 // Note that IsPostBack applies only for 
 // server forms (with runat="server")
 if ( Request.RequestType == "POST" ) // non-server forms
 {
   // Validate the supplied email address
   if( !Regex.Match(Request.Form["email"], 
        @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*",
        RegexOptions.None).Success) 
   {
     // Invalid email address
   }
   // Validate the supplied name
   if ( !RegEx.Match(Request.Form["name"],
        @"[A-Za-z'\- ]",
        RegexOptions.None).Success) 
   {
     // Invalid name
   }
 }
}


References

Personal tools