.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

Custom validation attribute that compare 2 valaues

Posted By:      Posted Date: September 09, 2010    Points: 0   Category :ASP.Net
I want to create Custom validation attribute  that compare 2 valaues i wnat to get the two vlaue   in side the validator together sucha that i have check  2 conditions 1)if the values of the two fieds are 0 then no need to do any comparison else value 1 should be less than value 2 MVC2  

View Complete Post

More Related Resource Links

Custom Validation Attribute is not called by validation mechanism.

Hello everyone I have create custom validation attribute and assign it to class level validation. Unfortunately, it is not called. I try every way that it think it could be solve the problem. However, it take me for hours and I can't find the attribute is not called by validation mechanism.For illustrate you I put the following code.Attribute[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)] public sealed class BooleanDependencyAttribute : ValidationAttribute { private const string _defaultErrorMessage = "?????????{0}"; private readonly object _typeId = new object(); public string DependencyPropertyName { get; private set; } public string DependentPropertyName { get; private set; } public BooleanDependencyAttribute(string dependencyPropertyName, string dependentPropertyName) : base(_defaultErrorMessage) { DependencyPropertyName = dependencyPropertyName; DependentPropertyName = dependentPropertyName; } public override object TypeId { get { return _typeId; } } public override string FormatErrorMessage(string name) { return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,name); } public override bool

Rejected by custom validation error & ItemAdding



I believe this topic was discussed before in this forum, but I couldn't find it using the exact error I receive: "operation for file.doc was rejected by custom validation on the server"

When I try to add a new word document to my doc library, Word displays this error instead of my custom error message. I set properties.Cancel=true in ItemAdding of my EventHandler, because my validation fails. 

Is there any way to display user properties.ErrorMessage instead of this generic error message?


Validation(): Attribute 'Factory' is not a valid attribute of element 'ServiceHost'

Hi, I'm using REST WCF3.5. In my .svc file, the Factory attribute is giving me Warning in the Visual Studio Team Suite saying "Validation(): Attribute 'Factory' is not a valid attribute of element 'ServiceHost'." <%@ ServiceHost Language="C#" Debug="true" Service="RestService" CodeBehind="~/App_Code/RestService.cs" Factory="AppServiceHostFactory" %> using System; using System.ServiceModel; using System.ServiceModel.Activation; using Microsoft.ServiceModel.Web; class AppServiceHostFactory : ServiceHostFactory {  protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)  {   WebServiceHost2 host = new WebServiceHost2(serviceType, true, baseAddresses);                 // Add the basic authenticator interceptor   host.Interceptors.Add(new BasicAuthenticationInterceptor(    System.Web.Security.Membership.Provider, "foo"));   return host;  } } I've added the reference as well & Everything works fine but I was wondering why am I getting this warning?? Thanks!  

Access Model Validation inside Custom Model Binder.

Hello,Is it possible, inside a Custom Model Binder, to fire "something" that "says" the value is invalid so it gets handled by validation part?Basically, I am getting an exception when the value for the property is invalid.Thank You,Miguel

Compare Validation for the Title field of the list

Hi, I do have a field known as 'Title' in the list.My requirement is there should be not be any duplicate values i.e first time if i enter say 'test' in Title field it should save where as second time when i enter same text as 'test' it should show message as 'item already exists with the Title that you have entered'.Ofcourse i should do the compare validation over here but just let me know how to do this Thanks & Regards, Sudheer

