MVC 4 Custom Data Annotation Request for jquery authentication

We are trying to create some custom validation using MVC 4 data annotations, what we create is more like inviting messages than more restrictive validation. First of all, we created some custom validation classes that inherit from the ValidationAttribute Class and override the IsValid () method to validate the data and return the ValidationResult if they are invalid. The view that displays this data has partial views that EditorTemplates use to display razor-generated data using our user data annotations and many built-in checks, all wrapped in a form like

@using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl })) 

Our requirements are to allow the user to submit data and partially save forms, but request them in any invalid fields, so use the CSS class in the submit form to allow postback like this

 <input type="submit" value="Save" class="cancel"/> 

All this works fine, but now we have requirements to display all error messages when loading the page, which I did not see until I try ...

I found some examples that used jquery in the $ (document) .ready event, which triggered the form as shown here.

Manual form validation in MVC 3 and jQuery

but it didn't seem useful to us for $ ('form). Validate () doesn't seem to do anything, the only call that seems to work when checking forms $ ("Form) .valid () But it only seems to show built-in validation, such as the [Required] attributes, and the only way to receive special validation messages to show is to use the submit button to submit the form.

Should there be a way to get my custom data annotations to display messages without sending back the page for the first time? Any help would be greatly appreciated.

+6
source share
3 answers

Ok, so I found a way to get the result that I wanted, although it was a little more work than I wanted / assumed it would be. I was missing that I did not inject IClientValidatable into my custom validation class and had to add my special verification to the jQuery Validator add-on that I tried, but not with IClientValidatable implanted into the custom validation class, I’ll quickly get down to how to get this job, assuming you have all the jQuery-created stuff / included

First create a simple model that uses a special validation attribute

 public class Person { [Required] [Display( Name="Name")] public string Name { get; set; } public int Age { get; set; } //Uses a custom data annotation that requires that at lease it self or the property name passed in the constructor are not empty [OneOfTwoRequired("Mobile")] public string Phone { get; set; } [OneOfTwoRequired("Phone")] public string Mobile { get; set; } } 

A custom validation class that uses reflection to retrieve the property of the name of a validated row with

Note from 08/15/2012: if you are using MVC 4, you need to reference System.web.mvc 3.0 to use IClientValidatable, since ModelClientValidationRule does not seem to exist in MVC 4

 public class OneOfTwoRequired : ValidationAttribute, IClientValidatable { private const string defaultErrorMessage = "{0} or {1} is required."; private string otherProperty; public OneOfTwoRequired(string otherProperty) : base(defaultErrorMessage) { if (string.IsNullOrEmpty(otherProperty)) { throw new ArgumentNullException("otherProperty"); } this.otherProperty = otherProperty; } public override string FormatErrorMessage(string name) { return string.Format(ErrorMessageString, name, otherProperty); } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { PropertyInfo otherPropertyInfo = validationContext.ObjectInstance.GetType().GetProperty(otherProperty); if (otherPropertyInfo == null) { return new ValidationResult(string.Format("Property '{0}' is undefined.", otherProperty)); } var otherPropertyValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null); if (otherPropertyValue == null && value == null) { return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName)); } return ValidationResult.Success; } public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { yield return new ModelClientValidationRule { ErrorMessage = FormatErrorMessage(metadata.DisplayName), //This is the name of the method aaded to the jQuery validator method (must be lower case) ValidationType = "oneoftworequired" }; } } 

Add this to the view or partial view, you have to make sure that this is not the $ (document) .ready method

  jQuery.validator.addMethod("oneoftworequired", function (value, element, param) { if ($('#Phone).val() == '' && $('#Mobile).val() == '') return false; else return true; }); jQuery.validator.unobtrusive.adapters.addBool("oneoftworequired"); 

jQuery authentication stuff seems to be necessary if you want to validate the form without posting back or on the page loading, and for that you just call $ ('form'). valid ()

Hope this helps someone :)

+6
source

Why is your common C # code applicable to any two fields, and the script code is tied specifically to the fields with the identifiers "#Phone" and "#Mobile"? Is there no way to generalize a script?

0
source

Source: https://habr.com/ru/post/922706/


All Articles