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

Top 5 Contributors of the Month
Post New Web Links

MVC Validation Pattern Question, Especially for Variable Length Lists and Conditional Validation

Posted By:      Posted Date: September 21, 2010    Points: 0   Category :ASP.Net

I've spent a lot of time exploring the various patterns of MVC validation. In particular, I am interesting in learning best-practice for validating a view which posts an enumerable collection back to the controller. One approach that is appealing involves posting the form via Ajax to check validation (http://jvance.com/blog/2010/02/20/MakingAnAjaxFormWithJQueryInASPdotNETMVC.xhtml). Obviously, the negative is that this is not true client-side validation since there is a "hidden" server round-trip, but the effect is comparable, and obviously client-side validation alone will never stand--server-side always needs to be done as well.

The CodePlex repository for this demo: http://mvcajaxvalidation.codeplex.com/SourceControl/list/changesets

The main reason I started heading this route is because in the course of writing lots of custom data annotation model validators (think "RequiredIf" or "RequiredWhenContains") it became very evident that the wiring to the client-side gets complicated. I was mostly able to pull it off using the custom validators' GetClientValidationRules() plus jQuery validator extensions (.addMethod('requiredif'...), ho

View Complete Post

More Related Resource Links

Conditional Validation



i have been looking for a way to conduct conditional validation for a web page i am developing and it seems like there isnt a real clear cut way to do this dynamically. from what i can tell a validation method could be developed in the aspx.cs file that is called to make sure the required fields are filled in for particular cases, but is there any other way? i was hoping to do it dynamically (as i mentioned before), does anyone have any examples i could look at?

here is what i am trying to accomplish:

There will be a drop down box, if a certain value is selected from that drop down box, another drop down box then becomes a required field. if any other value is selected then the other drop down box is only optional.

I also have another situation where i have a drop down box, when a certain value is selected, their must be input in the text and dropdown boxes next to it (it would be pretty cool to hid the boxes until needed but i am not sure how hard that would be). if any other value is selected from the drop down box, no input can be excepted in the other two fields.

Thanks for that help!

validation through variable

hii want to create a validation for text boxforsuch as there is a variale expthen decimal values + expegif exp=updthen validation shoud for like 123upd12.12updif exp=mgthen345mg34.222mgif exp=kgthen11kg45kgmeans there shoudl be numbers along with the values which exp hasthnks

AsyncFileUpload and form validation question


This is my first time using the AsyncFileUpload so please tell me if I'm missing something obvious.  I have it working in the sense that one can upload a file and I can save it to the correct place and all that stuff.

The implementation I am using it on is a form that sends an email, one that may or may not have an attachment.  The attachment isn't a required field, but other form fields are in fact required.

If one goes to the bottom of the form and uploads a file, without doing anything else, the file gets saved in my attachments folder on the web server.  However, it doesn't logically make sense to me that one should be able to do that without first filling out a valid form. It seems like what this is going to promote is a lot of files hanging around from those who already uploaded a file but didn't bother to fill out the rest of the form correctly.

There is an OnClientUploadStarted event, but that's too late.  It seems like there should be an OnClientBeforeUpload so form validation can take place prior to a file getting physically saved on the server.  Am I missing something?

So I guess what I could do is do server side form validation in the OnUploadedComplete event before calling the controls SaveAs method, is that really the only way to do it?  Where is the file "uploaded" to

conditional validation


I want to make either last name or first name required. Below is the code and it does not work as expected.
Once a RequiredFieldValidator is enabled by the Page_Load() method, there is no way to make it execute that method again to disable the RequiredFieldValidator. How can that be fixed?

Let's say after the first time the page loads, I click the Find button without entering any name.
That causes RequiredFieldValidator1 to be enabled by the Page_Load() method.
Now I enter first name and click Find; it does not execute Page_Load() and thus requires last name.
It should not require last name. How do you set RequiredFieldValidator's Enabled attribute when the server code is not executed?

Last Name: <asp:TextBox ID="LastName" runat="server"></asp:TextBox>
First Name: <asp:TextBox ID="FirstName" runat="server"></asp:TextBox>
<asp:Button ID="Button1" Text="Find" runat="server" OnClick="Button_Click" />


WPF POCO Validation Question


