Simply Change culture for [Required] data annotation validation message in .net Core 6.0 - asp.net-core

What I'm trying to do seems really simple but I'm struggling with it since this morning...
I just want to force French language for html.ValidationMessageFor(x=>x.Name)
Here my name property :
[Required]
public string Name { get; set; }
Right now, if I try to validate a form without filling the property I've got the "The Name field is required."
Where does this message "The {0} is required." come from ?
How can I change the language of it without having to override all my [Required] properties in all my ViewModels with something like :
[Required(ErrorMessageResourceName ="Required",ErrorMessageResourceType =typeof(FrenchDataAnnotation))]
Thanks a lot.

You can create a custom validation attribute that implements the default Required attribute and use it for validation:
public sealed class ExRequiredAttribute : RequiredAttribute
{
public ExRequiredAttribute() : base()
{
this.ErrorMessage = "my custom error message...!"
}
}
Then use it like:
[ExRequired]
public string Name { get; set; }
Another solution is to use third party localization nuget like XLocalizer which overrides all default data annotations, ModelBinding and IdentityErrors.

Related

Salesforce Apex/JSON serialization with change on variable name

In Salesforce/Apex how can i serialize an Apex Class to Json/String with a change of variable names mapping ? like in java we can use #SerializedName annotation.
So far, Apex does not support annotation for serialization. The supported annotations are
here
But, in this type of scenario, I always follows
public class TestClass
{
public string oldA { get; set; }
public string oldB { get; set; }
public string oldC { get; set; }
}
String jsonStr = JSON.serialize(objectTestClass);
jsonStr = jsonStr.replaceAll('"oldA":','"newA":');
You can use JSONGenerator to create the output yourself
There's no out of the box way for remapping variables via an annotation or a similar facility. To remap a variable you'd have to roll your own parser via JSONParser or use untyped deserialization and encapsulate it into your own Apex class.

ASP.NET CORE 2 disable spell check on input fields using annotations

Using ASP.NET CORE 2, is there a way to disable spell check on input fields using data annotations? For instance disable spell checking on first name data...
I know about setting spellcheck="false" directly in the html view, but would like to be able to use attributes in the viewmodel / model.
You can create a custom attribute defines whether the property should spell check:
[AttributeUsage(AttributeTargets.Property, Inherited = false)]
public class SpellCheckedAttribute : System.Attribute
{
private bool _spellCheck;
public SpellCheckedAttribute(bool spellCheck)
{
_spellCheck = spellCheck;
}
public virtual bool SpellCheck
{
get
{
return _spellCheck;
}
}
}
Then in model you can add the attribute on related property :
public class YourModel
{
[SpellChecked(true)]
public string name { get; set; }
}
In controller , you can check whether specific property should spell check by :
var nameShouldSpellCheck = typeof(YourModel).GetTypeInfo().GetProperty("name").GetCustomAttribute<SpellCheckedAttribute>().SpellCheck;
Then you could enable/disable spell check in javscript according to that value .

Pass Url Parameters to Action by Model in ASP.NET MVC 4

I want to assign my url parameters to Model properties, passed as a parameter to the associated Action. For example;
Say, my url is http://www.example.com/Item/Index?color=red&size=50
My action inside the controller is like below:
public class ItemController : Controller
{
public ActionResult Index(MyModel myModel)
{
//
return View(myModel);
}
}
I want to configure the model or whatever necessary so that my model takes the color and size as field values. The following didn't work:
public class MyModel
{
[Display(Name = "color")]
public string Color{ get; set; }
[Display(Name = "size")]
public string Size{ get; set; }
}
What would be the correct way to solve the problem?
Thanks for any suggestion.
Update
Well, yes! The code above would work correctly, because Url parameter names are the same as model property names. I should explain my problem exactly as I encounter for the next time, sorry.
I must correct a part of my question to make it clear. The url should have been: http://www.example.com/Item/Index?c=red&s=50 to detect the problem.
If the url is like that, the code would not work. Because Url parameters don't have the same name as Model properties.
Updated model is below:
public class MyModel
{
[Display(Name = "c")]
public string Color{ get; set; }
[Display(Name = "s")]
public string Size{ get; set; }
}
Try adding [FromUri] in front of the parameter.
public class ItemController : Controller
{
public ActionResult Index([FromUri] MyModel myModel)
{
// do something
return View();
}
}
debugging the issue
Here are some suggestions in debugging the issue, as it should work out of the box.
try binding to primitive types
public class ItemController : Controller
{
public ActionResult Index(string color, string size)
{
// do something
return View();
}
}
Try reading out of the request object directly
var size = this.Request["size"];
If either of those work there is an issue with your model binding.
Update
If you want to have the query string parameters different to the model in MVC you'll need to have a custom model binder. Take a look at Asp.Net MVC 2 - Bind a model's property to a different named value and http://ole.michelsen.dk/blog/bind-a-model-property-to-a-different-named-query-string-field.html which extends the answer a little.
https://github.com/yusufuzun/so-view-model-bind-20869735 has an example with some html helpers that could be useful.

