Error with German character in Asp.Net Core Identity - asp.net-identity-3

When I try to create a User with the UserManager and there are characters like ä, ö, ü in the UserName, I get a succeeded=false. I don’t understand why it is a problem. The DB is nvarchar (255) and should not have a problem with German characters. I can change it afterword by using the DbContext. How can I change this behavior?

Usermanager validates the username by checking if there is any character not contained in the list of allowed characters. You can change that list:
services.Configure<IdentityOptions>(options =>
{
// The list of allowed characters in the username used to validate user names
// you can add German characters here
options.User.AllowedUserNameCharacters
= "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._#+";
});
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();

Related

Vaadin 7 Validation (BeanValidator and setrequired)

Hi I have just started Vaadin 7 and have got the BeanValidator working. But, I have some issues. The code I am using is the following:
BeanItem<RegisterBean> item = new BeanItem<RegisterBean>(new RegisterBean());
final FieldGroup binder = new FieldGroup(item);
final TextField email = new TextField("email");
email.addValidator(new BeanValidator(RegisterBean.class, "email"));
The validates fine using the BeanValidator. With the #NotNull tag I am able to validate for Null values as well. However, I would like to give the user visual clues that the field in the form can't be left blank. For this, I used:
email.setRequired(true);
However, after adding the setRequired the BeanValidation for the form no longer works?
Is this a limitation?
How do I get around it?
You should probably rely on the bean validation itself and use the fieldgroup.
My model looks as follows:
#NotNull(message="Please enter a valid email address.")
#Email(message="Please enter a valid email address.")
#Size(min = 3, max = 255, message="Please enter a valid email address.")
#Column(name="P_EMAIL", nullable=true, length=255)
private String email;
In your view do either buildAndBind
Field<?> email = binder.buildAndBind("email");
Or use the annotation #PropertyId("email") in your field declaration. The rest is magic.
Instead of FieldGroupuse BeanFieldGroup.
A problem will be that validation is made preliminary. So install the validators on click. More to that topic can be found here: http://morevaadin.com/content/bean-validation-and-vaadin-comprehensive-example/
To complete the example above, using a BeanFieldGroup, as it got validators, you can use the setValidationVisible method of an AbstractField to turn off preliminary validation, then to turn on in a blurListener and in the buttons clickListeners.
AbstractTextField cName = binder.buildAndBind("Name","name", AbstractTextField.class);
cName.setNullRepresentation("");
cName.setValidationVisible(false);
cName.addBlurListener(new MyBlurListener(cName)); //<-- turn on setValidationVisible there
myButton.addClickListener(event -> {
try {
cName.setValidationVisible(true);
binder.commit();
} catch (CommitException e){
Notification.show("Sending error");
}
});

ASP.NET MVC - Resend confirmation email with WebSecurity?

Trying to use the WebSecurity and if my user loses, needs to resend, or otherwise changes their email, their does not seem to be any way to reset your confirmation token via the WebSecurity classes.
How do I reset the confirmation token for WebSecurity in Asp.NET MVC?
There doesn't seem to be support for this in the WebSecurity type. I was forced to query the database directly. Since I was using EF my code looked like the following:
public string GetConfirmationToken(string email)
{
using (var db = new DbContext())
{
var tsqlQuery = string.Format("SELECT [ConfirmationToken] FROM [webpages_Membership] WHERE [UserId] IN (SELECT [UserId] FROM [UserProfile] WHERE [Email] LIKE '{0}')", email);
return db.Database.SqlQuery<string>(tsqlQuery).First();
}
}

ASP.NET MVC DataAnnotations StringLength On Password ModelState.IsValid Fails When Hashed

First question is, using StringLength, is it possible to specify only a minimum length? More importantly, this is what I have for a password.
private string password;
[Required]
[DataType(DataType.Password)]
[StringLength(15, MinimumLength = 6)]
public string Password { get { return password; } set { HashPassword(value); } }
What I want is when the user enters the password that they can only enter a minimum of 6 and maximum of 15 characters for their password. The issue lies in my Controller because ModelState.IsValid fails due to the hashing generating a huge string exceeding 15 characters. How can I get around this?
I would recommend doing your hashing elsewhere (e.g. in the controller) instead of doing it in the set accessor of the property.

Disable 'The value 'xxx' is not valid for 'yyy' message

In my ASP.NET MVC application, I have a form and I'm using a ViewModel, so the ModelBinder can bind to my Strongly Typed Class. I'm using DataAnnotations for validation
public class FormViewModel
{
[Required]
public string SomeValue {get;set;}
[Range(0, 10, ErrorMessage="Enter a number between 0 and 10.")]
public byte? SomeOtherValue {get;set;}
}
This works great. The problem however is when the user doesn't enter a valid value for the SomeOtherValue (like abc), a standard MVC-error pops up: 'The value 'abc' is not valid for 'SomeOtherValue'. This is really annoying, as I can't customize this message. I know there are ways to Localize this message, but that just doesn't make sense (I don't want a general message, I want a value-specific value).
I tried applying a RegularExpression-attribute to the 'SomeOtherValue', which only allows byte-values, but probably the standard-validation 'overrides' this validation. Is there some way to apply a custom 'the value is not valid' message for a property, or otherwise disable the standard-message?
Here is a different (non-ideal way, IMHO) to fix it if the custom validation attribute is not working for you. In the controller:
if (!ModelState.IsValid)
{
string fieldName = "ThatFieldName";
var m = ViewData.ModelState[fieldName];
if (m != null && m.Errors.Count > 0)
{
ViewData.ModelState.Remove(fieldName);
ViewData.ModelState.AddModelError(fieldName, "You mucked that field up.");
}
}

asp.net mvc validation must be a number custom error

I am new to asp.net and I have a problem. When the users insert in a editor for a decimal field something other than numbers, they get an error "Field name" is not a number. But I don't want them to receive this message I want them to receive another message. I have no problem with this with required and range validators.
Is there any way for me to do this?
I am not refering necessarily to changing the culture just displaying another message.
Thanks.
Hope I understand your, to change RangeValidator ErrorMessage just initialize ErrorMessage parameter:
[Range(0, 100, ErrorMessage = "Some another error message insert here!")]
[RegularExpression("\d", ErrorMessage = "!!!")]
public decimal DecimalField { get; set; }
This is the actual answer:
Create a class CustomClientDataTypeModelValidatorProvider. Copy the code from the MVC sources. Change the method MakeErrorString to output the appropiate message like this:
private static string MakeErrorString(string displayName)
{
return string.Format(
CultureInfo.CurrentCulture,
Core.Resources.Errors.EroareNuENr,
displayName);
}
I couldn't find a way not to copy the code just extend it as it uses this static method.
If anyone knows this please tell me.
Then, in global.asax, I wrote this:
var cdProvider = ModelValidatorProviders.Providers.SingleOrDefault(p => p.GetType().Equals(typeof(ClientDataTypeModelValidatorProvider)));
if(cdProvider != null)
{
ModelValidatorProviders.Providers.Remove(cdProvider);
ModelValidatorProviders.Providers.Add(
new CustomClientDataTypeModelValidatorProvider());
}
so that the flow would actually be routed to my class and not the class in the asp.net MVC dll
I got the idea from here:
Unfortunately this is is not a trivial task. However you can try the following hack...
Better to do this only on essential fields, as this is more code to maintain.
In the controller's action method
if(ModelState.IsValid)
{
// code
}
else
{
if (ModelState["YourField"].Errors.Count > 0)
{
ModelState["YourField"].Errors.Clear();
ModelState.AddModelError("YourField", "Your custom message here");
}
// code
}
You can set ResourceClassKey of ClientDataTypeModelValidatorProvider class to name of a global resource that contains FieldMustBeNumeric key to replace mvc validation error message of number with your custom message. Also key of date validation error message is FieldMustBeDate.
ClientDataTypeModelValidatorProvider.ResourceClassKey="MyResources"; // MyResource is my global resource
See here for more details on how to add the MyResources.resx file to your project:
The field must be a number. How to change this message to another language?
To change the error message you get after server side validation you need to change 'PropertyValueInvalid' key in your resource file and assign the resource file name to DefaultModelBinder.ResourceClassKey. See this question for details: localize default model validation in mvc 2
Look for solution at the end of this page:
http://jwwishart.wordpress.com/2010/03/22/custom-server-and-client-side-required-validator-in-mvc-2-using-jquery-validate/
I checked this in my MVC 3 RTM project and it works well.
... or use jQuery to change to message on the client.
A quick and simple hack for Customize RangeValidator ErrorMessage --"'Field name' is not a number"-- is using RegularExpression
[Range(0.5, 1000, ErrorMessage = "Amount should be in range {1} to {2}.")]
[DataType(DataType.Currency)]
[RegularExpression(#"\d", ErrorMessage = "Amount is not valid.")]
public decimal Amount{ get; set; }
You could implement your own custom validation attribute: http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx
It seems that since Para's answer MVC evolved and now the ClientDataTypeModelValidatorProvider accepts a ResourceClassKey property. It uses the FieldMustBeNumeric and FieldMustBeNumeric messages specified in your resource class.

Resources