Hi all,

I am building a WPF 4 application with Prism and MVVM, I have some POCO to bind with different views in different modules. I would like to implement validation of user input.

After I have done tons of search I found all of the implmenetations are based on property changed and validation logic kicking off right away. And typical way is to leverage attributes under System.ComponentModel.DataAnnotations namespace and IDataErrorInfo interface.

My requirements are:

  • I don't want object to be validated until I click on some button. If I call Validator.TryValidateObject from my event handler, it does not seem that UI control can be notified with the errors.
  • I need different validation rules agaisnt same object in different modules/views. For example a field in module A is optional; but mandatory in module B.

Anybody has some good suggestion, articles to describe my requirements?



Welcome to help me with my open source project at http://code.google.com/p/batch-image-watermark-processor/

DateTime Validation in SSIS using conditional split



I am facing issue with null validation for DateTime. I have input csv file which contains DateTime field as Date datatype. In the destination database table, I am storing this field as datetime. I am using conditional split feature of SSIS package and try to validate this field before inserting into the database.

The value which is going into the db is "1899-12-30 00:00:00.000". I dont know why?

I have tried various expressions like ISNULL(DateTime), LEN(DTSTR, DateTime) == 0, ISNULL(DateTime) ? False : DateTime. Nothing is working.

Req is simple, if date is valid insert in db otherwise write is as bad data in error log file.

Can anyone provide suggestion on this.




Quick validation question...


I have a textbox called "tax rate" which I need to validate the input...

The only thing I need to ensure is that the value entered is a number (decimals ok of course).

eg. the input might be "8.75"

How do I write the validation expression for this please?



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 ?





VS 2010 HTML validation "in CSS" option - where the hell is it?


In VS 2008 there is a very useful feature of background HTML validation - it checks if CSS class name is valid i.e. it exists in one of the linked css files. But VS 2010 Express does not do that any more. And the relevant setting in Options->Text Editor->HTML->Validation->in CSS is not there. Ok, maybe they made it paid for option? VS 2010 Professional? Not there. Or maybe VS 2010 Ultimate? Not a trace.

1. am I blind?

2. they decided it is too convenient to use and removed it?

3. they will "introduce" it in SP1?

What is going on? That one thing made me move back to VS 2008 web developer.


User validation Issue in xlsx file



I am validating user from Login.xlsx file. It was working fine by validating email and password from that file. For testing i got new file same contents of file but added some more user names.

So after that when i validating the user i am getting the following error "Data type mismatch in criteria expression".

But when i replaced the new to old one it is working fine. The contens of both files are the same. So why this kind of error happened.


set messageTemplateResourceName from resource file in Validation appication block.



  I am using Validation application block in my project and want to set validation message from resource file, but not able to do that. I tried giving the path of resource file in messageTemplateResourceType and name of resource in messageTemplateResourceName. But it did not help as I only receive the message if I have set something in messageTemplate even after setting the resource file.

Here is my code:

<validator lowerBound="1" lowerBoundType="Inclusive" upperBound="250"
              upperBoundType="Inclusive" negated="false" messageTemplate=""
              messageTemplateResourceType="Asurion.jCare.Common.Resources.UIResources.PerilTypeAndDetailsSection, Asurion.jCare.Common.Resources, Version=, Culture=neutral, PublicKeyToken=null"
              tag="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.StringLengthValidator, Microsoft.Practices.Enterpris

Localize framework message from xml validation error


I need to validate an XML through XSD. I am using XMLReader (with XmlReaderSettings and 

Validation_EventHandler to do it). Depend on users preference, I would like to change the output message generated by  Validation_EventHandler in french or english.

Any idea on how to perform this?





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

Extreme ASP.NET: Model Validation & Metadata in ASP.NET MVC 2


Scott Allen shows how to improve your user input validation with new features coming out in ASP.NET MVC 2 that easily allow validation on both the client and server.

Scott Allen

MSDN Magazine March 2010

Data Points: Data Validation with Silverlight 3 and the DataForm


In this month's column, John Papa shows you how the DataForm control works and how it can be customized.  He presents in detail a sample application that uses several features to bind, navigate, edit and validate data using the DataForm.

John Papa

MSDN Magazine October 2009

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