Change the default error message in the model state binder - not working - asp.net-core-mvc

This is how mvc.net core 3.1 - This is is how my property is in the class
[BindProperty]
[Required(ErrorMessage = "Enter the valid amount")]
[ValidDecimal(ErrorMessage = "Enter the amount correctly")]
public decimal? QuoteAmountTotal { get; set; }
And code for custom ValidDecimal value is
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
public class ValidDecimalAttribute : ValidationAttribute{
protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
{
if (value == null || value.ToString().Length == 0)
{
return ValidationResult.Success;
}
return decimal.TryParse(value.ToString(), out _) ? ValidationResult.Success : new ValidationResult(ErrorMessage);
}
}
I am inputing value in this field with space or alpha numeric. For example 2 0 0 0.
However, it displays default mvc.net core error instead of my custom error which is
The value '2 0 0 0' is not valid for QuoteAmountTotal.
This is AttemptedvalueisInvalidAccessor
enter image description here
I need to display my custom error message instead of default MVC error model message, which is not displaying in this case.

If you put a break point on IsValid method ,when you debug,you'll find the method is never excuted
as the doc indicates:
Model state represents errors that come from two subsystems: model binding and model validation. Errors that originate from model binding are generally data conversion errors.Model validation occurs after model binding and reports errors where data doesn't conform to business rules.
UpDate:
You could try to replace the model binder with your customer model binder,I tried as below:
public class SomeEntityBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
var modelName = bindingContext.ModelName;
// Try to fetch the value of the argument by name
var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName);
if (valueProviderResult == ValueProviderResult.None)
{
return Task.CompletedTask;
}
bindingContext.ModelState.SetModelValue(modelName, valueProviderResult);
var value = valueProviderResult.FirstValue;
// Check if the argument value is null or empty
if (string.IsNullOrEmpty(value))
{
return Task.CompletedTask;
}
if (!decimal.TryParse(value, out var QuoteAmountTotal))
{
// Non-decimal arguments result in model state errors
bindingContext.ModelState.TryAddModelError(modelName,"Enter the amount correctly");
return Task.CompletedTask;
}
bindingContext.Result = ModelBindingResult.Success(QuoteAmountTotal);
return Task.CompletedTask;
}
}
in model:
[ModelBinder (typeof(SomeEntityBinder))]
public decimal QuoteAmountTotal { get; set; }
Result:

Related

Edit on Model - complex types not updated properly

