欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Asp.Mvc 2.0用户登录实例讲解---(4)服务器端验证

程序员文章站 2022-07-01 23:05:36
这一节给大家讲解下asp.net mvc 2.0的服务器端验证的用法。大家知道,一个项目只用js客户端验证是不安全的,用户可以禁用js来绕过客户端验证,所以必须有服务器端验证。 关于服务器端验证,主...

这一节给大家讲解下asp.net mvc 2.0的服务器端验证的用法。大家知道,一个项目只用js客户端验证是不安全的,用户可以禁用js来绕过客户端验证,所以必须有服务器端验证。

关于服务器端验证,主要调用system.componentmodel.dataannotations命名空间里面的类库。

具体用法参照:

x">http://msdn.microsoft.com/zh-cn/library/system.componentmodel.dataannotations.aspx

 

咱们这次还是以注册页面为例来讲解服务器端验证。

主要对注册页面做如下验证

1.用户名不能为空

 

2.密码不能为空,密码长度不能小于5位数,

 

3.密码和确认密码输入必须一样

 

4.邮件格式必须正确

 

咱们先看下效果图

 Asp.Mvc 2.0用户登录实例讲解---(4)服务器端验证


 

mvc中对所有字段的验证,实际上只需要在model层设置验证规则就可以。

 

1.用户名验证

对用户名的验证,只需要验证用户名不为空就可以了,使用required属性,把此属性绑定到model的用户名字段上就可以了。

[csharp]  /// <summary>  
       /// 用户名  
       /// </summary>  
        [displayname("用户名")] 
        [required(errormessage="用户名不能为空!")] 
        public string username 
        { get; set; } 
/// <summary>
       /// 用户名
       /// </summary>
        [displayname("用户名")]
        [required(errormessage="用户名不能为空!")]
        public string username
        { get; set; }

 

  required里面的参数表示具体的提示信息,此时如果用户名为空,就会在前台aspx页面出现用户名不能为空的提示。当然要在前台显示错误的提示信息。使用<%:html.validationmessagefor(m=>m.username)%>

标记就可以在前台显示错误的提示信息

 

2.密码验证

 

密码验证包括密码不能为空和密码长度限制。

验证密码为空和验证用户名为空一样,使用required属性。

验证密码的长度使用stringlength属性

 

[csharp] /// <summary>  
       /// 密码  
       /// </summary>  
      [displayname("密码")] 
       [required(errormessage="密码不能为空")] 
       [stringlength(10, errormessage = "密码长度不能小于5位",minimumlength=5)] 
       public string userpwd 
       { 
           get; 
           set; 
       } 
 /// <summary>
        /// 密码
        /// </summary>
       [displayname("密码")]
        [required(errormessage="密码不能为空")]
        [stringlength(10, errormessage = "密码长度不能小于5位",minimumlength=5)]
        public string userpwd
        {
            get;
            set;
        }

 

stringlength的第一个参数表示密码的最大长度,errormessage表示不满足条件的时候的错误提示信息。

minimumlength表示输入内容的最小长度.

当然,前台必须有地方显示错误信息,显示错误信息我们使用如下

<%:html.validationmessagefor(m=>m.userpwd)%>

 

3.验证密码和确认密码是否一致

 

要验证密码和确认密码是否一致,这个稍微有点复杂,需要我们自定义验证规则。自定义验证规则我们需要继承validationattribute类.然后实现它的isvaild方法.

 

