.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

Help on Binding validation rules

Posted By:      Posted Date: September 03, 2010    Points: 0   Category :WPF
Dear all, I have the follwoing code snipet: <TextBox Validation.ErrorTemplate="{StaticResource validationTemplate}" Style="{StaticResource textBoxInError}" Grid.Column="1" Grid.Row="3"> <TextBox.Text> <Binding Path="CurrentPlayer.Email" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged"> <Binding.ValidationRules> <vrules:EmptyStringValidationRules /> </Binding.ValidationRules> </Binding> <TextBox.Text> </TextBox> </Border> <Button Margin="1" Foreground="Black" FontSize="25" Grid.Row="5" Grid.Column="1" HorizontalAlignment="Stretch" Command="{x:Static local:QuizzCommands.Start}" Content="{StaticResource Ok}" /> From teh sample above I have place only a single text box but in fact I have 4 text box which should not be empty before pressing the button So in an other hand the Button should not be enabled until all text box entrie are filled by user I have impleneted a validation rules which check if filed is empty as follow : class EmptyStringValidationRules:ValidationRule { public overri

View Complete Post

More Related Resource Links

firing Validation rules under One way binding Mode


Can Validation Rules fire When binding Mode is set to OneWay.?

If No : Is is Because the validation rules fire only when the source property changes and hence under oneway binding the source never changes and so the rules never fire.

Is there a workaround to Fire the validation rules Except invoking the explicitly.( Because i have triggered the save button to be enabled only when ther's no validation errors, So makin the user click and explicitly firing rules is not what i want.)



Input Validation: Enforcing Complex Business Data Rules with WPF


Windows Presentation Foundation has a rich data binding system that includes flexible support for business data validation. We take a look at implementing some complex data input validation scenarios that include customized data errors for users.

Brian Noyes

MSDN Magazine June 2010

Web Services: Extend the ASP.NET WebMethod Framework with Business Rules Validation


In an earlier article the authors showed how to build a custom WebMethods extension that provides XML Schema validation, a function that is lacking in ASP.NET. In the process they established a foundation for enforcing business rules during the deserialization of XML data. The technique, which is described in this article, uses declarative XPath assertions to test business rule compliance.In building this business rules validation engine, the authors integrate the validation descriptions into the WSDL file that is automatically generated by the WebMethod infrastructure. Finally, they demonstrate how to extend wsdl.exe, the tool that generates WebMethod proxy/server code from WSDL files, to make use of their extensions.

Aaron Skonnard and Dan Sullivan

MSDN Magazine August 2003

Binding of complex entity turns into validation error

consider classic example: Product and Category editing Product in dropdown Id of Category is selected - Category mapped as object with all fields empty except Id when submitting Product edit form - validation gives an error: "Category name is required" (I have Required attribute on Category Name property) How deal with such errors if I want to use built-in validation (if (!ModelState.IsValid))? Writing custom data binder which would fill all such id-only-objects with values from database comes to mind.upd: I did small research of mvc code and found out that validation happens before binding - so this solution would't work. Do you have any other solutions for this problem?

Which is the best approach for applying business rules and basic validation like data types?

Hi Everybody   Please suggest me the best approach for applying the business rules and data type validations .Here is my choices : 1)Sequential work flow 2)State machine work flow 3)Work flow rule engine 4)Rule engine without workflow Out of above choices ,which is the best approach? Please provide me the reasons or senarioes for which is the best approach for applying the business rules and also performancewise. My requirement is : After getting the reports ,need to apply the datatype validations like valid or invalid date ...etc to the reports .And stored into Database.In the next step,need to apply the business rules to that reports in such a way that data should be good quality. Thank you very much

Defining Validation rules with Data annotations - ???


I am having following problem:

Defined RegisterModel class - with some validation rules for creating new users, and this works fine.

Then I get this class, strip few properties and wanted to reuse it as UserInfo_Form_Model,   for editing user properites.

No changes, just deleted few items, renamed and reused in strongly typed View for editing.

And result of validation is: -

[DisplayName("Name")] works fine, showing correct

[StringLength(20, ErrorMessage = "xxxx...")] - not working, no message showed when suppose to be one

[Required(ErrorMessage = "xxxx.")] - not working, not showing messages when delete required values?

but  (ModelState.IsValid) is false when I checked it in controller (it had to be because required value is missing)?

Is it this only partially correct and how this can be?

Well this is a bit frustrating because it cant be simpler than this and I cant make this simple code reuse. :|

Quite a few gotchas I already found or I am coding completely wrong.

Problems with multiple validation rules



I've added some custom validation rules programatically like this:



            BindingOperations.GetBinding(txtTitulo, TextBox.TextProperty).ValidationRules.Clear();

            BindingOperations.GetBinding(txtTitulo, TextBox.TextProperty).ValidationRules.Add(new ReglaDatoRequerido(Idioma.RecursoIdiomaLocal(this, "msjErrorDatoRequerido")));

            BindingOperations.GetBinding(txtTitulo, TextBox.TextProperty).ValidationRules.Add(new ReglaRangoDatos(Idioma.RecursoIdiomaLocal(this, "msjErrorDatoRequerido"), 1, 5, false));