I have this two objects - Magazine and Author (M-M relationship):
public partial class MAGAZINE
{
public MAGAZINE()
{
this.AUTHORs = new HashSet<AUTHOR>();
}
public long REF_ID { get; set; }
public string NOTES { get; set; }
public string TITLE { get; set; }
public virtual REFERENCE REFERENCE { get; set; }
public virtual ICollection<AUTHOR> AUTHORs { get; set; }
}
public partial class AUTHOR
{
public AUTHOR()
{
this.MAGAZINEs = new HashSet<MAGAZINE>();
}
public long AUTHOR_ID { get; set; }
public string FULL_NAME { get; set; }
public virtual ICollection<MAGAZINE> MAGAZINEs { get; set; }
}
}
My problem is that I can't seem to update the number of authors against a magazine e.g. if I have 1 author called "Smith, P." stored already against a magazine, I can add another called "Jones, D.", but after the post back to the Edit controller the number of authors still shows 1 - i.e. "Smith, P.H".
Please not that I have successfully model bound the number of authors back to the parent entity (Magazine), it uses a custom model binder to retrieve the authors and bind to the Magazine (I think), but it still doesn't seem to update properly.
My code for updating the model is straight forward - and shows the variable values both before and after:
public ActionResult Edit(long id)
{
MAGAZINE magazine = db.MAGAZINEs.Find(id);
return View(magazine);
}
and here are the variables pre-editing/updating -
[HttpPost]
public ActionResult Edit(MAGAZINE magazine)
{
if (ModelState.IsValid)
{
db.Entry(magazine).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(magazine);
}
...and here are the variables after a new author has been added...
I am getting suspicious that the author entity is showing, post edit that it is not bound to any magazine and I am guessing this is why it is not being updated back to the magazine entity - but it is perplexing as I am effectively dealing with the same magazine entity - I guess it may be something to do with the custom model binder for the author.
Can anyone help on this matter?
For completeness - I have included my AuthorModelBinder class too -
public class AuthorModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var values = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (values != null)
{
// We have specified asterisk (*) as a token delimiter. So
// the ids will be separated by *. For example "2*3*5"
var ids = values.AttemptedValue.Split('*');
List<int> validIds = new List<int>();
foreach (string id in ids)
{
int successInt;
if (int.TryParse(id, out successInt))
{
validIds.Add(successInt);
}
else
{
//Make a new author
AUTHOR author = new AUTHOR();
author.FULL_NAME = id.Replace("\'", "").Trim();
using (RefmanEntities db = new RefmanEntities())
{
db.AUTHORs.Add(author);
db.SaveChanges();
validIds.Add((int)author.AUTHOR_ID);
}
}
}
//Now that we have the selected ids we could fetch the corresponding
//authors from our datasource
var authors = AuthorController.GetAllAuthors().Where(x => validIds.Contains((int)x.Key)).Select(x => new AUTHOR
{
AUTHOR_ID = x.Key,
FULL_NAME = x.Value
}).ToList();
return authors;
}
return Enumerable.Empty<AUTHOR>();
}
}
I faced a very similar scenario when I developed my blog using MVC/Nhibernate and the entities are Post and Tag.
I too had an edit action something like this,
public ActionResult Edit(Post post)
{
if (ModelState.IsValid)
{
repo.EditPost(post);
...
}
...
}
But unlike you I've created a custom model binder for the Post not Tag. In the custom PostModelBinder I'm doing pretty much samething what you are doing there (but I'm not creating new Tags as you are doing for Authors). Basically I created a new Post instance populating all it's properties from the POSTed form and getting all the Tags for the ids from the database. Note that, I only fetched the Tags from the database not the Post.
I may suggest you to create a ModelBinder for the Magazine and check it out. Also it's better to use repository pattern instead of directly making the calls from controllers.
UPDATE:
Here is the complete source code of the Post model binder
namespace PrideParrot.Web.Controllers.ModelBinders
{
[ValidateInput(false)]
public class PostBinder : IModelBinder
{
private IRepository repo;
public PostBinder(IRepository repo)
{
this.repo = repo;
}
#region IModelBinder Members
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
HttpRequestBase request = controllerContext.HttpContext.Request;
// retrieving the posted values.
string oper = request.Form.Get("oper"),
idStr = request.Form.Get("Id"),
heading = request.Form.Get("Heading"),
description = request.Form.Get("Description"),
tagsStr = request.Form.Get("Tags"),
postTypeIdStr = request.Form.Get("PostType"),
postedDateStr = request.Form.Get("PostedDate"),
isPublishedStr = request.Form.Get("Published"),
fileName = request.Form.Get("FileName"),
serialNoStr = request.Form.Get("SerialNo"),
metaTags = request.Form.Get("MetaTags"),
metaDescription = request.Form.Get("MetaDescription"),
themeIdStr = request.Form.Get("Theme");
// initializing to default values.
int id = 0, serialNo = 0;
DateTime postedDate = DateTime.UtcNow;
DateTime? modifiedDate = DateTime.UtcNow;
postedDate.AddMilliseconds(-postedDate.Millisecond);
modifiedDate.Value.AddMilliseconds(-modifiedDate.Value.Millisecond);
/*if operation is not specified throw exception.
operation should be either'add' or 'edit'*/
if (string.IsNullOrEmpty(oper))
throw new Exception("Operation not specified");
// if there is no 'id' in edit operation add error to model.
if (string.IsNullOrEmpty(idStr) || idStr.Equals("_empty"))
{
if (oper.Equals("edit"))
bindingContext.ModelState.AddModelError("Id", "Id is empty");
}
else
id = int.Parse(idStr);
// check if heading is not empty.
if (string.IsNullOrEmpty(heading))
bindingContext.ModelState.AddModelError("Heading", "Heading: Field is required");
else if (heading.Length > 500)
bindingContext.ModelState.AddModelError("HeadingLength", "Heading: Length should not be greater than 500 characters");
// check if description is not empty.
if (string.IsNullOrEmpty(description))
bindingContext.ModelState.AddModelError("Description", "Description: Field is required");
// check if tags is not empty.
if (string.IsNullOrEmpty(metaTags))
bindingContext.ModelState.AddModelError("Tags", "Tags: Field is required");
else if (metaTags.Length > 500)
bindingContext.ModelState.AddModelError("TagsLength", "Tags: Length should not be greater than 500 characters");
// check if metadescription is not empty.
if (string.IsNullOrEmpty(metaTags))
bindingContext.ModelState.AddModelError("MetaDescription", "Meta Description: Field is required");
else if (metaTags.Length > 500)
bindingContext.ModelState.AddModelError("MetaDescription", "Meta Description: Length should not be greater than 500 characters");
// check if file name is not empty.
if (string.IsNullOrEmpty(fileName))
bindingContext.ModelState.AddModelError("FileName", "File Name: Field is required");
else if (fileName.Length > 50)
bindingContext.ModelState.AddModelError("FileNameLength", "FileName: Length should not be greater than 50 characters");
bool isPublished = !string.IsNullOrEmpty(isPublishedStr) ? Convert.ToBoolean(isPublishedStr.ToString()) : false;
//** TAGS
var tags = new List<PostTag>();
var tagIds = tagsStr.Split(',');
foreach (var tagId in tagIds)
{
tags.Add(repo.PostTag(int.Parse(tagId)));
}
if(tags.Count == 0)
bindingContext.ModelState.AddModelError("Tags", "Tags: The Post should have atleast one tag");
// retrieving the post type from repository.
int postTypeId = !string.IsNullOrEmpty(postTypeIdStr) ? int.Parse(postTypeIdStr) : 0;
var postType = repo.PostType(postTypeId);
if (postType == null)
bindingContext.ModelState.AddModelError("PostType", "Post Type is null");
Theme theme = null;
if (!string.IsNullOrEmpty(themeIdStr))
theme = repo.Theme(int.Parse(themeIdStr));
// serial no
if (oper.Equals("edit"))
{
if (string.IsNullOrEmpty(serialNoStr))
bindingContext.ModelState.AddModelError("SerialNo", "Serial No is empty");
else
serialNo = int.Parse(serialNoStr);
}
else
{
serialNo = repo.TotalPosts(false) + 1;
}
// check if commented date is not empty in edit.
if (string.IsNullOrEmpty(postedDateStr))
{
if (oper.Equals("edit"))
bindingContext.ModelState.AddModelError("PostedDate", "Posted Date is empty");
}
else
postedDate = Convert.ToDateTime(postedDateStr.ToString());
// CREATE NEW POST INSTANCE
return new Post
{
Id = id,
Heading = heading,
Description = description,
MetaTags = metaTags,
MetaDescription = metaDescription,
Tags = tags,
PostType = postType,
PostedDate = postedDate,
ModifiedDate = oper.Equals("edit") ? modifiedDate : null,
Published = isPublished,
FileName = fileName,
SerialNo = serialNo,
Theme = theme
};
}
#endregion
}
}
This line db.Entry(magazine).State = EntityState.Modified; only tells EF that magazine entity has changed. It says nothing about relations. If you call Attach all entities in object graph are attached in Unchanged state and you must handle each of them separately. What is even worse in case of many-to-many relation you must also handle relation itself (and changing state of relation in DbContext API is not possible).
I spent a lot of time with this problem and design in disconnected app. And there are three general approaches:
You will send additional information with your entities to find what has changed and what has been deleted (yes you need to track deleted items or relations as well). Then you will manually set state of every entity and relation in object graph.
You will just use data you have at the moment but instead of attaching them to the context you will load current magazine and every author you need and reconstruct those changes on those loaded entities.
You will not do this at all and instead use lightweight AJAX calls to add or remove every single author. I found this common for many complex UIs.