[csharp] /// <summary>  
   /// 此自定义类用于验证密码和确认密码必须一致  
   /// </summary>  
   [attributeusage(attributetargets.class, allowmultiple = true, inherited = true)] 
   public class pwdmatch :validationattribute 
   { 
 
       private object _typeid = new object(); 
       public string pwd { get; set; }//密码  
       public string confirmpwd { get; set; }//确认密码  
 
 
       public pwdmatch(string pwd, string confirmpwd) 
           : base() 
       { 
           pwd = pwd; 
           confirmpwd = confirmpwd; 
       } 
 
       /// <summary>  
       /// 返回错误的提示信息  
       /// </summary>  
       /// <param name="name"></param>  
       /// <returns></returns>  
       public override string formaterrormessage(string name) 
       { 
           return errormessage; 
       } 
 
       /// <summary>  
       /// 重写typeid  
       /// </summary>  
       public override object typeid 
       { 
           get 
           { 
               return _typeid; 
           } 
       } 
 
      /// <summary>  
      /// 判断是否想到  
      /// </summary>  
       /// <param name="value">value的值实际上是model提交的model类</param>  
      /// <returns></returns>  
       public override bool isvalid(object value) 
       { 
           propertydescriptorcollection properties = typedescriptor.getproperties(value); 
           object originalvalue = properties.find(pwd, true ).getvalue(value);//获取密码  
           object confirmvalue = properties.find(confirmpwd, true).getvalue(value);//获取确认密码的值  
           return object.equals(originalvalue, confirmvalue); 
 
       } 
   } 
 /// <summary>
    /// 此自定义类用于验证密码和确认密码必须一致
    /// </summary>
    [attributeusage(attributetargets.class, allowmultiple = true, inherited = true)]
    public class pwdmatch :validationattribute
    {

        private object _typeid = new object();
        public string pwd { get; set; }//密码
        public string confirmpwd { get; set; }//确认密码


        public pwdmatch(string pwd, string confirmpwd)
            : base()
        {
            pwd = pwd;
            confirmpwd = confirmpwd;
        }

        /// <summary>
        /// 返回错误的提示信息
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public override string formaterrormessage(string name)
        {
            return errormessage;
        }

        /// <summary>
        /// 重写typeid
        /// </summary>
        public override object typeid
        {
            get
            {
                return _typeid;
            }
        }

       /// <summary>
       /// 判断是否想到
       /// </summary>
        /// <param name="value">value的值实际上是model提交的model类</param>
       /// <returns></returns>
        public override bool isvalid(object value)
        {
            propertydescriptorcollection properties = typedescriptor.getproperties(value);
            object originalvalue = properties.find(pwd, true ).getvalue(value);//获取密码
            object confirmvalue = properties.find(confirmpwd, true).getvalue(value);//获取确认密码的值
            return object.equals(originalvalue, confirmvalue);

        }
    }
 

 

  pwdmatch属性类创建后,可把它标记在注册model的上面,然后提交注册的时候,就会验证了

  [pwdmatch("userpwd","confirpwd", errormessage ="密¨¹码?与®?确¨¡¤认¨?不?匹£¤配?")]

    public class registermodel

{

 

}

 

  pwdmatch的第一个参数表上密码,名称与registermodel中的密码属性相同,

第二个字段是确认密码,名称与registermodel与的确认密码属性相同。

最后一个参数是错误提示信息.

 

当然,也要在前台显示错误提示信息,使用

<%:html.validationsummary(true,"用®?户¡ì创ä¡ä建¡§失º¡ì败㨹!")%>就可以在前台显示一个总的错误信息列表.

 

4.邮箱验证

 

 邮箱验证主要是邮箱格式验证,验证格式是否满足要求.

验证邮箱我们使用regularexpressions属性就可以

 

[csharp] /// <summary>  
       /// 用户邮箱  
       /// </summary>  
       [displayname("邮箱")] 
       //[datatype(datatype.emailaddress)]  
       [regularexpression(@"^\w+((-\w+)|(\.\w+))*\@[a-za-z0-9]+((\.|-)[a-za-z0-9]+)*\.[a-za-z0-9]+$", errormessage = "电子邮件格式错误")] 
       public string email 
       { 
           get; 
           set; 
       } 
 /// <summary>
        /// 用户邮箱
        /// </summary>
        [displayname("邮箱")]
        //[datatype(datatype.emailaddress)]
        [regularexpression(@"^\w+((-\w+)|(\.\w+))*\@[a-za-z0-9]+((\.|-)[a-za-z0-9]+)*\.[a-za-z0-9]+$", errormessage = "电子邮件格式错误")]
        public string email
        {
            get;
            set;
        }
 

 

第一个参数邮箱验证的正则表达式,第二个参数是错误提示信息.

 

在aspx页面显示错误信息用

<%:html.validationmessagefor(m=>m.email)%>

 

 

 

以上是对用户注册信息的验证,当然,我们在提交信息的时候,要判断验证是否通过,我们使用modelstate.isvalid来判断验证是否通过,true表示通过。false表示未通过.

 

model代码

  

