Have a trouble with displaying errors near fields from own validation provider. Provider works and displays errors in summary validation block, but not near fields.
Provider is added to list of providers in Global.asax
ModelValidatorProviders.Providers.Add(new FFvalidator());
FFvalidator represents that code:
public class FFvalidator : ModelValidatorProvider
{
public override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context)
{
if(metadata.ContainerType == typeof(RegisterViewModel))
{
return new ModelValidator[] { new UserRegPropertyValidator(metadata, context) };
}
if(metadata.ModelType == typeof(RegisterViewModel))
{
return new ModelValidator[] { new UserRegValidator(metadata, context) };
}
return Enumerable.Empty<ModelValidator>();
}
}
Validator is inherited from ModelValidator Looks like that:
public class UserRegPropertyValidator : ModelValidator
{
...
}
Validation method (method of UserRegPropertyValidator) is shown below:
public override IEnumerable<ModelValidationResult> Validate(object container)
{
RegisterViewModel u = container as RegisterViewModel;
if(u != null)
{
switch (Metadata.PropertyName)
{
case "UserName":
Regex rgx = new Regex(@"^[0-9a-zA-Z-,]{1,35}$");
if ( !rgx.IsMatch(u.UserName) )
{
return new ModelValidationResult[]
{
new ModelValidationResult {MemberName="UserName", Message="Кроме букв, допустимы только символы - и ,"}
};
}
break;
}
}
But the trouble is that, AJAX validation doesn't work. ASP validation works well, for example an email binder show the error near the field like needed.
View:
<div class="form-group">
@Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.UserName, "", new { @class = "text-danger" })
</div>
</div>