MVC3 Client Validation JS formatted Error Message Automatically?

I created a custom validation with following sample JS code:
(function ($) {
$.validator.unobtrusive.adapters.add('myrule', ['minvalueproperty', 'maxvalueproperty'],
function (options) {
options.rules['myrule'] = options.params;
options.messages['currencyrule'] = options.message;
}
);
$.validator.addMethod('myrule', function (value, element, params) {
return false;
}
} (jQuery));
Server side validator code is
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class MyValidationAttribute : ValidationAttribute, IClientValidatable
{
public CurrencyValidationAttribute(string minPropertyName, string maxPropertyName)
: base (DefaultErrorMessage)
{
this.minPropertyName = minPropertyName;
this.maxPropertyName = maxPropertyName;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
return new ValidationResult(this.ErrorMessage);
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var clientValidationRule = new ModelClientValidationRule
{
ValidationType = "myrule",
ErrorMessage = this.ErrorMessage,
};
clientValidationRule.ValidationParameters["minvalueproperty"] = minPropertyName;
clientValidationRule.ValidationParameters["maxvalueproperty"] = maxPropertyName;
yield return clientValidationRule;
}
}
My model class is decorated with my custom validation attribute
[MyValidation("MinValue", "MaxValue",
ErrorMessage = "Wrong value, must be between {0} and {1}")]
public string Money { get; set; }
It appears to work for most part other than error message displaying. In my model property I have used a string with place holders to be replaced, but there is no actual code yet.
When I run the page, I entered some invalid value to the text box and forced client side validation to return false, the funny thing is that the error message I saw was
Wrong value, must be between [object Object] and {1}
Somehow {0} was replaced automatically. Any clue what is the reason the error message got replaced?

How to validate one field related to another's value in ASP .NET MVC 3

I had two fields some thing like phone number and mobile number. Some thing like..
[Required]
public string Phone { get; set; }
[Required]
public string Mobile{ get; set; }
But user can enter data in either one of it. One is mandatory. How to handle them i.e how to disable the required field validator for one field when user enter data in another field and viceversa. In which event i have to handle it in javascript and what are the scripts i need to add for this. Can anyone please help to find the solution...
One possibility is to write a custom validation attribute:
public class RequiredIfOtherFieldIsNullAttribute : ValidationAttribute, IClientValidatable
{
private readonly string _otherProperty;
public RequiredIfOtherFieldIsNullAttribute(string otherProperty)
{
_otherProperty = otherProperty;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var property = validationContext.ObjectType.GetProperty(_otherProperty);
if (property == null)
{
return new ValidationResult(string.Format(
CultureInfo.CurrentCulture,
"Unknown property {0}",
new[] { _otherProperty }
));
}
var otherPropertyValue = property.GetValue(validationContext.ObjectInstance, null);
if (otherPropertyValue == null || otherPropertyValue as string == string.Empty)
{
if (value == null || value as string == string.Empty)
{
return new ValidationResult(string.Format(
CultureInfo.CurrentCulture,
FormatErrorMessage(validationContext.DisplayName),
new[] { _otherProperty }
));
}
}
return null;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "requiredif",
};
rule.ValidationParameters.Add("other", _otherProperty);
yield return rule;
}
}
which you would apply to one of the properties of your view model:
public class MyViewModel
{
[RequiredIfOtherFieldIsNull("Mobile")]
public string Phone { get; set; }
public string Mobile { get; set; }
}
then you could have a controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel());
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
and finally a view in which you will register an adapter to wire the client side validation for this custom rule:
#model MyViewModel
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script type="text/javascript">
jQuery.validator.unobtrusive.adapters.add(
'requiredif', ['other'], function (options) {
var getModelPrefix = function (fieldName) {
return fieldName.substr(0, fieldName.lastIndexOf('.') + 1);
}
var appendModelPrefix = function (value, prefix) {
if (value.indexOf('*.') === 0) {
value = value.replace('*.', prefix);
}
return value;
}
var prefix = getModelPrefix(options.element.name),
other = options.params.other,
fullOtherName = appendModelPrefix(other, prefix),
element = $(options.form).find(':input[name="' + fullOtherName + '"]')[0];
options.rules['requiredif'] = element;
if (options.message) {
options.messages['requiredif'] = options.message;
}
}
);
jQuery.validator.addMethod('requiredif', function (value, element, params) {
var otherValue = $(params).val();
if (otherValue != null && otherValue != '') {
return true;
}
return value != null && value != '';
}, '');
</script>
#using (Html.BeginForm())
{
<div>
#Html.LabelFor(x => x.Phone)
#Html.EditorFor(x => x.Phone)
#Html.ValidationMessageFor(x => x.Phone)
</div>
<div>
#Html.LabelFor(x => x.Mobile)
#Html.EditorFor(x => x.Mobile)
#Html.ValidationMessageFor(x => x.Mobile)
</div>
<button type="submit">OK</button>
}
Pretty sick stuff for something so extremely easy as validation rule that we encounter in our everyday lives. I don't know what the designers of ASP.NET MVC have been thinking when they decided to pick a declarative approach for validation instead of imperative.
Anyway, that's why I use FluentValidation.NET instead of data annotations to perform validations on my models. Implementing such simple validation scenarios is implemented in a way that it should be - simple.
I know this question is not so hot, because it was asked relatively long time ago, nevertheless I'm going to share with a slightly different idea of solving such an issue. I decided to implement mechanism which provides conditional attributes to calculate validation results based on other properties values and relations between them, which are defined in logical expressions.
Your problem can be defined and automatically solved by the usage of following annotations:
[RequiredIf("Mobile == null",
ErrorMessage = "At least email or phone should be provided.")]
public string Phone{ get; set; }
[RequiredIf("Phone == null",
ErrorMessage = "At least email or phone should be provided.")]
public string Mobile { get; set; }
If you feel it would be useful for your purposes, more information about ExpressiveAnnotations library can be found here. Client side validation is also supported out of the box.
Since nobody else suggested it, I'm going to tell you a different way to do this that we use.
If you create a notmapped field of a custom data type (in my example, a pair of gps points), you can put the validator on that and you don't even need to use reflection to get all the values.
[NotMapped]
[DCGps]
public GPS EntryPoint
{
get
{
return new GPS(EntryPointLat, EntryPointLon);
}
}
and the class, a standard getter/setter
public class GPS
{
public decimal? lat { get; set; }
public decimal? lon { get; set; }
public GPS(decimal? lat, decimal? lon)
{
this.lat = lat;
this.lon = lon;
}
}
and now the validator:
public class DCGps : DCValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (!(value is GPS)) {
return new ValidationResult("DCGps: This annotation only works with fields with the data type GPS.");
}
//value stored in the field.
//these come through as zero or emptry string. Normalize to ""
string lonValue = ((GPS)value).lonstring == "0" ? "" : ((GPS)value).lonstring;
string latValue = ((GPS)value).latstring == "0" ? "" : ((GPS)value).latstring;
//place validation code here. You have access to both values.
//If you have a ton of values to validate, you can do them all at once this way.
}
}