[csharp] /// <summary>  
    /// 注册用户model  
    /// </summary>  
    [pwdmatch("userpwd", "confirpwd", errormessage = "密码与确认不匹配")] 
    public class registermodel 
    { 
       /// <summary>  
       /// 用户名  
       /// </summary>  
        [displayname("用户名")] 
        [required(errormessage="用户名不能为空!")] 
        public string username 
        { get; set; } 
 
        /// <summary>  
        /// 密码  
        /// </summary>  
       [displayname("密码")] 
        [required(errormessage="密码不能为空")] 
        [stringlength(10, errormessage = "密码长度不能小于5位",minimumlength=5)] 
        public string userpwd 
        { 
            get; 
            set; 
        } 
 
       [displayname("确认密码")] 
       [required(errormessage="确认密码不能为空!")] 
       [stringlength(10, errormessage = "确认密码长度不能小于5位",minimumlength=5)] 
      public string confirpwd 
      { 
          get; 
          set; 
      } 
        /// <summary>  
        /// 用户邮箱  
        /// </summary>  
        [displayname("邮箱")] 
        //[datatype(datatype.emailaddress)]  
        [regularexpression(@"^\w+((-\w+)|(\.\w+))*\@[a-za-z0-9]+((\.|-)[a-za-z0-9]+)*\.[a-za-z0-9]+$", errormessage = "电子邮件格式错误")] 
        public string email 
        { 
            get; 
            set; 
        } 
 
     
    } 
 
    
    /// <summary>  
    /// 此自定义类用于验证密码和确认密码必须一致  
    /// </summary>  
    [attributeusage(attributetargets.class, allowmultiple = true, inherited = true)] 
    public class pwdmatch :validationattribute 
    { 
 
        private object _typeid = new object(); 
        public string pwd { get; set; }//密码  
        public string confirmpwd { get; set; }//确认密码  
 
 
        public pwdmatch(string pwd, string confirmpwd) 
            : base() 
        { 
            pwd = pwd; 
            confirmpwd = confirmpwd; 
        } 
 
        /// <summary>  
        /// 返回错误的提示信息  
        /// </summary>  
        /// <param name="name"></param>  
        /// <returns></returns>  
        public override string formaterrormessage(string name) 
        { 
            return errormessage; 
        } 
 
        /// <summary>  
        /// 重写typeid  
        /// </summary>  
        public override object typeid 
        { 
            get 
            { 
                return _typeid; 
            } 
        } 
 
       /// <summary>  
       /// 判断是否想到  
       /// </summary>  
        /// <param name="value">value的值实际上是model提交的model类</param>  
       /// <returns></returns>  
        public override bool isvalid(object value) 
        { 
            propertydescriptorcollection properties = typedescriptor.getproperties(value); 
            object originalvalue = properties.find(pwd, true ).getvalue(value);//获取密码  
            object confirmvalue = properties.find(confirmpwd, true).getvalue(value);//获取确认密码的值  
            return object.equals(originalvalue, confirmvalue); 
 
        } 
    } 
/// <summary>
    /// 注册用户model
    /// </summary>
    [pwdmatch("userpwd", "confirpwd", errormessage = "密码与确认不匹配")]
    public class registermodel
    {
       /// <summary>
       /// 用户名
       /// </summary>
        [displayname("用户名")]
        [required(errormessage="用户名不能为空!")]
        public string username
        { get; set; }

        /// <summary>
        /// 密码
        /// </summary>
       [displayname("密码")]
        [required(errormessage="密码不能为空")]
        [stringlength(10, errormessage = "密码长度不能小于5位",minimumlength=5)]
        public string userpwd
        {
            get;
            set;
        }

       [displayname("确认密码")]
       [required(errormessage="确认密码不能为空!")]
       [stringlength(10, errormessage = "确认密码长度不能小于5位",minimumlength=5)]
      public string confirpwd
      {
          get;
          set;
      }
        /// <summary>
        /// 用户邮箱
        /// </summary>
        [displayname("邮箱")]
        //[datatype(datatype.emailaddress)]
        [regularexpression(@"^\w+((-\w+)|(\.\w+))*\@[a-za-z0-9]+((\.|-)[a-za-z0-9]+)*\.[a-za-z0-9]+$", errormessage = "电子邮件格式错误")]
        public string email
        {
            get;
            set;
        }

   
    }

  
    /// <summary>
    /// 此自定义类用于验证密码和确认密码必须一致
    /// </summary>
    [attributeusage(attributetargets.class, allowmultiple = true, inherited = true)]
    public class pwdmatch :validationattribute
    {

        private object _typeid = new object();
        public string pwd { get; set; }//密码
        public string confirmpwd { get; set; }//确认密码


        public pwdmatch(string pwd, string confirmpwd)
            : base()
        {
            pwd = pwd;
            confirmpwd = confirmpwd;
        }

        /// <summary>
        /// 返回错误的提示信息
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public override string formaterrormessage(string name)
        {
            return errormessage;
        }

        /// <summary>
        /// 重写typeid
        /// </summary>
        public override object typeid
        {
            get
            {
                return _typeid;
            }
        }

       /// <summary>
       /// 判断是否想到
       /// </summary>
        /// <param name="value">value的值实际上是model提交的model类</param>
       /// <returns></returns>
        public override bool isvalid(object value)
        {
            propertydescriptorcollection properties = typedescriptor.getproperties(value);
            object originalvalue = properties.find(pwd, true ).getvalue(value);//获取密码
            object confirmvalue = properties.find(confirmpwd, true).getvalue(value);//获取确认密码的值
            return object.equals(originalvalue, confirmvalue);

        }
    }
 

 

 

