xVal Date Validation with Nhibernate Validator - asp.net

I am using xVal with NHibernate Validator and I have a hard time to validate the dates.
First, NHibernate does not have validation for Date/DateTime formatting (except Past and Future). Second, I tried xVal itself (not using NHibernate Validator) but still no chance.
I need to validate the date values (let's say in a text box), to make sure it's a valid date. For instance, 13/01/2010 or 11/31/2010 are not valid dates.
I have tried creating new rules for NHibernate Validator by extending a new class, but it needs to be declared in the xVal client side too. I don't like to overwrite the existing scripts, if possible. I also used xval's [DataType(DataType.Date)] but it doesn't check if the date is valid!
Any suggestions?

After spending some time on this issue, here is the answer to my question: Custom Validation in xVal

Related

Validation occurs even Data Anotations is not set

I am working on dot net core 3.1. I have a form for submitting product details. I have used Data annotations with jQuery validations.
My problem is when I try to submit the form even the field which I haven't used data annotations is getting stops by validations. Even If I comment all data annotations in the modal also the validations is stopping me. I don't know what is causing problem. I have tried by cleaning and rebuild the solutions. But the problem remains.
I am getting below validation errors:
Below is the modal which I haven't added data annotations:
Below is cshtml:
It's important to note that your model validation takes into consideration the datatype of the fields. So fields like decimal or int are non-nullable. But you can solve this by declaring your fields as nullable. For such types, you don't need to declare [Required] because by their very nature they cannot be null unless declared nullable using ? operator.
Example:
public decimal? DiscountedProductPrice

Hibernate Validator Depends on

Is there a way to achieve depends on behavior with hibernate validation. For instance if i have two custom validations
#InvalidAmount // Validates the amount is invalid with some custom logic
#AmountNotAccepted // Validates the currency is not accepted along with some custom logic
The idea is not to merge both of them together and throw second error only if the first one succeeds. Is there a way to do it? Something like run the second validate only first first is not an error.
For example:
#AmountNotAccepted(dependsOn = {InvalidAmount})
You may be after group sequences?

entity framework core exception handling db first

Background
With ef core code first approach, validation is robust and simple: https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/validation
With the database first approach, it seems like any validation is happening behind the scenes by the database when dbcontext.SaveChanges(); is called. What's worse, these exceptions are nebulous and entirely unhelpful, for example, SqlException: String or binary data would be truncated can be thrown if any of the string properties of any of the entities have too many chars (ours is a legacy app riddled with char(10) and such), or even if a key that is a string is left null.
Question
I want to know if there is any reasonable or accepted way of enforcing the validation. I've found this question which might help debugging, but I would like to enforce the constraints in code
Is there any better method than changing every auto property to one that throws if it's constraints aren't met?
EntityFramework Core does not enforce any validation at all. The validation rules you see in the example are enforced by MVC and not EF. One of the main reason for EF Core to remove validation check was that only. Validation are run in UI and then in EF and then again in database which is just redundant. Hence client side validation is left to the front-end (MVC in this case) and server side is done by database engine.
When you use database first approach, EF core does not generate any annotation for validation because it does not reason about them anyway. That means you would get only server side validation which means error during SaveChanges.
The only way to enforce constraint in the code (client side) is to write those annotations so that MVC can enforce them or write custom code to deal with it. The whole validation mechanism is transparent to EF.
I ended up going with a psuedo extension to the generator tooling. Since the DBContext is a partial class, I made a new class that has a main
public partial class DBContext{
public static void Main(string[]args){
DBContext context = new DBContext();
var modelbuilder = new Microsoft.EntityFrameworkCore.ModelBuilder(new Microsoft.EntityFrameworkCore.Metadata.Conventions.ConventionSet());
context.OnModelCreating(modelbuilder);
IMutableModel model=modelbuilder.Model;
from there I used Linq to transform the various info about each entity's properties and the annotations on them into List<KeyValuePair<string,List<KeyValuePair<Regex,string>>>> where the first pair's key is the entity name, and the value is a list of find and replace pairs to edit the code that had already been generated with the corresponding validation, one per property. Then all I had to do was abuse the fact that the tooling generates the classes in <className>.cs files, and iterate over my list, executing the replacements for each entity source code file.
I'd have preferred doing something a little less hacky, because I'm relying on format that the ef tooling outputs, but it works

Keep a history of values for specific properties of EF entities

I have a requirement to keep a history of values of some fields in an EF4 ASP.NET MVC3 application. This just needs to be a log file of sorts, log the user, datetime, tablename, fieldname, oldvalue, newvalue.
Although it would be pretty easy to code this in various save routines, I'm wondering if I can get global coverage by wiring it into some sort of dataannotation, so that I can perhaps declare
[KeepHistory()]
public string Surname { get; set; }
in my partial class (I'm using POCO but generated from a T4 template).
So Questions
1) Is this a bad idea ? I'm basically proposing to side-effect changes to an entity, not directly referenced by the code, as a result of an annotation.
2) Can it be done ? Will I have access to the right context to tie up with my unit of work so that changes get saved or dropped with the context save?
3) Is there a better way?
4) If you suggest I do this, any pointers would be appreciated - everything I've read is for validation, which may not be the best starting point.
Actually, validation might be a good starting point. Since an attribute does not know about which property or class it was assigned to, but a validation-attribute gets called by the validation framework with all the necessary informátion. If you implement the System.ComponentModel.DataAnnotations.ValidationAttribute class you can override the IsValid(object, ValidationContext) method, which gives you the actual value of the property, the name of the property and the container.
This might take a lot of work, since you need to get to the currently logged-in user etc. I'm guessing that the .NET implementation provides some sort of caching for the specific attributes on an entity type, which would be a pain to implement by yourself.
Another way, would be to use the ObjectStateManager exposed by your EF ObjectContext, which can provide you with the ObjectStateEntry-objects for all entities of a given state. See the
ObjectStateManager.GetObjectStateEntries(EntityState) method, for more information about how to call it (and when). The ObjectStateEntry actually contains a record of the original and current-values, which can be compared to find any changes made within the lifetime of the current ObjectContext.
You might consider using the ObjectStateManager to inject your custom logging behavior, while this behavior decides based on property-attributes which change should be logged.

hibernate validator: validate 2 fields match

I was wondering, am I overlooking something or does the hibernate validator offer no annotation to verify that 2 fields are equal (such as a password).
I know I can write my own validators, but well this seems like standard functionality.
If you’re using Spring Framework then you can use Spring Expression Language (SpEL) for that. I’ve wrote small library that provides JSR-303 validator based on SpEL that makes cross-field validations very easy. Take a look at https://github.com/jirutka/validator-spring.
This will validate equality of password fields when at least one of them is not empty.
#SpELAssert(value = "password.equals(passwordVerify)",
applyIf = "password || passwordVerify",
message = "{validator.passwords_not_same}")
public class User {
private String password;
private String passwordVerify;
}
Just went for the custom validator route. The other 2 answers here aren't really related to the question.
With a bit of googling I found a fieldmatch example.
Hibernate is a ORM Mapper.
It is used to persist data into a DB and extract it again. As such, having 2 fields with an identical value makes not much sense (From a persistance point of view). Thats something you should check in your Business logic.
And I am with Junesh... Dont persist your passwords in a retrievable format... Look up Hasing and Salting - Or even better, think about openID so you dont have to bother your clients with yet another stupid password...
I am hoping you are not saving the confirm password in the database as well. You do not have any out of the box validations for this, but instead you will have to use custom annotation which is pretty straight forward as well.

Resources