Asp.Net MVC validation annotation regular expression attribute

When I have a checkbox in my form it is not enough to mark the matching property as Required because a true or false is sent as it's value.
Whats the best way to validate this in the model? I was thinking a regular expression to match the string true but I am either not writing it correctly or it does not work on a Boolean property.
public bool FeeAgree
{
get
{
return _feeAgree;
}
set
{
_feeAgree = value;
}
}
Above is the property I am trying to validate. Using the Required attribute does not work because the Html.CheckBoxFor creates a hidden field so there is always a valueof either true or false passed.
You don't need any data annotation for boolean properties. If the value is not true or false the default model binder will handle the case when trying to parse it and add a model error. So basically just by the fact of having such model property it would only accept true or false. Every other value would be considered as error.
If you were using a nullable boolean you could enforce it to have a value with the Required attribute:
[Required]
public bool? FeeAgree { get; set; }
To ensure that the user checked the checkbox you could write a custom validation attribute:
public class MustBeTrueAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
return value != null && (bool)value;
}
}
and then:
[MustBeTrue(ErrorMessage = "You must accept the terms and conditions")]
public bool FeeAgree { get; set; }
This solution could be extended to include client side validation.
public class MustBeTrueAttribute : ValidationAttribute, IClientValidatable {
public override bool IsValid(object value) {
return value is bool && (bool)value;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
ModelMetadata metadata, ControllerContext context) {
return new ModelClientValidationRule[] {
new ModelClientValidationRule {
ValidationType = "checkboxtrue",
ErrorMessage = this.ErrorMessage
}};
}
}
Then if the view included a bit of jquery code to add the "checkboxtrue" validation type...
jQuery.validator.unobtrusive.adapters.add("checkboxtrue", function (options) {
if (options.element.tagName.toUpperCase() == "INPUT" && options.element.type.toUpperCase() == "CHECKBOX") {
options.rules["required"] = true;
if (options.message) {
options.messages["required"] = options.message;
}
}
});
The result is client-side checkbox validation

