Allow non filled fields - asp.net-mvc-3

I have a model for an ASP.NET MVC view containing several properties:
Subject
Message
Id
While subject and message are required, Id isn't required (it's hidden and only set
for an existing entry). Unfortunately, MVC validates it as required ( The If field
is required) even though I haven't set the Required attribute.
Has someone a solution? Haven't found a solution here, maybe just searching wrong...
Kind regards,
Sascha

If Id is an Int... you can try making it Int? (nullable Int).
If it is nullabe, I think MVC will not validate it.
Another way, would be place a default value in that hidden, lets say a "-1"... and on the controller you can check it.

By default, ASP.Net Mvc will treat non-nullable properties as 'required' - even if you do not add the [Required] attrtibute to the property. If your id is of type int - it is not-nullable and therefore required.
You have basically two options:
Change your Id property to int? - ie a nullable int.
Change the default setting for MVC to not regard non-nullable attributes as required.
Option 1 is straight-forward. For option 2 add the following to the Application_Start method in your global.asax
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = true;

Related

Vaadin & Spring Boot - Alternative translations within ValidationMessages.properties are not picked up

I tried to use BeanFieldGroup<Entity> in Vaadin Spring Boot, with javax.validator and Hibernate validators.
#NotBlank(message = "{may.not.null}")
#Column(name = "name", unique = true)
private String name;
and I created two files: ValidationMessages_en.properties:
may.not.null=not null
and ValidationMessages_fr.properties:
may.not.null=non null
But even when I change the language to French, the validator message is still from ValidationMessages_en.properties.
Have any of you any idea about this, please?
The BeanFieldGroup creates the BeanValidator with the locale, which is set to the component under validation. Your question does not mention how you create the text field for the name property, but let's assume that you create it this way:
TextField nameTextField = new TextField("Name");
The important factor here is to make sure that the nameTextField has correct locale before you bind the properties with BeanFieldGroup (you can check the locale with nameTextField.getLocale()).
So, try to configure your TextField to use the session locale like this:
nameTextField.setLocale(UI.getCurrent().getLocale());
This piece of code takes the locale from the request ("Accept-Language" request header) and sets it to the field -> the BeanFieldGroup will then create BeanValidators with the correct locale and the validation messages are localized (this happens in BeanFieldGroup#configureField).
However use this code only to check that the problem is really only in that your text field does not have correct Locale. It really does not mean that you have to set the Locale for each and every field out there... That's because in Vaadin (at least in Vaadin 7) the session (request based) Locale should be inherited by component from the parent. So if you add TextField to the Layout, then the TextField inherits the locale of the Layout, the Layout inherits it from the View and so on (all the way up to UI.getCurrent().getLocale() - so check that you have desired locale there). Since the inheritance happens during addComponent() call, it's my guess, that, maybe, in your case, it would be enough to call the addComponent() method (where you are adding the TextField to the layout) before you actually use the BeanFieldGroup binding.
More info about your problem here: Remember to set the Locale
Note: I tried to code your issue right now, I faced the same problem as you had and resolved it by moving the addComponent() call before the BeanFieldGroup.

Web application's form validation - design to propagate domain errors to client-side?

Data validation should occur at the following places in a web-application:
Client-side: browser. To speed up user error reporting
Server-side: controller. To check if user input is syntactically valid (no sql injections, for example, valid format for all passed in fields, all required fields are filled in etc.)
Server-side: model (domain layer). To check if user input is domain-wise valid (no duplicating usernames, account balance is not negative etc.)
I am currently a DDD fan, so I have UI and Domain layers separated in my applications.
I am also trying to follow the rule, that domain model should never contain an invalid data.
So, how do you design validation mechanism in your application so that validation errors, that take place in the domain, propagate properly to the client? For example, when domain model raises an exception about duplicate username, how to correctly bind that exception to the submitted form?
Some article, that inspired this question, can be found here: http://verraes.net/2015/02/form-command-model-validation/
I've seen no such mechanisms in web frameworks known to me. What first springs into my mind is to make domain model include the name of the field, causing exception, in the exception data and then in the UI layer provide a map between form data fields and model data fields to properly show the error in it's context for a user. Is this approach valid? It looks shaky... Are there some examples of better design?
Although not exactly the same question as this one, I think the answer is the same:
Encapsulate the validation logic into a reusable class. These classes are usually called specifications, validators or rules and are part of the domain.
Now you can use these specifications in both the model and the service layer.
If your UI uses the same technology as the model, you may also be able to use the specifications there (e.g. when using NodeJS on the server, you're able to write the specs in JS and use them in the browser, too).
Edit - additional information after the chat
Create fine-grained specifications, so that you are able to display appropriate error messages if a spec fails.
Don't make business rules or specifications aware of form fields.
Only create specs for business rules, not for basic input validation tasks (e.g. checking for null).
I want to share the approach used by us in one DDD project.
We created a BaseClass having fields ErrorId &
ErrorMessage.
Every DomainModel derive from this BaseClass & thus have a two extra fields ErrorId & ErrorMessage available from
BaseClass.
Whenever exception occurs we handle exception(Log in server, take appropriate steps for compensating logic & fetch User Friendly message from client location based localized Resource file for message ) then propagate data as simple flow without raising or throwing exception.
At client side check if ErrorMessage is not null then show error.
It's basic simple approach we followed from start of project.
If it's new project this is least complicated & efficient approach, but if you doing changes in big old project this might not help as changes are big.
For validation at each field level, use Validation Application Block from Enterprise Library.
It can be used as :
Decorate domain model properties with proper attributes like:
public class AttributeCustomer
{
[NotNullValidator(MessageTemplate = "Customer must have valid no")]
[StringLengthValidator(5, RangeBoundaryType.Inclusive,
5, RangeBoundaryType.Inclusive,
MessageTemplate = "Customer no must have {3} characters.")]
[RegexValidator("[A-Z]{2}[0-9]{3}",
MessageTemplate = "Customer no must be 2 capital letters and 3 numbers.")]
public string CustomerNo { get; set; }
}
Create validator instance like:
Validator<AttributeCustomer> cusValidator =
valFactory.CreateValidator<AttributeCustomer>();
Use object & do validation as :
customer.CustomerNo = "AB123";
customer.FirstName = "Brown";
customer.LastName = "Green";
customer.BirthDate = "1980-01-01";
customer.CustomerType = "VIP";
ValidationResults valResults = cusValidator.Validate(customer);
Check Validation results as:
if (valResults.IsValid)
{
MessageBox.Show("Customer information is valid");
}
else
{
foreach (ValidationResult item in valResults)
{
// Put your validation detection logic
}
}
Code example is taken from Microsoft Enterprise Library 5.0 - Introduction to Validation Block
This links will help to understand Validation Application Block:
http://www.codeproject.com/Articles/256355/Microsoft-Enterprise-Library-Introduction-to-V
https://msdn.microsoft.com/en-in/library/ff650131.aspx
https://msdn.microsoft.com/library/cc467894.aspx

Core Data: In XCode how can I set my attribute to be unique?

I'm setting up my Data Model for Core Data and I'm trying to find out how I can set up an attribute to be unique. I want it so that if another object is about the be saved then it wont allow it if this attribute is the same value as another. How can I do this? Thanks!
As specified in the Validation section of the CoreData guide, you can use the key-valu-coding validation patterns described in the KVC guide. Specifically, in the automatic validation section, it mentions that CoreData will use the KVC validation patterns when it tries to save. So on your model categories, you will end up with something like this:
-(BOOL) validateCourseName:(NSString **) courseName error:(NSError **) error {
// lookup existing course names, return NO if one exists, YES if none.
// note that courseName is a **, which means you can modify it if that makes sense.
*courseName = #"new name which will validate";
// but be sure to read the parts of the linked docs about memory if you do this.
return YES
}

wp7 - application.current as app Value can not be null

I put some properties in the App.xaml.cs file which I am using to store data and populate textboxes as I navigate through my application:
public String appRXName { set; get; }
public String appRXNumber { set; get; }
Originally I had a pivot control that called different pages to gather data, but then I moved that pivot control item off to its own page that still calls other pages to collect data. Now when I run the application I get an error.
Basically it was working when I had it inside the original Pivot control. Once I moved it to a separate page (pivot page calles it) then I started to get this error:
System.ArgumentNullException was unhandled Message=Value can not be null. Parameter name: Text
No matter what page I hit always the second item in the list displays the error.
txtRxNotes.Text = (Application.Current as App).appDosageNotes;
txtQuantity.Text = (Application.Current as App).appQuantity.ToString();
I found something online about a RootVisual but I'm not sure if that is what I looking at or not. Does anyone have any ideas?
The ArgumentNullException is being thrown because the value that you are trying to set for the Text property is null, which you cannot do; the Text property is not a nullable type.
Without knowing how and when these application-level properties are being set it's difficult to provide a good explanation of why the behavior is different since your refactor, but you could either:
Put a null check in the code that accesses these application-level properties.
Initialise the application-level properties to string.Empty in the application constructor.

Silverlight 4: Localization of built-in data annotation validation exceptions

I would like use data annotations to handle validation in my Silverlight app. The built-in validation attributes (primarily StringLength and Required) are great, and make life very easy. However, they seem to have one critical flaw. If my locale is set to fr-CA, for example, the validation exceptions are still in English - 'The Name field is required', 'The field Name must be a string with a maximum length of 20', etc.
This is a major problem. It means that if I want localized error messages for the built-in validation attributes, I have to manually add ErrorMessage/ErrorMessageResourceType to every validation attribute on every validatable property in my business layer, and manually add translated strings for every error message.
So... am I missing something here? Is there a way to automatically have the built-in validation attributes localized? Or some other easier way of doing this? Or am I just completely out of luck, and stuck with the manual route?
Any comments or thoughts would be appreciated.
Ok, I got around this by simply subclassing the built-in validation attributes. Problem solved!
internal class LocalizedStringLengthAttribute : StringLengthAttribute
{
public LocalizedStringLengthAttribute(int maximumLength)
: base(maximumLength)
{
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentUICulture, LanguageResources.Resource.Error_StringLength, name, MaximumLength);
}
}

Resources