Multi field validator using Enterprise Library - Validation Application block

There are number of built-in ASP.NET validation controls(RequiredFieldValidator, CompareValidator, CustomValidator and few more) exist. But there is no multi field validator. It is quite feasible to write custom validator to meet the requirement and there are third party controls available such as this one.

I was looking for a Required Field validator that checks all the controls(TextBoxes, Drop down lists and Listboxe controls) on the form and outputs appropriate message when atleast one of the controls is not used/selected. I want to stop the search if the end user has not entered any text in TextBox / selected Dropdownlist / List Box controls.

Validation Application block from enterprise library is catering more than what I was looking for. Above requirement is easily met with just few lines of code(shown below)I found it really interesting and easy to use Validation Application block from Enterprise Library as explained below.

Enterprise Library - Validation Application Block

Below custom validator class that can be in your App_Code folder or your desired location.

Step 1

Declare properties in a class with required Validation rules

//Required name spaces for validation block
using Microsoft.Practices.EnterpriseLibrary.Validation;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;

/// <summary>
/// Declare fields and properties with 
///desired validation rules
/// </summary>
public class EmployeeValidator 
{
//Private Members
private string FirstName = string.Empty;
private string LastName = string.Empty;
private string Country = string.Empty;

//Properties with validation rules
[StringLengthValidator(1, 10, MessageTemplate=
"Please enter your search criteria")]
public string _FirstName
{
get { return FirstName; }
set { FirstName = value; }
}
[StringLengthValidator(1, 10, MessageTemplate =
"Please enter your search criteria")]
public string _LastName
{
get { return LastName; }
set { LastName = value; }
}
[StringLengthValidator(1, 10, MessageTemplate =
"Please enter your search criteria")]
public string _Country
{
get { return Country; }
set { Country = value; }
}

}
Step 2

Implement your validation rules by creating an instance of your validation object and associating your properties with ASP.NET Controls input as shown below.

protected void btnSearch_Click(object sender, EventArgs e)
{
//Message lable
lblValidationMsg.Text = "";

//Create an instance of Custom validator class
EmployeeValidator Employee = new EmployeeValidator();
//Assign form controls text to your business object - properties
Employee._FirstName = txtFirstName.Text;
Employee._LastName = txtLastName.Text;
Employee._Country = ddlCountry.SelectedValue;

//Create an instance of Validator and associate
//to your objects
Validator<EmployeeValidator> validator = ValidationFactory.
CreateValidator<EmployeeValidator>();
ValidationResults results = validator.Validate(Employee);

// Check if valid
if (!results.IsValid)
{
if (results.Count < 3)
{
//your button_click event code goes here
}
else
{
// If not valid, loop through the ValidationResults
foreach (var result in results)
{
lblValidationMsg.Text = result.Message;
}
}
}
}

Above few lines of code do the rest for you. You are ready to take off!

References

9 Comments

  • Thank you for the steps to associate Enterprise library with my project. It's working now.

    I see in your code that you use the "validation factory" instead of a facade. I am not quite sure what a facade is and how to use one. But David Hayden's blog has some information that I haven't had a chance to read more details. I will read more on Monday. Could you please tell me why you choose one over the other if you know it?

    Regards,

    Annie

  • I was able to use the facade to find the input error and post the error message on the asp. But it does not stop the search to execute which in my case will load thousands of records when the user does not enter any search critieria. It feels just like what the client side javascript can do. Then what is the benefit of using Validation Block? How can I stop the execution of search? Is there a way to do this kind of validation on the client side and also stop the execution of the search if it's invalid?

    Thank you very much,

    Annie

  • Hi Annie

    Note that validation block is used in the above source code just to 'STOP' the NULL search and output relevant msg.

    As you notice minimum required number of characters are validated using 'StringLenghtValidator'(FirstName, LastName and Country).

    Let me know, your requirement. Are you trying to STOP null search or do you have any requirements?

    Thanks

  • To stop the Null search and display only the error messages is what I want. Meaning when the user does not enter any information and click "Search" button, it shoudl only display the error message and do NOT execute the query. Do I have to write code to stop the null search or it stops the execution of the query automatically when it detacts any error?

    Thank you,

    Annie

  • [quote name="annie2010"]Do I have to write code to stop the null search or it stops the execution of the query automatically when it detacts any error? [/quote]

    Yes, you need to write the code in btn_Click event as shown above.

    All you need to make sure is that you have same number of Validators in your class file as on your web form. In other words, same number of input controls(Text boxes or drop down lists etc).

    In the above demo i have used just 3 controls, thats why i have 3 properties in class file and checking this in button click event if (results.Count < 3)

    Let me know further...

  • My question here is: Did you write code to stop executing the query? Or when the system sees (!results.IsValid), it automatically stops execting the query?

    I guess I am a little confused. I assume when (!results.IsValid), the page should be set to invalid, then in my SqlDataSource_selecting method, I can use (!page.IsValid) to stop executing the query . But the page is still valid when (!results.IsValid). How do you stop the query from execting? Could you show me the code, Please? The code above does not show this part.

    Thank you,

    Annie

  • sukumarraju,

    It's working now. Really appreciate your help. It is such a nice topic to learn for custom validation especially with your guidance.

    Best regards,

    Annie

  • Nice post

  • And what about adding some more illustrations? I’m not trying to offend anyone, page is really great. Just as I know people acquire information much more effective if there are certain helpful images.

    Joahn Page

Comments have been disabled for this content.