ASP MVC 2 Validation : Passing Javascript code to the client

I am writing a custom validation attribute
It does conditional validation between two fields
When I create my rule, one of the things that I could not solve is how to pass javascript code through ValidationParameters
Usually, I just do
ValidationParameters["Param1"] = "{ required :function(element) { return $("#age").val() < 13;) }"
However, the MicrosoftMvcJQueryValidation.js routines trnasforms this to
Param1 = "{ required :function(element) { return $("#age").val() < 13;) }"
I could use Param1.eval() in Javascript. This will evaluates and executes the code but I just want to evalute the code and execute it later
JSON parser does not parse string contening Javascript code
So I am asking here for any idea
Not sure how you would inject javascript as you describe, but you may want to consider using the custom validation pattern for ASP.NET MVC 2.
Important pieces are the ValidationAttribute, DataAnnotationsModelValidator, registering the validator in Application_Start with DataAnnotationsModelValidatorProvider.RegisterAdapter, and the client side Sys.Mvc.ValidatorRegistry.validators function collection to register your client side validation code.
Here's the example code from my post.
[RegularExpression("[\\S]{6,}", ErrorMessage = "Must be at least 6 characters.")]
public string Password { get; set; }
[StringLength(128, ErrorMessage = "Must be under 128 characters.")]
[MinStringLength(3, ErrorMessage = "Must be at least 3 characters.")]
public string PasswordAnswer { get; set; }
public class MinStringLengthAttribute : ValidationAttribute
{
public int MinLength { get; set; }
public MinStringLengthAttribute(int minLength)
{
MinLength = minLength;
}
public override bool IsValid(object value)
{
if (null == value) return true; //not a required validator
var len = value.ToString().Length;
if (len < MinLength)
return false;
else
return true;
}
}
public class MinStringLengthValidator : DataAnnotationsModelValidator<MinStringLengthAttribute>
{
int minLength;
string message;
public MinStringLengthValidator(ModelMetadata metadata, ControllerContext context, MinStringLengthAttribute attribute)
: base(metadata, context, attribute)
{
minLength = attribute.MinLength;
message = attribute.ErrorMessage;
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
var rule = new ModelClientValidationRule
{
ErrorMessage = message,
ValidationType = "minlen"
};
rule.ValidationParameters.Add("min", minLength);
return new[] { rule };
}
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MinStringLengthAttribute), typeof(MinStringLengthValidator));
}
Sys.Mvc.ValidatorRegistry.validators["minlen"] = function(rule) {
//initialization
var minLen = rule.ValidationParameters["min"];
//return validator function
return function(value, context) {
if (value.length < minLen)
return rule.ErrorMessage;
else
return true; /* success */
};
};

Resources