loosing dataAnottation when upload model from database

I have a big database existing database to comunicate with, and I'm using EF 5.0 database first, the problem I'm having is that if I create any data decoration like [stringlength(50)] on the class and then the databases is uploaded, when I "upload from database" all data annotations are gone. How can I do to keep them?
It's very simple: You Can't! Because those codes are auto-generated and will be over written on each model update or change.
However you can achieve what you need through extending models. Suppose that EF generated the following entity class for you:
namespace YourSolution
{
using System;
using System.Collections.Generic;
public partial class News
{
public int ID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int UserID { get; set; }
public virtual UserProfile User{ get; set; }
}
}
and you want do some work arounds to preserve your you data annotations and attributes. So, follow these steps:
First, add two classes some where (wherever you want, but it's better to be in Models) like the following:
namespace YourSolution
{
[MetadataType(typeof(NewsAttribs))]
public partial class News
{
// leave it empty.
}
public class NewsAttribs
{
// Your attribs will come here.
}
}
then add what properties and attributes you want to the second class - NewsAttribs here. :
public class NewsAttrib
{
[Display(Name = "News title")]
[Required(ErrorMessage = "Please enter the news title.")]
public string Title { get; set; }
// and other properties you want...
}
Notes:
1) The namespace of the generated entity class and your classes must be the same - here YourSolution.
2) your first class must be partial and its name must be the same as EF generated class.
Go through this and your attribs never been lost again ...
The accepted answer may work for standard data operations, but I am trying to validate the model prior to the call to DbSet.Add using TryValidateObject. With the accepted answer, it is still not picking up on the data annotations.
What did work for me I found in a .NET Runtime GitHub thread, as proposed by what I'm inferring is one of the .NET developers.
Basically, this is a bug, and you have to force the model to recognize the metadata decorations using TypeDescriptor.AddProviderTransparent . . .
TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(News), typeof(NewsAttrib)), typeof(News));
Once I make this call, TryValidateObject recognizes the data annotations and returns false when any of the constraints are not met.
Here's the link. I little more than half-way down, there's a working code sample in a .zip file.
https://github.com/dotnet/runtime/issues/46678

mvc4 url validation

I'm writing this question here after trying to find an answer for two days.
basically here's what's going on.
I have a property in the viewmodel as follows
[Required(ErrorMessage = "Required Field")]
[Url(ErrorMessage="Please enter a valid url")]
[DisplayName("Website")]
public string web { get; set; }
in the view, I have this
#Html.EditorFor(model => model.web, new { AutoCompleteType = "Disabled", autocomplete = "off" })
now the problem lies in how the input text for this field is validated in the client side. the field must have the protocol prefix at all times, otherwise it becomes invalid.
what is the best way I can fix this issue?
Many Thanks
You can do this using the DataAnnotationsExtensions library. They have an UrlAttribute that you can configure to only validate when a protocol is specified. This attribute also supplies client-side validation. You can see an example of this behavior here: http://dataannotationsextensions.org/Url/Create
You can use this attribute as follows:
using System.ComponentModel.DataAnnotations;
namespace DataAnnotationsExtensions.Core
{
public class UrlEntity
{
[Url]
[Required]
public string Url { get; set; }
[Url(UrlOptions.OptionalProtocol)]
[Required]
public string UrlWithoutProtocolRequired { get; set; }
[Url(UrlOptions.DisallowProtocol)]
[Required]
public string UrlDisallowProtocol { get; set; }
}
}
For your purposes, the first option suffices.
The package of this library (with ASP.NET MVC support included) can be found on NuGet:
Install-Package DataAnnotationsExtensions.MVC3
Note: this also works fine with ASP.NET MVC 4
Not sure if I fully understand the question. Are you trying to validate for correctly formed URLs? If so you could implement a RegularExpression DataAnnotation as follows:
[RegularExpression(#"^http(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?$", ErrorMessage = "My Error Message")]