custom model validation

 Hi all, I am trying to wrap my head around a practical real world scenario where the out-of-the-box model validation framework in MVC2 poses some challenges. Consider the following model classes:     public class Organization    {        public int ID { get; set; }         [Required(ErrorMessage = "Work Address is a required field.")]        [DisplayName("Work Address")]        public Address WorkAddress { get; set; }         [DisplayName("Home Address")]        public Address HomeAddress { get; set; }     }     public class Address    {        [DataType(DataType.Text)]        [DisplayName("Address 1")]        [StringLength(50)]        [Required(ErrorMessage = "Address Line 1 is a required field.")]        public string Address1 { get; set; }         [DataType(DataType.Text)] &n

A general validation attribute for checking uniqueness in a linq to sql data context

I've been programming asp.net for, oh, a couple of days now. Here's a question I can't even begin to figure out for myself. I hope it's obvious from the code what I want to accomplish, and I have, but it's not pretty. Furthermore I'd like to use it on whatever table, whatever field, i.e. check the uniqueness of a value against a table and field I specify, passing it all into the attribute constructor. public class UniqueEmailAttribute : ValidationAttribute{    public UniqueEmailAttribute()    {    }    public override Boolean IsValid(Object value)    {        //not pretty. todo: do away with this.        var db = new CoinDataContext();        int c = db.Emails.Count(e => e.Email1 == value.ToString());        return (Boolean) (c == 0);    }}

how to read a custom dynamic data meta data attribute in a field template

All --Please help.I need to know how to read a custom dynamic data meta data attribute in a field template.I know how to do it in a page template because I have a handle to the meta table on the page.However, I do not know how to get a handle to the meta column at run time in a field template.Can you help?Please advise.Thank you.-- Mark Kamoski

Custom Model Binder Attribute

Hello,I have the following custom model binder attribute: public class DateTimeAttribute : CustomModelBinderAttribute { public DateTimeAttribute(String date, String time) { _binder = new DateTimeModelBinder { Date = date, Time = time }; } // DateTimeAttribute public override IModelBinder GetBinder() { return _binder; } // GetBinder } // DateTimeAttributeHowever, when I use it as follows:[AcceptVerbs(HttpVerbs.Get), DateTime("Date", "Time")] public virtual ActionResult Create() { // ... }I get the following error:Attribute 'MyApp.DateTime' is not valid on this declaration type. It is only valid on 'class, struct, enum, interface, param' declarations.What am I missing?I am using MVC 3.Thanks,MiguelError 5 Attribute 'FlyOnDreams.Net.Mvc.DateTime' is not valid on this declaration type. It is only valid on 'class, struct, enum, interface, param' declarations. C:\Users\Miguel\Projects\Fly On Dreams Lab\Fly On Pages\Solution\Trunk\Source\FlyOnDreams.FlyOnPages.Presentation\Areas\FlyOnPages\Controllers\UserController.cs 46 46 FlyOnDreams.FlyOnPages.Presentation

Custom Authenticate Attribute with Constructor (Dependency) Injection

  I have a [BeastAuthenticate] attribute on my controller.  The following code works fine but I would like to use Contructor (Dependency) Injection with Unity.  The problem is that the attribute will run the contructor with no parameters.  Interfaces ITMSLogger and IADGroups are setup to use Dependency Injection with TMSLogger and ADGroups respectively.   The following code works fine but doesn't use dependency injection for class ADGroups. public class BeastAuthenticateAttribute : AuthorizeAttribute { private ITMSLogger logger = new TMSLogger(); public BeastAuthenticateAttribute() { ADGroups adGroups = new ADGroups(logger); Roles = adGroups.GetRolesWithGroup("BEAST"); } } I tried the following but I'm getting an error ("Object reference is required...") with "this (adGroups). public class BeastAuthenticateAttribute : AuthorizeAttribute { private ITMSLogger logger = new TMSLogger(); private IADGroups adGroups;// = new ADGroups(new TMSLogger()); public BeastAuthenticateAttribute() : this (adGroups) { // adGroups = new ADGroups(logger); // this(adGroups); } public BeastAuthenticateAttribute(IADGroups adGroups) { //ADGroups adGroups = new ADGroups(l

how should i use custom validation in asp.net....

1)plz help me in doing the custom validation in asp.net.... 2)i also use java script also in custom validation.....3)provide me some examples also......

Allow System.Enum and System.ValueType as parameter types in a custom attribute

This is a continuation from a Microsoft Connect posting: https://connect.microsoft.com/VisualStudio/feedback/details/507907/error-an-attribute-argument-must-be-a-constant-expression-etc-incorrectly-received-when-the-argument-is-of-type-enum I am replying to Karel Zikmund’s latest posting, dated 29/07/2010 at 12:57.   Thank you for your response Karel, but once again, I am afraid you are wrong: > > This is irrelevant: the same is true irrespective of whether the parameter type is System.Enum or System.Object. > It is actually relevant - Think how IL code for this code should look like: >    void MyMethod(System.Enum arg) { System.WriteLine(arg); } >    MyMethod(MyInt1Enum.One); >    Mymethod(MyInt4Enum.Two); I’ve looked at the generated IL. It looks exactly the same as it does if I change the parameter type to System.Object. This is also what I expected. What IL did you expect to be generated? > System.Object is passed by reference which is a fixed size (4 or 8 bytes on x86 or x64 arch respectively). Yes, and so is System.Enum (and System.ValueType). > Enums and value types are passed by value (unless they are boxed) and their size therefore has to be known at JIT time. Yes, but System.Enum and System.ValueType are both neither an enum type nor a value type — they are both reference types that

Validation is not working in Custom List Form using JavaScript ddwrt:GenFireServerEvent()

Hii am creating custom New form for a list using sharepoint designer. i have added the below button for sumbit<input name="Submit1" type="submit" value="Submit" onclick="javascript: {ddwrt:GenFireServerEvent('__commit;__redirect={http://myserver/Lists/VTest/AllItems.aspx}')}" />                <xsl:text xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime" ddwrt:nbsp-preserve="yes" disable-output-escaping="yes">&amp;nbsp;                                    </xsl:text><input name="Submit2" type="submit" value="Cancel" onclick="javascript: {ddwrt:GenFireServerEvent('__redirect={http://myserver/Lists/VTest/AllItems.aspx}')}" />the problem is the validation is not working properly. it submits the page without entering values for the required fields.particularly the validation is not working for DateFields.let me know what is the problem here. is it a Bug?muthu

client ip during custom user validation


There are a lot of similar questions on this forum but there is no exact one.

i try this

public class CustomUserValidator : UserNamePasswordValidator
   public override void Validate(string userName, string password)

OperationContext context = OperationContext.Current;
MessageProperties messageProperties = context.IncomingMessageProperties;
RemoteEndpointMessageProperty endpointProperty = messageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
return endpointProperty.Address;



but OperationContext.Current is null in current context ...

Could somebody help me ?

Compare Validation


Hi Guys

I want to compare TextBox2 (date) is NOT LESS THAN TextBox1 (date). And also i would like to compare TextBox1 (date) is greater than Todays Date.

I have tried the compare validator but for some odd reason it is not working, Take a look at my code below.

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="CompareD.aspx.vb" Inherits="CompareD" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

<!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">
    <form id="form1" runat="server">
    <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
From Date :- <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

    <!--This is the required field validator-->
    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="TextBox1" runat="se

jQuery Custom Invalid Validation



Is there a method in jQuery that I can customize an invalid validation myself instead of using jQuery plug-in validation?

For example, if the form is valid do this below.

if ($('form').valid()) {
    //do something

But if I wanted to have a cutomize invalid method I could do this below.


if (!x == y) {
     $('form').valid() = False; //Sad   

     alert('Form is not valid.');

Thank You,


Clientside custom validation for controls in Inserttemplate of listview



I have 2 linked controls in a Insertitem template of a listview, I use a customvalidator to validate them 
on serverside I use:

 oCB = (CheckBox)ListView1.InsertItem.FindControl("Member");

to find the chkBoxcontrol to validate against my textbox and that works

But now I want to do the same thing on clientside, how can I find my controls in a javascript validation function ?


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