ASP.NET:利用RegexStringValidator验证字符串格式

1)判断字符串是不是邮箱格式:设定邮箱的正则表达式为RegexStringValidator的参数,然后对需要验证的字符串进行验证就可以了,方法很简单:

    private bool EmailDetecton(string str)
    {
        string pattern = @"^[a-zA-Z\.\-_]+@([a-zA-Z\.\-_]+\.)+[a-zA-Z]{2,4}$";
        RegexStringValidator rsv = new RegexStringValidator(pattern);
        try
        {
            rsv.Validate(str.GetType());
            return true;
        }
        catch
        {
            return false;
        }
    }

    这个恰好是微软MSDN给出来的例子,登陆MSDN查看就行了,一目了然。或者在我这里看也可以,下面是代码。很简单,就是设定需要验证字符串的正则表达式,然后验证字符串是够满足就可以了。

using System;
using System.Configuration;
namespace Microsoft.Samples.AspNet.Validators
{
  class UsingRegexStringValidator
  {
    static void Main(string[] args)
    {
      // Display title.
      Console.WriteLine("ASP.NET Validators");
      Console.WriteLine();

      // Create RegexString and Validator.
      string testString = "someone@example.com";
      string regexString =
       @"^[a-zA-Z\.\-_]+@([a-zA-Z\.\-_]+\.)+[a-zA-Z]{2,4}$";
      RegexStringValidator myRegexValidator =
       new RegexStringValidator(regexString);

      // Determine if the object to validate can be validated.
      Console.WriteLine("CanValidate: {0}",
        myRegexValidator.CanValidate(testString.GetType()));

      try
      {
        // Attempt validation.
        myRegexValidator.Validate(testString);
        Console.WriteLine("Validated.");
      }
      catch (ArgumentException e)
      {
        // Validation failed.
        Console.WriteLine("Error: {0}", e.Message.ToString());
      }

      // Display and wait
      Console.ReadLine();
    }
  }
}

posted @ 2013-03-07 16:21  Patrick005  阅读(538)  评论(0编辑  收藏  举报