前台页面代码

[html] <%@ page language="c#" inherits="system.web.m.viewpage<mvclogin.models.registermodel>" %> 
 
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> 
 
<html xmlns="" > 
<head runat="server"> 
    <title>注册页面</title> 
    <script type="text/javascript" src="../../scripts/jquery-1.4.1-vsdoc.js"></script> 
    <script type="text/javascript" src="../../scripts/jquery.validate.js"></script> 
    <script type="text/javascript"> 
//        $().ready(function () { 
//            $("#form1").validate( 
//        { 
//            rules: 
//           { 
//               username: 
//              { 
//                  required: true 
//              }, 
//               userpwd: 
//               { 
//                   required: true, 
//                   minlength: 6 
//               }, 
//               confirpwd: 
//               { 
//                   required: true, 
//                   minlength: 6, 
//                   equalto: "#userpwd" 
 
//               }, 
//               email: 
//               { 
//                   email: true 
//               } 
 
//           }, 
//            messages: 
//           { 
//               username: 
//              { 
//                  required: "<span style='color:red'>用户名不能为空! </span>" 
//              }, 
 
//               userpwd: 
//              { 
//                  required: "<span style='color:red'>密码不能为空!</span>", 
//                  minlength: jquery.format("<span style='color:red'>密码长度不能小于{0}个字符!</span>") 
//              }, 
//               confirpwd: 
//               { 
//                   required: "<span style='color:red'>确认密码不能为空!<span>", 
//                   minlength: jquery.format("确认密码长度不能小于{0}个字符!"), 
//                   equalto: "<span style='color:red'>两次输入密码不一致!</span>" 
 
//               }, 
//               email: 
//               { 
//                   email: "<span style='color:red'>邮箱输入格式不正确!</span>" 
//               } 
//           }, 
//            onkeyup: false 
//        }); 
 
//        }); 
    </script> 
</head> 
<body> 
    <p> 
    <br /> 
 
    <p style="font-size:12px;color:red"> 
 
    <%if (viewdata["msg"] != null) 
      {%> 
    <%:viewdata["msg"]%> 
    <%} %> 
    </p> 
    <br /> 
    <p> 
      <%:html.validationsummary(true,"用户创建失败!") %> 
    </p> 
    <%html.beginform("register", "user", formmethod.post, new  { name="form1",id="form1"}) ; %> 
 
  
        <table> 
           <tr> 
             <td><%: html.labelfor(m => m.username) %></td> 
             <td>  <%: html.textboxfor(m => m.username) %></td> 
             <td><%:html.validationmessagefor(m=>m.username) %></td> 
           </tr> 
 
              <tr> 
             <td> <%: html.labelfor(m => m.userpwd) %></td> 
             <td>   <%: html.passwordfor(m => m.userpwd) %></td> 
              <td><%:html.validationmessagefor(m=>m.userpwd) %></td> 
           </tr> 
 
              <tr> 
             <td> <%: html.labelfor(m => m.confirpwd) %></td> 
             <td> <%: html.passwordfor(m => m.confirpwd)%></td> 
              <td><%:html.validationmessagefor(m=>m.confirpwd) %></td> 
           </tr> 
 
              <tr> 
             <td>    <%: html.labelfor(m => m.email) %></td> 
             <td>  <%: html.textboxfor(m => m.email) %></td> 
              <td><%:html.validationmessagefor(m=>m.email) %></td> 
           </tr> 
 
              <tr> 
             <td> <input type="submit" value="提交" /></td> 
             <td></td> 
              <td></td> 
           </tr> 
 
 
        </table> 
 
 
 
    <%html.endform(); %> 
     
    </p> 
</body> 
</html> 
<%@ page language="c#" inherits="system.web.mvc.viewpage<mvclogin.models.registermodel>" %>

<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">

<html xmlns="" >
<head runat="server">
    <title>注册页面</title>
    <script type="text/javascript" src="../../scripts/jquery-1.4.1-vsdoc.js"></script>
    <script type="text/javascript" src="../../scripts/jquery.validate.js"></script>
    <script type="text/javascript">
