Search Results

Search found 17503 results on 701 pages for 'bean validation model'.

Page 4/701 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • How to dynamically set validation messages on properties with a class validation attribute

    - by Dan
    I'm writing Validation attribute that sits on the class but inspects the properties of the class. I want it to set a validation message on each of the properties it finds to be invalid. How do I do this? This is what I have got so far: [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class LinkedFieldValidationAttribute : ValidationAttribute { private readonly string[] _properiesToValidate; public LinkedFieldValidationAttribute(params string[] properiesToValidate) { _properiesToValidate = properiesToValidate; } public override bool IsValid(object value) { PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value); foreach (var propertyName in _properiesToValidate) { var propertyValue = properties.Find(propertyName, false).GetValue(value); //if value is invalid add message from base } //return validity } }

    Read the article

  • Constructor parameter validation in C# - Best practices

    - by MPelletier
    What is the best practice for constructor parameter validation? Suppose a simple bit of C#: public class MyClass { public MyClass(string text) { if (String.IsNullOrEmpty(text)) throw new ArgumentException("Text cannot be empty"); // continue with normal construction } } Would it be acceptable to throw an exception? The alternative I encountered was pre-validation, before instantiating: public class CallingClass { public MyClass MakeMyClass(string text) { if (String.IsNullOrEmpty(text)) { MessageBox.Show("Text cannot be empty"); return null; } else { return new MyClass(text); } } }

    Read the article

  • Validation Meta tag for Bing [closed]

    - by Yannis Dran
    Note of the author: I did my research before posting and the old "duplicate" generated over a year ago and things have changed since then. In addition, it was generic question but mine is targeting only ONE search engine machine: BING. FAQ is not clear about how should we deal with these, "duplicate" cases. The "duplicate" can be found here: Validation Meta tags for search engines Should I remove the validation meta tag for the Bing search engine after I validate the website?

    Read the article

  • Data Model Dissonance

    - by Tony Davis
    So often at the start of the development of database applications, there is a premature rush to the keyboard. Unless, before we get there, we’ve mapped out and agreed the three data models, the Conceptual, the Logical and the Physical, then the inevitable refactoring will dog development work. It pays to get the data models sorted out up-front, however ‘agile’ you profess to be. The hardest model to get right, the most misunderstood, and the one most neglected by the various modeling tools, is the conceptual data model, and yet it is critical to all that follows. The conceptual model distils what the business understands about itself, and the way it operates. It represents the business rules that govern the required data, its constraints and its properties. The conceptual model uses the terminology of the business and defines the most important entities and their inter-relationships. Don’t assume that the organization’s understanding of these business rules is consistent or accurate. Too often, one department has a subtly different understanding of what an entity means and what it stores, from another. If our conceptual data model fails to resolve such inconsistencies, it will reduce data quality. If we don’t collect and measure the raw data in a consistent way across the whole business, how can we hope to perform meaningful aggregation? The conceptual data model has more to do with business than technology, and as such, developers often regard it as a worthy but rather arcane ceremony like saluting the flag or only eating fish on Friday. However, the consequences of getting it wrong have a direct and painful impact on many aspects of the project. If you adopt a silo-based (a.k.a. Domain driven) approach to development), you are still likely to suffer by starting with an incomplete knowledge of the domain. Even when you have surmounted these problems so that the data entities accurately reflect the business domain that the application represents, there are likely to be dire consequences from abandoning the goal of a shared, enterprise-wide understanding of the business. In reading this, you may recall experiences of the consequence of getting the conceptual data model wrong. I believe that Phil Factor, for example, witnessed the abandonment of a multi-million dollar banking project due to an inadequate conceptual analysis of how the bank defined a ‘customer’. We’d love to hear of any examples you know of development projects poleaxed by errors in the conceptual data model. Cheers, Tony

    Read the article

  • Achieving decoupling in Model classes

    - by Guven
    I am trying to test-drive (or at least write unit tests) my Model classes but I noticed that my classes end up being too coupled. Since I can't break this coupling, writing unit tests is becoming harder and harder. To be more specific: Model Classes: These are the classes that hold the data in my application. They resemble pretty much the POJO (plain old Java objects), but they also have some methods. The application is not too big so I have around 15 model classes. Coupling: Just to give an example, think of a simple case of Order Header - Order Item. The header knows the item and the item knows the header (needs some information from the header for performing certain operations). Then, let's say there is the relationship between Order Item - Item Report. The item report needs the item as well. At this point, imagine writing tests for Item Report; you need have a Order Header to carry out the tests. This is a simple case with 3 classes; things get more complicated with more classes. I can come up with decoupled classes when I design algorithms, persistence layers, UI interactions, etc... but with model classes, I can't think of a way to separate them. They currently sit as one big chunk of classes that depend on each other. Here are some workarounds that I can think of: Data Generators: I have a package that generates sample data for my model classes. For example, the OrderHeaderGenerator class creates OrderHeaders with some basic data in it. I use the OrderHeaderGenerator from my ItemReport unit-tests so that I get an instance to OrderHeader class. The problem is these generators get complicated pretty fast and then I also need to test these generators; defeating the purpose a little bit. Interfaces instead of dependencies: I can come up with interfaces to get rid of the hard dependencies. For example, the OrderItem class would depend on the IOrderHeader interface. So, in my unit tests, I can easily mock the behaviour of an OrderHeader with a FakeOrderHeader class that implements the IOrderHeader interface. The problem with this approach is the complexity that the Model classes would end up having. Would you have other ideas on how to break this coupling in the model classes? Or, how to make it easier to unit-test the model classes?

    Read the article

  • javascript date validation

    - by Bharanikumar
    Assume in my text box user enter like 18-06-2010 , Validation RULE if date is greater then current date then program should through the validation error like , PELASE ENTER PAST OR CURRENT DATE, DONT CHOOSE FUTURE DATE , Thanks

    Read the article

  • Model binding & derived model classes

    - by Richard Ev
    Does ASP.NET MVC offer any simple way to get model binding to work when you have model classes that inherit from others? In my scenario I have a View that is strongly typed to List<Person>. I have a couple of classes that inherit from Person, namely PersonTypeOne and PersonTypeTwo. I have three strongly typed partial views with names that match these class names (and render form elements for the properties of their respective models). This means that in my main View I can have the following code: <% for(int i = 0; i < Model.Count; i++) { Html.RenderPartial(Model[i].GetType().Name, Model[i]); } %> This works well, apart from when the user submits the form the relevant controller action method just gets a List<Person>, rather than a list of Person, PersonTypeOne and PersonTypeTwo. This is pretty much as expected as the form submission doesn't contain enough information to tell the default model binder to create any instances of PersonTypeOne and PersonTypeTwo classes. So, is there any way to get such functionality from the default model binder?

    Read the article

  • The Interaction between Three-Tier Client/Server Model and Three-Tier Application Architecture Model

    The three-tier client/server model is a network architectural approach currently used in modern networking. This approach divides a network in to three distinct components. Three-Tier Client/Server Model Components Client Component Server Component Database Component The Client Component of the network typically represents any device on the network. A basic example of this would be computer or another network/web enabled devices that are connected to a network. Network clients request resources on the network, and are usually equipped with a user interface for the presentation of the data returned from the Server Component. This process is done through the use of various software clients, and example of this can be seen through the use of a web browser client. The web browser request information from the Server Component located on the network and then renders the results for the user to process. The Server Components of the network return data based on specific client request back to the requesting client.  Server Components also inherit the attributes of a Client Component in that they are a device on the network and that they can also request information from other Server Components. However what differentiates a Client Component from a Server Component is that a Server Component response to requests from devices on the network. An example of a Server Component can be seen in a web server. A web server listens for new requests and then interprets the request, processes the web pages, and then returns the processed data back to the web browser client so that it may render the data for the user to interpret. The Database Component of the network returns unprocessed data from databases or other resources. This component also inherits attributes from the Server Component in that it is a device on a network, it can request information from other server components and database components, and it also listens for new requests so that it can return data when needed. The three-tier client/server model is very similar to the three-tier application architecture model, and in fact the layers can be mapped to one another. Three-Tier Application Architecture Model Presentation Layer/Logic Business Layer/Logic Data Layer/Logic The Presentation Layer including its underlying logic is very similar to the Client Component of the three-tiered model. The Presentation Layer focuses on interpreting the data returned by the Business Layer as well as presents the data back to the user.  Both the Presentation Layer and the Client Component focus primarily on the user and their experience. This allows for segments of the Business Layer to be distributable and interchangeable because the Presentation Layer is not directly integrated in with Business Layer. The Presentation Layer does not care where the data comes from as long as it is in the proper format. This allows for the Presentation Layer and Business Layer to be stored on one or more different servers so that it can provide a higher availability to clients requesting data. A good example of this is a web site that uses load balancing. When a web site decides to take on the task of load balancing they must obtain a network device that sits in front of a one or machines in order to distribute the request across multiple servers. When a user comes in through the load balanced device they are redirected to a specific server based on a few factors. Common Load Balancing Factors Current Server Availability Current Server Response Time Current Server Priority The Business Layer and corresponding logic are business rules applied to data prior to it being sent to the Presentation Layer. These rules are used to manipulate the data coming from the Data Access Layer, in addition to validating any data prior to being stored in the Data Access Layer. A good example of this would be when a user is trying to create multiple accounts under one email address. The Business Layer logic can prevent duplicate accounts by enforcing a unique email for every new account before the data is even stored in the Data Access Layer. The Server Component can be directly tied to this layer in that the server typically stores and process the Business Layer before it is returned to the end-user via the Presentation Layer. In addition the Server Component can also run automated process through the Business Layer on the data in the Data Access Layer so that additional business analysis can be derived from the data that has been already collected. The Data Layer and its logic are responsible for storing information so that it can be easily retrieved. Typical in most modern applications data is stored in a database management system however data can also be in the form of files stored on a file server. In addition a database can take on one of several forms. Common Database Formats XML File Pipe Delimited File Tab Delimited File Comma Delimited File (CSV) Plain Text File Microsoft Access Microsoft SQL Server MySql Oracle Sybase The Database component of the Networking model can be directly tied to the Data Layer because this is where the Data Layer obtains the data to return back the Business Layer. The Database Component basically allows for a place on the network to store data for future use. This enables applications to save data when they can and then quickly recall the saved data as needed so that the application does not have to worry about storing the data in memory. This prevents overhead that could be created when an application must retain all data in memory. As you can see the Three-Tier Client/Server Networking Model and the Three-Tiered Application Architecture Model rely very heavily on one another to function especially if different aspects of an application are distributed across an entire network. The use of various servers and database servers are wonderful when an application has a need to distribute work across the network. Network Components and Application Layers Interaction Database components will store all data needed for the Data Access Layer to manipulate and return to the Business Layer Server Component executes the Business Layer that manipulates data so that it can be returned to the Presentation Layer Client Component hosts the Presentation Layer that  interprets the data and present it to the user

    Read the article

  • Custom ASP.Net MVC 2 ModelMetadataProvider for using custom view model attributes

    - by SeanMcAlinden
    There are a number of ways of implementing a pattern for using custom view model attributes, the following is similar to something I’m using at work which works pretty well. The classes I’m going to create are really simple: 1. Abstract base attribute 2. Custom ModelMetadata provider which will derive from the DataAnnotationsModelMetadataProvider   Base Attribute MetadataAttribute using System; using System.Web.Mvc; namespace Mvc2Templates.Attributes {     /// <summary>     /// Base class for custom MetadataAttributes.     /// </summary>     public abstract class MetadataAttribute : Attribute     {         /// <summary>         /// Method for processing custom attribute data.         /// </summary>         /// <param name="modelMetaData">A ModelMetaData instance.</param>         public abstract void Process(ModelMetadata modelMetaData);     } } As you can see, the class simple has one method – Process. Process accepts the ModelMetaData which will allow any derived custom attributes to set properties on the model meta data and add items to its AdditionalValues collection.   Custom Model Metadata Provider For a quick explanation of the Model Metadata and how it fits in to the MVC 2 framework, it is basically a set of properties that are usually set via attributes placed above properties on a view model, for example the ReadOnly and HiddenInput attributes. When EditorForModel, DisplayForModel or any of the other EditorFor/DisplayFor methods are called, the ModelMetadata information is used to determine how to display the properties. All of the information available within the model metadata is also available through ViewData.ModelMetadata. The following class derives from the DataAnnotationsModelMetadataProvider built into the mvc 2 framework. I’ve overridden the CreateMetadata method in order to process any custom attributes that may have been placed above a property in a view model.   CustomModelMetadataProvider using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using Mvc2Templates.Attributes; namespace Mvc2Templates.Providers {     public class CustomModelMetadataProvider : DataAnnotationsModelMetadataProvider     {         protected override ModelMetadata CreateMetadata(             IEnumerable<Attribute> attributes,             Type containerType,             Func<object> modelAccessor,             Type modelType,             string propertyName)         {             var modelMetadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);               attributes.OfType<MetadataAttribute>().ToList().ForEach(x => x.Process(modelMetadata));               return modelMetadata;         }     } } As you can see, once the model metadata is created through the base method, a check for any attributes deriving from our new abstract base attribute MetadataAttribute is made, the Process method is then called on any existing custom attributes with the model meta data for the property passed in.   Hooking it up The last thing you need to do to hook it up is set the new CustomModelMetadataProvider as the current ModelMetadataProvider, this is done within the Global.asax Application_Start method. Global.asax protected void Application_Start()         {             AreaRegistration.RegisterAllAreas();               RegisterRoutes(RouteTable.Routes);               ModelMetadataProviders.Current = new CustomModelMetadataProvider();         }   In my next post, I’m going to demonstrate a cool custom attribute that turns a textbox into an ajax driven AutoComplete text box. Hope this is useful. Kind Regards, Sean McAlinden.

    Read the article

  • MVC Validation with ModelState.isValid through a wizard

    - by Emmanuel TOPE
    I'm working on a small educational project on MVC 3, and I'm facing a small problem, when attempting to handle validation in my application through a wizard. I tried to get benefit from the ability of MVC3 to deliver content of a different view using the same URL, when handling an [HttpPost] method on a page. I my case,my main model's class contains about ten [Required] properties, that I would like to expose through a small wizard in 3 steps , So I want that the user may be able to enter his personal informations in the first step, then respond to some questions in the second stepp and finally receive a confirmation mail from the web application whit his credentials in the last step. I can't access the last step, because of the ModelState.isValid method that I use to handle validations, and which can't perform properly if I define some properties as [Required], but don't put them on the first view. As the replies to those questions remain in a couple of choices, I've thinked that I may use some nullable bool? for in order to avoid validation issues, but know that it's not the proper way. Are there someone who would like to help me find a way to extend my validation to those three steps ? Thanks in advance and sorry for my english, I'm not a native speaker.

    Read the article

  • How to apply verification and validation on the following example

    - by user970696
    I have been following verification and validation questions here with my colleagues, yet we are unable to see the slight differences, probably caused by language barrier in technical English. An example: Requirement specification User wants to control the lights in 4 rooms by remote command sent from the UI for each room separately. Functional specification The UI will contain 4 checkboxes labelled according to rooms they control. When a checkbox is checked, the signal is sent to corresponding light. A green dot appears next to the checkbox When a checkbox is unchecked, the signal (turn off) is sent to corresponding light. A red dot appears next to the checkbox. Let me start with what I learned here: Verification, according to many great answers here, ensures that product reflects specified requirements - as functional spec is done by a producer based on requirements from customer, this one will be verified for completeness, correctness). Then design document will be checked against functional spec (it should design 4 checkboxes..), and the source code against design (is there a code for 4 checkboxes, functions to send the signals etc. - is it traceable to requirements). Okay, product is built and we need to test it, validate. Here comes our understanding trouble - validation should ensure the product meets requirements for its specific intended use which is basically business requirement (does it work? can I control the lights from the UI?) but testers will definitely work with the functional spec, making sure the checkboxes are there, working, labelled, etc. They are basically checking whether the requirements in functional spec were met in the final product, isn't that verification? (should not be, lets stick to ISO 12207 that only validation is the actual testing)

    Read the article

  • Where we should put validation for domain model

    - by adisembiring
    I still looking best practice for domain model validation. Is that good to put the validation in constructor of domain model ? my domain model validation example as follows: public class Order { private readonly List<OrderLine> _lineItems; public virtual Customer Customer { get; private set; } public virtual DateTime OrderDate { get; private set; } public virtual decimal OrderTotal { get; private set; } public Order (Customer customer) { if (customer == null) throw new ArgumentException("Customer name must be defined"); Customer = customer; OrderDate = DateTime.Now; _lineItems = new List<LineItem>(); } public void AddOderLine //.... public IEnumerable<OrderLine> AddOderLine { get {return _lineItems;} } } public class OrderLine { public virtual Order Order { get; set; } public virtual Product Product { get; set; } public virtual int Quantity { get; set; } public virtual decimal UnitPrice { get; set; } public OrderLine(Order order, int quantity, Product product) { if (order == null) throw new ArgumentException("Order name must be defined"); if (quantity <= 0) throw new ArgumentException("Quantity must be greater than zero"); if (product == null) throw new ArgumentException("Product name must be defined"); Order = order; Quantity = quantity; Product = product; } } Thanks for all of your suggestion.

    Read the article

  • [java bean]hibernate Session breaks a java bean?

    - by blow
    Hi all, i have a simple JPanel bean in my projects, now i want to drag my panel bean class into my jframe. My panel bean class is like this: public class BeanPanel extends javax.swing.JPanel { /** Creates new form BeanPanel */ public BeanPanel () { initComponents(); Session session=HibernateUtil.getSessionFactory().openSession(); } This code seem to break the bean: Session session=HibernateUtil.getSessionFactory().openSession(); When i try to drag the class into my JFrame bean i had this error message: This component cannot be instantiated. Please make sure it is a JavaBeans Component If i comment it all works fine. What is the reason of this? Thanks.

    Read the article

  • jQuery Validation plugin: disable validation for specified submit buttons when there is submitHandle

    - by ccppjava
    Ok, I am using umbraco forum module, and on the comment form it uses jquery validate plugin. The problem is that I have added a search button on the same page using a UserControl, the search submit button triggers the comment form submission validation. I have done some research, and added the 'cancel' css class to the button. This bypass the first validation issue, however, it still fall into the 'submitHandler'. Have read the source code and find a way to detect whether the search button triggers the submission. however, there is not a nice way to bypass the handler. I am currently using a ugly way to do it: create javascript errors! I would like to know a nicer way to do the job. Many thanks! Btw, I am currently using: submitHandler: function (form) { $(form).find(':hidden').each(function () { var name = $(this).attr('name'); if (name && name.indexOf('btnSearch') === name.length - 'btnSearch'.length) { // this is a dirty hack to avoid the validate plugin to work for the button eval("var error = 1 2 ''"); } }); // original code from umbraco ignored here.... } ...............

    Read the article

  • Spring MVC: Where to place validation and how to validation entity references.

    - by arrages
    Let's say I have the following command bean for creating a user: public class CreateUserCommand { private String userName; private String email; private Integer occupationId; pirvate Integer countryId; } occupationId and countryId are drop down selected values on the form. They map to an entity in the database (Occupation, Country). This command object is going to be fed to a service facade like so: userServiceFacade.createUser(CreateUserCommand command); This facade will construct a user entity to be sent to the actual service. So I suppose that in the facade layer I will have to make several dao calls to map all the lookup properties of the User entity. Based on this what is the best strategy to validate that occupationId and countryId map to real entities? Where is the best place to perform this validation? There is the spring validator but I am not sure this is the best place for this, for one I am wary of this method as validation is tied to the web tier, but also that means I would need to make the dao calls in the validator for validation but I would need to call the dao's in the facade layer again when the command - entity translation occurs. Is there anything I can do better? Thanks.

    Read the article

  • JSF how to temporary disable validators to save draft

    - by Swiety
    I have a pretty complex form with lots of inputs and validators. For the user it takes pretty long time (even over an hour) to complete that, so they would like to be able to save the draft data, even if it violates rules like mandatory fields being not typed in. I believe this problem is common to many web applications, but can't find any well recognised pattern how this should be implemented. Can you please advise how to achieve that? For now I can see the following options: use of immediate=true on "Save draft" button doesn't work, as the UI data would not be stored on the bean, so I wouldn't be able to access it. Technically I could find the data in UI component tree, but traversing that doesn't seem to be a good idea. remove all the fields validation from the page and validate the data programmaticaly in the action listener defined for the form. Again, not a good idea, form is really complex, there are plenty of fields so validation implemented this way would be very messy. implement my own validators, that would be controlled by some request attribute, which would be set for standard form submission (with full validation expected) and would be unset for "save as draft" submission (when validation should be skipped). Again, not a good solution, I would need to provide my own wrappers for all validators I am using. But as you see no one is really reasonable. Is there really no simple solution to the problem?

    Read the article

  • Backbone.js (model instanceof Model) via Chrome Extension

    - by Leoncelot
    Hey guys, This is my first time ever posting on this site and the problem I'm about to pose is difficult to articulate due to the set of variables required to arrive at it. Let me just quickly explain the framework I'm working with. I'm building a Chrome Extension using jQuery, jQuery-ui, and Backbone The entire JS suite for the extension is written in CoffeeScript and I'm utilizing Rails and the asset pipeline to manage it all. This means that when I want to deploy my extension code I run rake assets:precompile and copy the resulting compressed JS to my extensions Directory. The nice thing about this approach is that I can actually run the extension js from inside my Rails app by including the library. This is basically the same as my extensions background.js file which injects the js as a content script. Anyway, the problem I've recently encountered was when I tried testing my extension on my buddy's site, whiskeynotes.com. What I was noticing is that my backbone models were being mangled upon adding them to their respective collections. So something like this.collection.add(new SomeModel) created some nonsense version of my model. This code eventually runs into Backbone's prepareModel code _prepareModel: function(model, options) { options || (options = {}); if (!(model instanceof Model)) { var attrs = model; options.collection = this; model = new this.model(attrs, options); if (!model._validate(model.attributes, options)) model = false; } else if (!model.collection) { model.collection = this; } return model; }, Now, in most of the sites on which I've tested the extension, the result is normal, however on my buddy's site the !(model instance Model) evaluates to true even though it is actually an instance of the correct class. The consequence is a super messed up version of the model where the model's attributes is a reference to the models collection (strange right?). Needless to say, all kinds of crazy things were happening afterward. Why this is occurring is beyond me. However changing this line (!(model instanceof Model)) to (!(model instanceof Backbone.Model)) seems to fix the problem. I thought maybe it had something to do with the Flot library (jQuery graph library) creating their own version of 'Model' but looking through the source yielded no instances of it. I'm just curious as to why this would happen. And does it make sense to add this little change to the Backbone source? Update: I just realized that the "fix" doesn't actually work. I can also add that my backbone Models are namespaced in a wrapping object so that declaration looks something like class SomeNamespace.SomeModel extends Backbone.Model

    Read the article

  • Validation and authorization in layered architecture

    - by SonOfPirate
    I know you are thinking (or maybe yelling), "not another question asking where validation belongs in a layered architecture?!?" Well, yes, but hopefully this will be a little bit of a different take on the subject. I am a firm believer that validation takes many forms, is context-based and varies at each level of the architecture. That is the basis for the post - helping to identify what type of validation should be performed in each layer. In addition, a question that often comes up is where authorization checks belong. The example scenario comes from an application for a catering business. Periodically during the day, a driver may turn in to the office any excess cash they've accumulated while taking the truck from site to site. The application allows a user to record the 'cash drop' by collecting the driver's ID, and the amount. Here's some skeleton code to illustrate the layers involved: public class CashDropApi // This is in the Service Facade Layer { [WebInvoke(Method = "POST")] public void AddCashDrop(NewCashDropContract contract) { // 1 Service.AddCashDrop(contract.Amount, contract.DriverId); } } public class CashDropService // This is the Application Service in the Domain Layer { public void AddCashDrop(Decimal amount, Int32 driverId) { // 2 CommandBus.Send(new AddCashDropCommand(amount, driverId)); } } internal class AddCashDropCommand // This is a command object in Domain Layer { public AddCashDropCommand(Decimal amount, Int32 driverId) { // 3 Amount = amount; DriverId = driverId; } public Decimal Amount { get; private set; } public Int32 DriverId { get; private set; } } internal class AddCashDropCommandHandler : IHandle<AddCashDropCommand> { internal ICashDropFactory Factory { get; set; } // Set by IoC container internal ICashDropRepository CashDrops { get; set; } // Set by IoC container internal IEmployeeRepository Employees { get; set; } // Set by IoC container public void Handle(AddCashDropCommand command) { // 4 var driver = Employees.GetById(command.DriverId); // 5 var authorizedBy = CurrentUser as Employee; // 6 var cashDrop = Factory.CreateCashDrop(command.Amount, driver, authorizedBy); // 7 CashDrops.Add(cashDrop); } } public class CashDropFactory { public CashDrop CreateCashDrop(Decimal amount, Employee driver, Employee authorizedBy) { // 8 return new CashDrop(amount, driver, authorizedBy, DateTime.Now); } } public class CashDrop // The domain object (entity) { public CashDrop(Decimal amount, Employee driver, Employee authorizedBy, DateTime at) { // 9 ... } } public class CashDropRepository // The implementation is in the Data Access Layer { public void Add(CashDrop item) { // 10 ... } } I've indicated 10 locations where I've seen validation checks placed in code. My question is what checks you would, if any, be performing at each given the following business rules (along with standard checks for length, range, format, type, etc): The amount of the cash drop must be greater than zero. The cash drop must have a valid Driver. The current user must be authorized to add cash drops (current user is not the driver). Please share your thoughts, how you have or would approach this scenario and the reasons for your choices.

    Read the article

  • jQuery Templates - XHTML Validation

    - by hajan
    Many developers have already asked me about this. How to make XHTML valid the web page which uses jQuery Templates. Maybe you have already tried, and I don't know what are your results but here is my opinion regarding this. By default, Visual Studio.NET adds the xhtml1-transitional.dtd schema <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> So, if you try to validate your page which has jQuery Templates against this schema, your page won't be XHTML valid. Why? It's because when creating templates, we use HTML tags inside <script> ... </script> block. Yes, I know that the script block has type="text/html" but it's not supported in this schema, thus it's not valid. Let's try validate the following code Code <!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>     <title>jQuery Templates :: XHTML Validation</title>     <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.min.js" type="text/javascript"></script>     <script src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js" type="text/javascript"></script>          <script language="javascript" type="text/javascript">         $(function () {             var attendees = [                 { Name: "Hajan", Surname: "Selmani", speaker: true, phones: [070555555, 071888999, 071222333] },                 { Name: "Denis", Surname: "Manski", phones: [070555555, 071222333] }             ];             $("#myTemplate").tmpl(attendees).appendTo("#attendeesList");         });     </script>     <script id="myTemplate" type="text/html">          <li>             ${Name} ${Surname}             {{if speaker}}                 (<font color="red">speaks</font>)             {{else}}                 (attendee)             {{/if}}         </li>     </script>      </head>     <body>     <ol id="attendeesList"></ol> </body> </html> To validate it, go to http://validator.w3.org/#validate_by_input and copy paste the code rendered on client-side browser (it’s almost the same, only the template is rendered inside OL so LI tags are created for each item). Press CHECK and you will get: Result: 1 Errors, 2 warning(s)  The error message says: Validation Output: 1 Error Line 21, Column 13: document type does not allow element "li" here <li> Yes, the <li> HTML element is not allowed inside the <script>, so how to make it valid? FIRST: Using <![CDATA][…]]> The first thing that came in my mind was the CDATA. So, by wrapping any HTML tag which is in script blog, inside <![CDATA[ ........ ]]> it will make our code valid. However, the problem is that the template won't render since the template tags {} cannot get evaluated if they are inside CDATA. Ok, lets try with another approach. SECOND: HTML5 validation Well, if we just remove the strikethrough part bellow of the !DOPCTYPE <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> our template is going to be checked as HTML5 and will be valid. Ok, there is another approach I've also tried: THIRD: Separate template to an external file We can separate the template to external file. I didn’t show how to do this previously, so here is the example. 1. Add HTML file with name Template.html in your ASPX website. 2. Place your defined template there without <script> tag Content inside Template.html <li>     ${Name} ${Surname}     {{if speaker}}         (<font color="red">speaks</font>)     {{else}}         (attendee)     {{/if}} </li> 3. Call the HTML file using $.get() jQuery ajax method and render the template with data using $.tmpl() function. $.get("/Templates/Template.html", function (template) {     $.tmpl(template, attendees).appendTo("#attendeesList"); }); So the complete code is: <!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>     <title>jQuery Templates :: XHTML Validation</title>     <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.min.js" type="text/javascript"></script>     <script src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js" type="text/javascript"></script>          <script language="javascript" type="text/javascript">         $(function () {             var attendees = [                 { Name: "Hajan", Surname: "Selmani", speaker: true, phones: [070555555, 071888999, 071222333] },                 { Name: "Denis", Surname: "Manski", phones: [070555555, 071222333] }             ];             $.get("/Templates/Template.html", function (template) {                 $.tmpl(template, attendees).appendTo("#attendeesList");             });         });     </script>      </head>     <body>     <ol id="attendeesList"></ol> </body> </html> This document was successfully checked as XHTML 1.0 Transitional! Result: Passed If you have any additional methods for XHTML validation, you can share it :). Thanks,Hajan

    Read the article

  • Simple PHP form Validation and the validation symbols

    - by Cool Hand Luke UK
    Hi have some forms that I want to use some basic php validation (regular expressions) on, how do you go about doing it? I have just general text input, usernames, passwords and date to validate. I would also like to know how to check for empty input boxes. I have looked on the interenet for this stuff but I haven't found any good tutorials. Thanks

    Read the article

  • Step by Step validation with jquery validation plugin

    - by Alex
    I know its been asked many times already but no one could come up with solution so far. The idea is to have one form separated into few steps and validate each step on next click of the button. I know jquery validation plugin is offering quite complicated way of doing it with accordion but can anyone come up with a simple solution something like var stepOne = { rules: { fieldname1: "required", fieldname2: "required", } } $("form").validate(stepOne); //onclick hope someone could suggest the best way of doing it. Thanks.

    Read the article

  • Detect whether or not a specific attribute was valid on the model

    - by Sir Code-A-Lot
    Having created my own validation attribute deriving from System.ComponentModel.DataAnnotations.ValidationAttribute, I wish to be able to detect from my controller, whether or not that specific attribute was valid on the model. My setup: public class MyModel { [Required] [CustomValidation] [SomeOtherValidation] public string SomeProperty { get; set; } } public class CustomValidationAttribute : ValidationAttribute { public override bool IsValid(object value) { // Custom validation logic here } } Now, how do I detect from the controller whether validation of CustomValidationAttribute succeeded or not? I have been looking at the Exception property of ModelError in the ModelState, but I have no way of adding a custom exception to it from my CustomValidationAttribute. Right now I have resorted to checking for a specific error message in the ModelState: public ActionResult PostModel(MyModel model) { if(ModelState.Where(i => i.Value.Errors.Where((e => e.ErrorMessage == CustomValidationAttribute.SharedMessage)).Any()).Any()) DoSomeCustomStuff(); // The rest of the action here } And changed my CustomValidationAttribute to: public class CustomValidationAttribute : ValidationAttribute { public static string SharedMessage = "CustomValidationAttribute error"; public override bool IsValid(object value) { ErrorMessage = SharedMessage; // Custom validation logic here } } I don't like relying on string matching, and this way the ErrorMessage property is kind of misused. What are my options?

    Read the article

  • Using unless in rails uniqueness validation

    - by dunxd
    I am just starting out in Rails, and trying to develop a simple application. I need to validate three values submitted to the application - each must meet the same validation criteria. The validation is pretty simple: Value is valid if unqiue, null or equal to "p" or "d". The following gets me halfway there: validates_uniqueness_of :value1, :value2, :value3, :allow_nil => true I think I can use :unless to check whether the value is either "p" or "d", however I can't figure out how. I guess I am trying to combine validates_uniqueness_of with validates_inclusion_of. Any suggestions?

    Read the article

  • Rails group validation with just one error message

    - by Victor
    The following validation code in the model: validates :formatted_address, :zip, :city, :state, :country, :presence => true, :message => "is incomplete. Please enter full address." is displayed when either of the fields are empty. Let's say now :address and country are empty, 2 errors are displayed: Formatted Address is incomplete. Please enter full address. Country is incomplete. Please enter full address. How can I group the error message in the validation to just show one error message if either of the fields validated does not exist? Address is incomplete. Please enter full address. Thanks.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >