StringLength attribute, client side validation and a membership provider - validation

How do I pass a value from Membership Provider (taken from web.config) to Validation Attributes in AccountModels in default MVC 3 project?
Membership.MinRequiredPasswordLength
returns value obtained from web.config and Register.cshtml view uses it:
<p>
Passwords are required to be a minimum of #Membership.MinRequiredPasswordLength
characters in length.
</p>
But it seems that ViewModel in AccountModels file have the values hard-coded in:
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
So how do I pass the value from web.config to MinimumLength parameter?

You won't be able to specify an attribute property dynamically like you would like. That is why the templates have it hard-coded. The workaround to still use data annotations would be to have your view model implement IValidatableObject and have it check the password against Membership.MinRequiredPasswordLength. Another option would be to create an attribute that inherits from ValidationAttribute and checks against Membership.MinRequiredPasswordLength.
David Hayden has a post covering both of these options.
For the client side, you would need to implement IClientValidatable on the model or the custom attribute. Here is another answer that shows an example. You would also need to add the client side validation function, and you could use #Membership.MinRequiredPasswordLength inside your Razor view to pull in the value.

Related

ASP NET MVC 3: Form doesn't POST due to a required hidden field

I want to submit a form, but the button isn't clickable. After some search I found out that this is due to the jquery validation that ASP.NET MVC has for required fields.
For some weird reason ASP NET thinks my hidden field "UserId" is required. Which isn't actually true. See part of my model here:
public class ResetPasswordModel
{
[.....]
public Guid UserId
{
get;
set;
}
}
And the page source shows this:
<input data-val="true" data-val-required="The UserId field is required." id="UserId" name="UserId" type="hidden" value="" />
Any ideas?!?
The fact it's not a nullable type means it's required. Change the definition to Guid? (include the question mark to make it nullable) Or even better create a viewmodel that doesn't have it.
I believe that a Guid is required by default because it is not nullable. Guids are usually primary keys so making them nullable is problematic. Try converting your guid ToString() so that you can use it in your view, then back to a Guid before using it in your controller or model. You may have to create a ViewModel in order to do this.
Are you sure there isn't a separate partial class containing MetaData which has marked the field as mandatory?
Something like this:
class UserResetPasswordModelMetaData
{
[Required(ErrorMessage = "The UserId field is required.")]
public Guid UserId { get; set; }
}
Search your project for the string "The UserId field is required". I bet it's there somewhere.
Also, how do you identify the user who is trying to reset their password, if not by their id?
setup the jQuery validator to ignore hidden fields. Like so:
jQuery Validate Ignore elements with style
Probably There is a Key attribute on top of UserId property which means it's mandatory

Contact form. Message limit

I have form on my website which is contact form. I am using ReCaptcha on that.
The form just sending email, no records to data base.
So my question is should i put character limit on that message?
It's always a good idea to put limits on input fields. For example you could decorate the property on your view model which is bound to the message with the StringLength attribute to enforce validation.
[StringLength(1000, ErrorMessage = "The message must be at most {1} characters long.")]
[AllowHtml]
public string Message { get; set; }

RIA service default required attribute

I have an EF4 model with table's columns doesn't allow null.
At the SL client application I always receieve the "columnName is required" because I have the binding in xaml with [NotifyOnValidationError=True,ValidatesOnExceptions=True] for the textboxes.
My questions is:
I can overide the default required errormessage at the metadata class, but how can I have it as a custom validation? I mean I don't wnat to do this at the sealed metadata class:
[Required(ErrorMessage = "Coin English Name Is required")]
[CustomValidation(typeof (CustomCoinVaidation), "ValidateCoinName")]
public string coin_name_1 { get; set; }
I want to have it inside the custom validation method that I will define for all types of errors regards that coin_name_1, as follows:
public static ValidationResult ValidateCoinName(string name, ValidationContext validationContext)
{
if (string.IsNullOrWhiteSpace(name))
{
return new ValidationResult("The Coin Name should be specified", new [] { "Coin Name" });
}
return ValidationResult.Success;
}
Why?
for two reasons :
1- Group all the validation isdie one container (for easy localization further).
2- I don't want the coin_name_1 to be displayed to the end-user, but a meanigful as "Coin English Name".
Second question:
I have a ValidationSummary control on my xaml page where all the errors are displayed but is displaying the orignal name of the column "coin_name_1" how can I chnge that to be a meanigfil also.
Best regards
Waleed
A1:
I just left the required as it is implemented right now..
A2:
I went through different sources and find this artical.
It shows how to style the validation summary:
http://www.ditran.net/common-things-you-want-know-about-silverlight-validationsummary
I am also implementing a client-side validation asyncronizly.
Regards

How do I show a different Required message to instances of the same object in MVC3?

I have a Razor MVC3 project which has two user records in a form, one for the key contact and one for a backup contact. For example;
public class User
{
[Required(ErrorMessage = "First name is required")]
public string FirstName { get; set; }
}
Validation all works well except for the small issue where the user fails to fill out a field, it says 'First name is required' but I'd like to point the user to which one of the first name fields is missing. Such as 'Backup contact first name is required' or 'Key contact first name is required'.
Ideally I'd like to leave the [Required] annotation on the class as it is used elsewhere.
This seems like one of those small cases that might have been missed and is not easily achieved, but please prove me wrong.
Ryan
One way you can accomplish this is with a separate view model for this screen, instead of a single User model with all the error messages. In the new view model, you could have a BackupContactFirstName property, KeyContactFirstName property, etc each with its separate error message. (Alternatively this view model could contain separate User models as properties, but I've found that Microsoft's client validation doesn't play well with complex models and prefers flat properties).
Your view model would look like this:
public class MySpecialScreenViewModel
{
[Required(ErrorMessage = "Backup contact first name is required")]
public string BackupContactFirstName { get; set; }
[Required(ErrorMessage = "Key contact first name is required")]
public string KeyContactFirstName { get; set; }
}
Then pass your view model to the view like this:
#model MySpecialScreenViewModel
...
Your post controller action would collect the properties from the view model (or map them to separate User models) and pass them to the appropriate data processing methods.
An alternative I have stumbled across, just modify the ModelState collection. It will have the elements in a collection named by index, like 'User_0__EmailAddress' and you can adjust / amend / replace the Errors collection associated with that key.
[Required(ErrorMessage = "{0} is required")]
{0}=The DisplayName is automatically placed on it
sample
[DisplayName("Amount per square meter")]
[Required(ErrorMessage = "{0} is required")]
public int PriceMeter { get; set; }
output
Amount per square meter is required

Globally localize validation

I'm using System.ComponeneModel.DataAnnotations attributes such as Required and StringLength. Is it possible to localize its error messages globally?
I know I can do this
[Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(Resources.Validation))]
But doing this everywhere I use required attribute would be just insane. Also I'd like to avoid stuff like:
public class LocalizedRequiredAttribute : RequiredAttribute {
public LocalizedRequiredAttribute()
: base() {
ErrorMessageResourceName = "Required";
ErrorMessageResourceType = typeof(Resources.Validation);
}
}
(but if there isn't any other way, I'll settle for this)
AFAIK you need either a custom attribute or specify the ErrorMessageResourceName and ErrorMessageResourceType properties. There is another possibility detailed here:
Create a global resource class in
App_GlobalResources, and set
DefaultModelBinder.ResourceClassKey to
the name of this class (for example,
if you made "Messages.resx", then set
ResourceClassKey to "Messages").
There are two strings you can override
in MVC 2:
The string value for
"PropertyValueInvalid" is used when
the data the user entered isn't
compatible with the data type (for
example, typing in "abc" for an
integer field). The default message
for this is: "The value '{0}' is not
valid for {1}."
The string value for
"PropertyValueRequired" is used when
the user did not enter any data for a
field which is not nullable (for
example, an integer field). The
default message for this is: "A value
is required."
It's important to note
in the second case that, if you have
the
DataAnnotationsModelValidatorProvider
in your validator providers list
(which it is by default), then you
will never see this second message.
This provider sees non-optional fields
and adds an implied [Required]
attribute to them so that their
messages will be consistent with other
fields with explicit [Required]
attributes and to ensure that you get
client-side validation for required
fields.
For MVC3 see DataAnnotationsResources. It's "RequiredAttribute_ValidationError" and more.
You may solve it by installing .NET Framework language pack(s).
See also

Resources