//        $().ready(function () {
//            $("#form1").validate(
//        {
//            rules:
//           {
//               username:
//              {
//                  required: true
//              },
//               userpwd:
//               {
//                   required: true,
//                   minlength: 6
//               },
//               confirpwd:
//               {
//                   required: true,
//                   minlength: 6,
//                   equalto: "#userpwd"

//               },
//               email:
//               {
//                   email: true
//               }

//           },
//            messages:
//           {
//               username:
//              {
//                  required: "<span style='color:red'>用户名不能为空! </span>"
//              },

//               userpwd:
//              {
//                  required: "<span style='color:red'>密码不能为空!</span>",
//                  minlength: jquery.format("<span style='color:red'>密码长度不能小于{0}个字符!</span>")
//              },
//               confirpwd:
//               {
//                   required: "<span style='color:red'>确认密码不能为空!<span>",
//                   minlength: jquery.format("确认密码长度不能小于{0}个字符!"),
//                   equalto: "<span style='color:red'>两次输入密码不一致!</span>"

//               },
//               email:
//               {
//                   email: "<span style='color:red'>邮箱输入格式不正确!</span>"
//               }
//           },
//            onkeyup: false
//        });

//        });
    </script>
</head>
<body>
    <p>
    <br />

    <p style="font-size:12px;color:red">

    <%if (viewdata["msg"] != null)
      {%>
    <%:viewdata["msg"]%>
    <%} %>
    </p>
    <br />
    <p>
      <%:html.validationsummary(true,"用户创建失败!") %>
    </p>
    <%html.beginform("register", "user", formmethod.post, new  { name="form1",id="form1"}) ; %>

 
        <table>
           <tr>
             <td><%: html.labelfor(m => m.username) %></td>
             <td>  <%: html.textboxfor(m => m.username) %></td>
             <td><%:html.validationmessagefor(m=>m.username) %></td>
           </tr>

              <tr>
             <td> <%: html.labelfor(m => m.userpwd) %></td>
             <td>   <%: html.passwordfor(m => m.userpwd) %></td>
              <td><%:html.validationmessagefor(m=>m.userpwd) %></td>
           </tr>

              <tr>
             <td> <%: html.labelfor(m => m.confirpwd) %></td>
             <td> <%: html.passwordfor(m => m.confirpwd)%></td>
              <td><%:html.validationmessagefor(m=>m.confirpwd) %></td>
           </tr>

              <tr>
             <td>    <%: html.labelfor(m => m.email) %></td>
             <td>  <%: html.textboxfor(m => m.email) %></td>
              <td><%:html.validationmessagefor(m=>m.email) %></td>
           </tr>

              <tr>
             <td> <input type="submit" value="提交" /></td>
             <td></td>
              <td></td>
           </tr>


        </table>

 

    <%html.endform(); %>
   
    </p>
</body>
</html>
 

 

  controller代码

  

[csharp] /// <summary>  
    /// 注册提交  
    /// </summary>  
    /// <param name="model"></param>  
    /// <returns></returns>  
    [httppost] 
    public actionresult register(models.registermodel model) 
    { 
        if (modelstate.isvalid) 
        { 
            //验证通过  
            bool result = false; 
            if (!new models.sqlhelper().existuser(model)) 
            { 
                result = new models.sqlhelper().adduser(model); 
            } 
 
            if (result) 
            { 
                //添加成功转向主页  
                formsservice.signin(model.username, false); 
                return redirecttoaction("index"); 
            } 
            else 
            { 
                //返回注册页面  
                viewdata["msg"] = "添加用户失败"; 
                return view(model); 
            } 
 
        } 
        else 
        { 
            //验证不通过  
            //返回注册页面  
            viewdata["msg"] = "添加用户失败"; 
            return view(model); 
        } 
    } 
    /// <summary>
        /// 注册提交
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [httppost]
        public actionresult register(models.registermodel model)
        {
            if (modelstate.isvalid)
            {
                //验证通过
                bool result = false;
                if (!new models.sqlhelper().existuser(model))
                {
                    result = new models.sqlhelper().adduser(model);
                }

                if (result)
                {
                    //添加成功转向主页
                    formsservice.signin(model.username, false);
                    return redirecttoaction("index");
                }
                else
                {
                    //返回注册页面
                    viewdata["msg"] = "添加用户失败";
                    return view(model);
                }

            }
            else
            {
                //验证不通过
                //返回注册页面
                viewdata["msg"] = "添加用户失败";
                return view(model);
            }
        }

 

demo下载:
 

 

 

摘自 奶酪专栏