rahebirizah
rahebirizah

Reputation: 115

Enterprise Library 6 validation config file

i'm trying to learn EnterpriseLibraryValidatoin. when i configure TypeValidation to validate a class through config file it does not pick up. but when i add Data Annotations it Validates Correctly I don't know if i'm leaving something out

any help please

validation config file

<validation>
<type name="ValidationBlockExample.Person" defaultRuleset="ValidimiFushave"
    assemblyName="ValidationBlockExample, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
    <ruleset name="ValidimiFushave">
        <fields>
            <field name="LastName">
                <validator type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.NotNullValidator, Microsoft.Practices.EnterpriseLibrary.Validation, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                    messageTemplate="Last Name Required!" name="Not Null Validator" />
            </field>
        </fields>
    </ruleset>
</type>

code to validate

        ValidationFactory.SetDefaultConfigurationValidatorFactory(new SystemConfigurationSource(false));

        Validator<Person> pValidator = ValidationFactory.CreateValidator<Person>();

        Person prsn = new Person();
        prsn.FirstName = "Name";
        ////prsn.LastName = "Haz";
        prsn.Age = 31;

        ValidationResults valResults = pValidator.Validate(prsn);


        if (!valResults.IsValid)
        {
            foreach (var valResult in valResults)
            {
                Console.WriteLine(valResult.Message);

            }

        }
        else
            Console.WriteLine("Preson Validated !!!");

        Console.ReadLine();

the class to be validated

public class Person
{
    public string FirstName { get; set; }
    //[Required]
    public string LastName { get; set; }
    public int Age { get; set; }

}

Upvotes: 1

Views: 1504

Answers (2)

Uuuuuumm
Uuuuuumm

Reputation: 657

This answer is tailored for .net core 6:

First, you need to store whatever parameters you need in you config file.

appsettings.json

{
  "Account": {
    "PasswordMinLength": 8,
    "PasswordPattern": "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*#?&])[A-Za-z\\d@$!%*#?&]*$"
  }
}

Then you need to create a custom Validator attribute class:

(you can make this class directly in your ViewModel class if you want)

class MyPasswordValidater : ValidationAttribute
{
    private readonly int MinimumLength;
    private readonly string MatchPattern;
    private readonly string FieldName;
    public MyPasswordValidater(
        string configFilePath="appsettings.json",
        string fieldName="Password"
    ) : base() {
        using StreamReader r = new(configFilePath);
        string json = r.ReadToEnd();
        dynamic obj = ((dynamic)JsonConvert.DeserializeObject(json))["Account"];
        MinimumLength = (int)obj["PasswordMinLength"];
        MatchPattern = (string)obj["PasswordPattern"];
        FieldName = fieldName;

    }

    public override bool IsValid(object value)
    {
        if (value == null || value.ToString().Length == 0)
        {
            ErrorMessage = $"{FieldName} is required";
            return false;
        }
        if (value.ToString().Length < MinimumLength)
        {
            ErrorMessage = $"{FieldName} must be at least {MinimumLength} characters";
            return false;
        }
        if (!Regex.IsMatch(value.ToString(), MatchPattern))
        {
            ErrorMessage = $"{FieldName} does not meet requirements";
            return false;
        }
        return true;
    }
}

Notice in the constructor the value gets pulled from appsettings.json, where it is then stored until validation occurs.

The last step is giving the attribute to the field you want:

[MyPasswordValidater()]
public string Password { get; set; }

[MyPasswordValidater(fieldName: "Confirm Password")]
public string ConfirmPassword { get; set; }

Since, the constructor doesn't have any required parameters you don't need to pass anything to the validator, but you can change the field name displayed in the error messages

This will validate required, minimum length, and matching a regular expression (which I used to determine if the password has special characters and upper/lower case)

Upvotes: 0

Novox
Novox

Reputation: 804

Per Microsoft Enterprise Library 6 – Final Release, Release Notes

Validation Application Block

The ValidationFactory class no longer automatically builds its configuration from the configuration file. You must now invoke the SetDefaultConfigurationValidatorFactory method to load the configuration from the configuration file. This is a breaking change.

So, as has been suggested to me, do this:

ValidationFactory.SetDefaultConfigurationValidatorFactory(
new SystemConfigurationSource());

before you validate.

Upvotes: 3

Related Questions