MVC :: How And When Custom Model Validator Is Used
Apr 29, 2010
I am trying to understand a little more about implementing a custom model validator. I have implemented a custom model validator (derived from DataAnnotationsModelValidator<T>) for my custom validation attribute in order to do validation on the client side as well. There is not much documented about DataAnnotationsModelValidator. Besides, implementing client-side validation when is it a good idea or needed to implement a custom model validator for a custom attribute?
A separate question - in trying to understand how and when a custom model validator is used by the framework I noticed that my custom validator is always created with the context (2nd parameter in DataAnnotationsModelValidator<T>'s constructor) being a ViewContext, although it is declared as ControllerContext. Will a validator ever be created with something else than a ViewContext, and if so, when?
I created my custom validator in one project, something like that:
[Code]....
he composite control in another project. I added a reference of the custom validator project to the composite control project. I have a textbox in a composite control and I would like to validate this textbox by the composite control I created. But how can I do that? How can I create the custom validator instance that is linked to the custom validator I created?
I have a validator callout extender that works, it shows the callout box. But, it does a postback. It didn't do a post back the first time I clicked the button but it did for subsequent times. I read on the AJAX site that a custom validator must be used with this for it to work. I'm currently using this with a required field and regular expression validator. It works, the callout appears, but it doesn't work every time with out the post back.I posted this to see if there is a way to get this to work with a required field and regular expression validator, with out using a custom validator. I'm using the newest release of the toolkit, so I thought the documentation may be old, since the callout is appearing.
I've been trying to get a custom validator component working that ensures at least one checkbox from a checkboxlist has been checked. I've been used some code I found on dotnetjunkies.com but the client-side validation didn't work. I've been attempting to modify it to get the client-side javascript validation to work with no luck. Basically, I compile the below code into a DLL and add it to my bin folder.
What I'm trying to do is rather basic, but I might have my facts mixed up. I have a details page that has a custom class as it's Model. The custom class uses 2 custom objects with yet another custom object a property of one of the 2. The details page outputs a fair amount of information, but allows the user to post a comment. When the user clicks the post button, the page gets posted to a Details action that looks something like this:
[AcceptVerbs(HttpVerbs.Post)] public ActionResult Details(VideoDetailModel vidAndComment) { ....} [Code]....
The only fields on the form that is posted are CommentText and VideoId. Here is what the VideoDetailModel looks like.
public class VideoDetailModel { public VideoDetailModel() { [Code].... I suppose if I added more form fields for the properties I need, they would get posted, but I only need 1 form entry field for the CommentText. If I could get the same Model objects value that were sent to the page to post with the page, it looks like the solution is rather simple. I think using the RenderPartial in the middle of a form is problematic somehow to how the form gets written in html. I can't really put my finger on why things went bonkers, but if I do my RenderPartials before my form and then begin my form with the text entry field and the hidden VideoId, the default ModelBinder works just fine. I was beginning the form, writing the hidden VideoId, rendering several partial views, create my CommentText field, and then closed the form out. The CommentText field would get bound just fine. The hidden VideoId would not. Maybe I missed a rule somewhere about using RenderPartial.
For completeness, the partial view I was rendering took a Comment object and just wrote out it's CommentText data. Several of these objects would exist for a single Video object. All of this data was in a custom type and passed into the View (the main view) as it's Model. This partial view did not have a form and did not have any data entry fields.
When I first heard about ASP.NET MVC, I was thinking that would mean applications with three parts: model, view, and controller.
Then I read NerdDinner and learned the ways of repositories and view-models. Next, I read this tutorial and soon became sold on the virtues of a service layer. Finally, I read the Fluent Validation documentation, and I'll be darned if I didn't end up writing a bunch of validators.
Tonight, I took a step back and thought about what had become of my project. It seems to have become the victim of the design pattern equivalent of "feature creep". Somehow I'd gone from Model-View-Controller to Model-Repository-Service-Validator-View-ViewModel-Controller. You want loosely coupled and DRY? We got your loosely coupled and DRY right here! But I'm wondering if this could be a case of too much of a good thing.
Am I right to be concerned? Or is this actually not as crazy as it sounds? On one hand, it seems crazy to have so many layers. On the other hand, every layer has a clearly defined purpose that makes sense to me. Have your MVC applications turned into MRSVVVMC apps too? If not, what do they look like? Where's that right balance?
i am just having a play with HtmlHelpers in MVC, very useful stuff and now i am trying to create one for dropdowns based on passing in a model ( any ) what the property is for the value and same for text.
Does anybody know of a way to set the width of a custom validtor so that the error message text will wrap if it exceeds the specified width? I have a user control that contains a custom validator which the containing page can set the error message on based on specific validation results. he user control sits within a table cell in a page. If the message is very long it simply prints the entire message on a single line ignoring any column widths that are set. I have tried setting the width property on the custom validator itself to no avail.
I have two buttons on my page, the first page is View Button and the second is Update Button. View button display's member's personal profile. If I click on the view button, my custom validator automatically trigger, meaning, it automatically displays the error message. Whereas, the custom validator must trigger if I click on the Update button. How am be able to deal with this kind of problem.
I have a custom validator, which I have set a property for, and I can access this validator from my MVC controller method. However, when I run the code, I am not seeing the error message on the page. My code in the controller method looks like this:
If (!bool) { this.view.customValidator.IsValid = false; this.view.customValidator.Visible = true; }
I am using Customvalidator control . I am giving client side validation function in it. On running it is giving error as: ValidationStream is not defined.
I have two custom validators that are in the same validation group. This validation group is launched by one button. My question is, in what order will the custom validators fire in? It appears that the validator that is placed earlier in the aspx page fires first, but I don't want to rely solely on this.
I have quite a few text area's on my page and am wanting to limit the number of characters for each one. However each one should be able to have its own maxlength (i.e. one could be 20 characters and the other could be 100 characters). My validation on the page is all done using custom validation as the built in validation of .NET is not extensible enough for me to display my validation errors how I want to display them. So this is what im wanting to do:
Make a custom validatorPass a MaxLength value from the custom validator into the javascript function, this value must also be accessible from the code behindI can then run client side and server side validation on each textbox control. The problem I am having is passing a MaxLength value to client side script and to server side. Is there a property on custom validators which I can use to pass values around? For instance in Javascript I would want the value of the MaxLength and also the id of the Div which will show the characters remaining, and server side I would need to know the MaxLength. I have done lots of research on this and cannot seem to find an answer.
I have a form with textbox for name and two dropdownlist for month and years. Textbox has Requiredfieldvalidator and the dropdowns has got ustomvalidator.Initially when i dont enter anything in the text box and leave the dropdowns with default "MM" for month and "YYYY" for year i get error message in the validation summary at top and asterisk next to the textbox and dropdowns. Once i enter some text in the textbox and focus is away from textbox the asterisk disappears but even though i hav selected a valid month and year the asterisk next to the dropdowns is not disappearing. Same problem with the radio buttons.
I have the following validation which is working fine for the rest of my fields, but trying to get a custom validator to work as part of the validation summary for a checkbox but no joy.
This is what I have at the moment
<script language="javascript" type="text/javascript"> function ValidateTandCs(source, args) { args.IsValid = document.getElementById('<%= optIn.ClientID %>').checked; } </script> <asp:ValidationSummary CssClass="highlight" id="ValidationSummary1" HeaderText="<p>Please amend these errors below to continue with your application.</p>" Runat="server" /> <asp:CheckBox id="optIn" runat="server"></asp:CheckBox> I agree to the terms and conditions of this site and I wish to Opt In for registration. <asp:CustomValidator ID="valTandCs" ClientValidationFunction="ValidateTandCs" ValidationGroup="ValidationSummary1" runat="server" ErrorMessage="Please accept Terms and Conditions before submitting."> </asp:CustomValidator>
But when I click submit I only see the error messages for my other fields and nothing for this checkbox..
How to compare tow date in format using custom validator and else. I have java script function like as. I want to call this function by using custom validator as
< </ asp:CustomValidator id="CustomValidator2" runat="server" ControlToValidate = "tbMyDate1" EnableClientScript="True" Display="Static" ClientValidationFunction="Compare" SetFocusOnError="True" >asp:CustomValidator> function { document.getElementById( Compare()"lblrefdate").innerText="";var m_names = new Array( "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"); var { { dispMM=i+1; } } dispdate=document.getElementById("tbMyDate");var dispDD=dispdate .value.split("-")[0];var s1=dispdate.value.split("-")[1];var dispMM;var i=0;for(i=0;i<=m_names .length ;i++)if(m_names [i]==s1) var { { refMM=j+1; } } dispYY=dispdate .value.split("-")[2];var refdate=document.getElementById("tbMyDate1");var refDD=refdate.value.split("-")[0];var s2=refdate.value.split("-")[1];var refMM;var j=0;for(j=0;j<m_names .length ;j++)if(m_names[j]==s2)var refYY=refdate.value.split("-")[2]; if { document.getElementById( } (isNaN (refYY))"lblrefdate").innerText=""; else { { { { { document.getElementById( } if(refYY<=dispYY)if(refMM <=dispMM )if(refMM==dispMM)if(refDD <=dispDD )"lblrefdate").innerText="";else { document.getElementById( } } } "lblrefdate").innerText="Ref Date can Not Be Grater then Disp Date";else { document.getElementById( } } "lblrefdate").innerText="Ref Date can Not Be Grater then Disp Date";else document.getElementById( { } } } "lblrefdate").innerText="Ref Date can Not Be Grater then Disp Date";
I am working on a custom form field validator, it seems like the custom validator is working by not allowing it to continue to the next page, but it doesn't update the Validation Summary nor does it display the asterisk and the labels that i've made visable. I also have other validators like RequiredFieldValidator on the same field. My ValidationGroup is set, as is the Text and IsValid. I even wrote and set a dummy client side validation method in javascript as some workarounds suggests.
I have a UserControl which contains a TextBox and a CustomValidator. I would like to set the CustomValidator.ServerValidate to a method in the page that contains the UserControl I found this code which will allow me to dynamically set the custom validators validation function: cusvCustom.ServerValidate += new System.Web.UI.WebControls.ServerValidateEventHandler(MethodName);
The problem is that a string value won't work there. It needs to be a reference to the method. Is it possible to use reflection (or some other method) to get a valid reference to the parent controls method using only the string name of it? The reason I want to use the string value of the method name is so I can place the control on the page thusly: <uc1:TextBoxField ID="tbUserName" runat="server" CustomValidationMethod="ValidateUserName" />
WebUserControl.ascx <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl.ascx.cs" Inherits="WebApplication1.WebUserControl" %> <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Custom Validation Failed" OnServerValidate="CustomValidator1_ServerValidate" /> <asp:TextBox ID="TextBox1" runat="server" /> <asp:Button ID="Button1" runat="server" Text="Submit" CausesValidation="true" /> WebUsecControl.ascx.cs using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication1 { public partial class WebUserControl : System.Web.UI.UserControl { public ServerValidateEventHandler Validating; protected void CustomValidator1_ServerValidate(object sender, ServerValidateEventArgs e) { if (Validating != null) Validating(sender, e); } } } TestPage.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TestPage.aspx.cs" Inherits="WebApplication1.TestPage" %> <%@ Register Src="~/WebUserControl.ascx" TagName="WebUserControl" TagPrefix="uc1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <uc1:WebUserControl ID="WebUserControl1" runat="server" OnValidating="WebUserControl1_Validating" /> </div> </form> </body> </html> TestPage.aspx.cs using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication1 { public partial class TestPage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //WebUserControl1.Validating += WebUserControl1_Validating; } protected void WebUserControl1_Validating(Object sender, ServerValidateEventArgs e) { e.IsValid = false; } } }
I did some research and I found Type.GetMethod and MethodInfo but I can't get them to work. Primarily because I don't know the type of the parent control and can't figure out how to get it. EDIT: My code for matt-dot-net. As you can see it's almost an exact duplicate of your code. For whatever reason it does not work for me as I have it here. When I click on the button the page reloads and is the same. When I un-comment the one line though and click the button then I see the error message.
how to implement WCF username authentication with a custom validator in both client side and server side. I am trying this since last 2 days. but no result.
I have a requirement that one of multiple fields is required. Using custom validator the even fires, false is returned, but no error message is display and the form validates. What am I missing? I have tried with and without ValidationSummary.
I am using C# for ASP .NET 2.0. On my web form I have a TextBox that I want to let the end-user type inside of. The rules are as such: They should only be allowed to type numbers and a decimal. No negative numbers allowed. The number has to range from 0.00 to 24.00 - for hours - and can only allow for quarter hours - example: 0.00, 0.25, 0.50, 0.75, 1.00, 1.25, etc. Do I need a custom validator for this? If so, I do I check to see that the number is valid?