these are the rules:
public abstract class ReglaValidacionBase : ValidationRule
        /// <summary>
        /// Mensaje de error.
        /// </summary>
        public string MensajeError { get; set; }

   public class ReglaDatoRequerido : ReglaValidacionBase
        public ReglaDatoRequerido(st

MVC3 : Validation parameter names in unobtrusive client validation rules must start with a lowercase


I am migrating my application to MVC3 and getting this error message

Validation parameter names in unobtrusive client validation rules must start with a lowercase letter and consist of only lowercase letters or digits.

How can I ovoid it without going and modifying all my ViewModels

Tank you for your help 

Validation when adding a new item and no target to source binding has yet taken place


Using: WPF (.NET 4) with Entity Framework on a SQLCE database.

In my app, the user can edit existing employees and create new employees. The same UI control is used to add and edit. In the case of editing an Employee, the DataContext for the control is the Employee object of my Entity Framework context. It is updated through binding, and the SaveChanges method is called on my EF to update the database. In the case of adding and Employee, the DataContext is a new Employee object, which will gets added to the EF and then saved. Simple.

I've been trying to hook-up validation to the control. I'm using WPF's ValidationRule objects for each field binding as required. When the field loses focus (as is the default action for a target to source binding), the validation rules are checked, which can incur an error. I can then check for the presence of these errors before allowing the employee to be saved.

But when adding a new Employee, if I go ahead and push the Save button without doing anything else, no validation takes place, becasue the bindings have never attempted to update the source! It just throws an exception as expected.

What can I do? I have ideas which would probably work, but I thought I should post here first in case I am missing something obvious! Is there a standard way to deal with t

Binding WPF Controls to an Entity Data Model

In this interview, programming writer, McLean Schofield, demonstrates how to bind WPF controls to an entity data model, using Visual Studio 2010 Beta 1. You can also learn more in the topic: Walkthrough: Binding WPF Controls to an Entity Data Model.

Binding the multiple drop down boxes in GridView using JQuery in ASP.NET

Here is the code for binding the multiple drop down boxes in GridView using JQuery in ASP.NET

Binding WPF Controls to an Entity Data Model

In this interview, programming writer, McLean Schofield, demonstrates how to bind WPF controls to an entity data model, using Visual Studio 2010 Beta 1. You can also learn more in the topic: Walkthrough: Binding WPF Controls to an Entity Data Model.

WPF / Silverlight tutorial: Visibility property and binding

Visibility property is a very powerful and yet often overlooked property available in both WPF and Silverlight. It enables you to set Visibility of certain UIElement objects to different states like: Visible, Collapsed and Hidden (not supported by Silverlight). This tutorial shows you how to use it and how to bind to Visibility property

Binding an array to dropdown list


I have the following string which is a list of urls. How do I get this to work so the url shows for the selection and also is the value?      


allLinks = newAllLinks
        Me.DropDownList1.DataTextField = "Link"
        Me.DropDownList1.DataValueField = "LinkURL"
        Me.DropDownList1.Items.Insert(0, New ListItem(" - Select - ", 0))
        Me.DropDownList1.DataSource = allLinks


 ArgumentNullException: Value cannot be null.
Parameter name: container]
   System.Web.UI.DataBinder.GetPropertyValue(Object container, String propName) +121
   System.Web.UI.DataBinder.GetPropertyValue(Object container, String propName, String format) +8

Server side validation of Fileupload control not working



I've tried this method in my code behind to try and validate that the Fileupload control has a file or not. I get the error message the the event "Server Validate" cannot be found. Can anyone tell why? Thanks.

Public Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate

' Get file name

        Dim uploadAvatar As FileUpload = DirectCast(AdvertisementForm.FindControl("uploadAvatar"), FileUpload)

        Dim UploadFileName As String = uploadAvatar.PostedFile.FileName

        If UploadFileName = "" Then
            ' There is no file selected
            args.IsValid = False
            Dim Extension As String = UploadFileName.Substring(UploadFileName.L

Integer Validation



I need to make validation for Textbox to allow enter integer stated by 9 or 6 or 5 , and also maximum 8 digits , how to do that ?





Binding Nested Listviews in MVC ViewPage


I am a longtime .NET developer but for big applications and services.  This is my first asp.net project and I have chosen MVC.   I have a need for nesting a ListView within a ListView.  In this simple catalog app, I have EF 4 Entities that are Categories, SubCategories, ItemTypes, and Items.

My goal is to display a 5 column layout of SubCategories with their ItemTypes below them in a ViewPage.  I did just fine with it done out in C# as server directives such as:

    var subcats = Model.SubCategory.ToArray();
    var nrSubCats = subcats.Count();
    var rows = (nrSubCats/5) + (((nrSubCats % 5) > 0) ? 1 : 0);
    for (var row = 0; row < rows; row++)
    { %>
        <div style="width: 100%; float: left; clear: right;">
        var start = row * 5;
        for (var i = start; (i < start + 5) && (i < nrSubCats); i++)
        var subcat = subcats[i];
            <div style="float: left; clear: right; width: 20%; margin-left: 5;">
                <h2> <%:subcat.Name%></h2>
                    foreach (var its in subcat.ItemType)
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend