Regular Expression Validator

Topics: General discussion, Validation Application Block
Oct 15, 2008 at 9:31 AM
Validate a string with email address regular expression if and only if the string is not empty.
If the string value is empty do not validate it.
How can I do this?
Oct 15, 2008 at 1:04 PM
Edited Oct 15, 2008 at 1:09 PM
Hi,

You can try this.

In the config.
1. Add a Validation Application Block
2. Add a new type (your class that has the email address)
3. Add a new Rule Set
4. Choose members(Select the email address property)
5. Add a Or Composite Validator
6. Add a Range Validator 
    LowerBound = 1
    LowerBoundType = Inclusive
    Negated = true
    UpperBoundType - Ignore
7. Add a RegEx validator
8. In the Pattern property of the regex, select the internet email address pattern


------ Sample Code

//Sample Class

 

public class Email
{
    public string EAdd { get; set; }
}

//Invoke

 

 

static void Main(string[] args)
{
    Email.
Email emailAdd = new Email.Email();
    emailAdd.EAdd =
string.Empty;
    ValidationResults res = Validation.Validate<Email.Email>(emailAdd, "Rule Set");
    
    if
(res.IsValid)
    {
        Console.WriteLine("Either a Valid email or nothing is supplied!");
    }
    else
    {
        Console.Write("Email is Invalid!");
    }
    Console.ReadLine();
}

 

 //Config file


<?xml version="1.0" encoding="utf-8"?>

<configuration>

  <configSections>

    <section name="validation" type="Microsoft.Practices.EnterpriseLibrary.Validation.Configuration.ValidationSettings, Microsoft.Practices.EnterpriseLibrary.Validation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />

    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />

  </configSections>

  <validation>

    <type assemblyName="Email, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"

      name="Email.Email">

      <ruleset name="Rule Set">

        <properties>

          <property name="EAdd">

            <validator messageTemplate="" messageTemplateResourceName=""

              messageTemplateResourceType="" tag="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.OrCompositeValidator, Microsoft.Practices.EnterpriseLibrary.Validation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

              name="Or Composite Validator">

              <validator lowerBound="1" lowerBoundType="Inclusive" upperBound=""

                upperBoundType="Ignore" negated="true" messageTemplate="" messageTemplateResourceName=""

                messageTemplateResourceType="" tag="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.RangeValidator, Microsoft.Practices.EnterpriseLibrary.Validation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

                name="Range Validator" />

              <validator pattern="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"

                options="None" patternResourceName="" patternResourceType=""

                messageTemplate="" messageTemplateResourceName="" messageTemplateResourceType=""

                tag="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.RegexValidator, Microsoft.Practices.EnterpriseLibrary.Validation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

                name="Regex Validator" />

            </validator>

          </property>

        </properties>

      </ruleset>

    </type>

  </validation>

</configuration>


 

Hope this Helps.



.Kratos

 



Oct 15, 2008 at 2:35 PM
Hello

This is half working.
if the property value is empty myvalidationresult.isvalid is true which is fine.
even if the property value is not empty say: zyx, myvalidationresult.isvalid is true, I think regular expression is not fired.
could you please help me here.

I wrote:
<property name="Email1">
            <validator messageTemplate=" " messageTemplateResourceName=""
              messageTemplateResourceType="" tag="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.OrCompositeValidator, Microsoft.Practices.EnterpriseLibrary.Validation, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
              name="Or Composite Validator" >
            <validator lowerBound="1" lowerBoundType="Inclusive" upperBound=""
              upperBoundType="Ignore" negated="false" messageTemplate="range"
              messageTemplateResourceName="" messageTemplateResourceType=""
              tag="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.RangeValidator, Microsoft.Practices.EnterpriseLibrary.Validation, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
              name="Range Validator" />
            <validator pattern="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
              options="None" patternResourceName="" patternResourceType=""
              messageTemplate="email" messageTemplateResourceName="" messageTemplateResourceType=""
              tag="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.RegexValidator, Microsoft.Practices.EnterpriseLibrary.Validation, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
              name="Regex Validator" />
              </validator>

          </property>

Oct 15, 2008 at 6:51 PM
I have the exact same problem, and I feel that an attribute IgnoreNullOrEmpty is exactly what is needed here.  I've seen the posts about adding the attribute in other threads, and it appears a lot of folks are after the same behaviour.   I got this to work with the example given above, but it is very non-intuitve to write logic this way.   This makes the code hard to read for someone that isn't familiar with this issue.  I don't see why IgnoreNullOrEmpty, doesn't solve this problem.  From what I see, you can't write your own validator to do this since you seem to use that attribute during validation to skip the validators if the value is null.  If we could write our own, please let us know.
Oct 16, 2008 at 4:05 AM
Hi, I tried Kratos' solution and when I enter zyx, the validation result is invalid which is the correct behavior.  However, if you entered a blank space, it would also be invalid.
An IgnoreNullOrEmpty attribute would indeed solve the problem but Entlib 4.0 doesn't have that feature yet.  And yes, I think you can't create a custom validator for applying the IgnoreNullOrEmpty logic if you're after skipping other validators if the value is null.  But you can try creating that validator and just use it in an OrCompositeValidator. That's a lot of work though compared to other workarounds you can apply.

What I did is use the IgnoreNulls attribute, a RegExValidator and added the logic of returning null in the property's get accessor whenever its value is null or empty.
Oct 17, 2008 at 1:13 PM
Hi

Still I am having problems with this.
Please help me here

I am unable to resolve this with null values.
Oct 17, 2008 at 3:45 PM
Could you post your code here?
Oct 20, 2008 at 9:12 AM
Hi


i wrote the same:
in the app.config:
<property name="Email1">
            <validator messageTemplate=" " messageTemplateResourceName=""
              messageTemplateResourceType="" tag="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.OrCompositeValidator, Microsoft.Practices.EnterpriseLibrary.Validation, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
              name="Or Composite Validator" >
            <validator lowerBound="1" lowerBoundType="Inclusive" upperBound=""
              upperBoundType="Ignore" negated="false" messageTemplate="range"
              messageTemplateResourceName="" messageTemplateResourceType=""
              tag="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.RangeValidator, Microsoft.Practices.EnterpriseLibrary.Validation, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
              name="Range Validator" />
            <validator pattern="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
              options="None" patternResourceName="" patternResourceType=""
              messageTemplate="email" messageTemplateResourceName="" messageTemplateResourceType=""
              tag="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.RegexValidator, Microsoft.Practices.EnterpriseLibrary.Validation, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
              name="Regex Validator" />
              </validator>
          </property>



Oct 20, 2008 at 11:25 AM
Well, that's half working right? I'd suggest you just try out the solution I made.  No need to configure anything the app.config, just add the [IgnoreNulls] and [RegexValidator] attribute to the Email1 property.  In the get accessor:

private string email1;

[IgnoreNulls]
[RegexValidator(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*")]
public string Email1
{
    get { if(!string.IsNullOrEmpty(email1.Trim()))
            {
                return email1;
            }
            return null;
    set { email1 = value;}
}



static void Main(string[] args)
{
    Email.
Email emailAdd = new Email.Email();
    emailAdd.Email1 =
string.Empty;
    ValidationResults res = Validation.Validate<Email.Email>(emailAdd);
    
    if
(res.IsValid)
    {
        Console.WriteLine("Either a Valid email or nothing is supplied!");
    }
    else
    {
        Console.Write("Email is Invalid!");
    }
    Console.ReadLine();
}

Oct 20, 2008 at 2:03 PM
thanks very much :)