如何使用ASP.NET编写完全自定义的验证器? [英] How can I write a completely custom validator using ASP.NET?

查看:51
本文介绍了如何使用ASP.NET编写完全自定义的验证器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不使用ASP.NET内置验证器控件的情况下编写用于文本输入的验证器?

我只想编写函数或类,并使用函数/类中的代码检查文本框的值.

我希望验证的各种输入包括:

  • 电话号码
  • 名字
  • 姓氏
  • 电子邮件地址
  • How can i write a validator for text input without using ASP.NET''s built-in validator controls?

    I wish to only write my function, or my class, and check the value of textboxes using code within my function/class.

    Various inputs that I hope to validate include:

    • telephone numbers
    • first names
    • family names
    • email addresses
    • 推荐答案

      如果愿意,您可以编写自己的javascript,甚至还有一个自定义验证器,为您提供了执行此操作的框架.
      You can write your own javascript if you want to, there''s even a custom validator that gives you a framework for doing it.


      如果您想编写自己的验证器,那么应​​该注意两件事

      1-客户端验证,将通过您的自定义javascript代码完成.

      2-服务器端验证,如果客户端验证失败(浏览器问题,客户端禁用JS),因为您不能完全依赖客户端验证,则需要这样做.在这种情况下,您需要检查Page.IsValid上的验证.


      要编写自定义验证器,您需要从BaseVlidator或任何现有的验证器类继承类,例如,为了进行比较,您可以使用System.Web.UI.WebControls命名空间中的BaseCompareValidator 类.

      要在服务器端检查验证,您需要覆盖
      If you want to write your own validator then you should take care of two things

      1- Client side validation that will be done by your custom javascript code.

      2- Server side validation, this is required if in case the client side validation fails (Browser Issue, JS is disabled at client side) as you can’t totally rely on client side validation. In this case you need to check the validation on Page.IsValid.


      To write you custom validator you need to inherit you class from BaseVlidator or any existing validator class like for comparision you can use BaseCompareValidator class present in the System.Web.UI.WebControls namespace.

      To check the validation at server side you need to overwrite the
      EvaluateIsValid()

      方法,在此方法中,您需要在服务器端检查验证,

      method, in this method you need to check you validation at server side,

      protected override bool EvaluateIsValid()
              {
                  //Check you server side logic here.
              } 



      对于客户端验证,您可以覆盖OnPreRender方法,在该方法中,您需要按以下方法注册客户端脚本.



      For client side validation you can override the OnPreRender method, where you need to register your client side script as following.

      protected override void OnPreRender(EventArgs e)
              {
      
                  base.OnPreRender(e);
                 
                  if (base.RenderUplevel)
                      Page.RegisterClientScriptBlock("ValidateJS", …….<removed client="" script="" here="">);
      }



      对于您要寻找的验证类型非常普遍,您可以在Google上轻松获得用于验证的正则表达式.



      For the validation types you are looking for are very common, and you can get the regular expressions for the validation on google easily.


      这篇关于如何使用ASP.NET编写完全自定义的验证器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