public void GetJsonValidationMetadata_ValidationSummary() { // Arrange FormContext context = new FormContext() { FormId = "theFormId", ValidationSummaryId = "validationSummary" }; ModelClientValidationRule rule = new ModelClientValidationRule() { ValidationType = "ValidationType1", ErrorMessage = "Error Message" }; rule.ValidationParameters["theParam"] = new { FirstName = "John", LastName = "Doe", Age = 32 }; FieldValidationMetadata metadata = new FieldValidationMetadata() { FieldName = "theFieldName", ValidationMessageId = "theFieldName_ValidationMessage" }; metadata.ValidationRules.Add(rule); context.FieldValidators["theFieldName"] = metadata; // Act string jsonMetadata = context.GetJsonValidationMetadata(); // Assert string expected = @"{""Fields"":[{""FieldName"":""theFieldName"",""ReplaceValidationMessageContents"":false,""ValidationMessageId"":""theFieldName_ValidationMessage"",""ValidationRules"":[{""ErrorMessage"":""Error Message"",""ValidationParameters"":{""theParam"":{""FirstName"":""John"",""LastName"":""Doe"",""Age"":32}},""ValidationType"":""ValidationType1""}]}],""FormId"":""theFormId"",""ReplaceValidationSummary"":false,""ValidationSummaryId"":""validationSummary""}"; Assert.Equal(expected, jsonMetadata); }
/// <summary> /// before mvc3 /// </summary> /// <param name="htmlHelper"></param> /// <param name="column"></param> /// <param name="modelName"></param> /// <returns></returns> private static FieldValidationMetadata ApplyFieldValidationMetadata(HtmlHelper htmlHelper, IColumn column, string modelName) { FieldValidationMetadata validationMetadataForField = htmlHelper.ViewContext.FormContext.GetValidationMetadataForField(modelName, true); if (column.DataType == DataType.Int || column.DataType == DataType.Decimal) { validationMetadataForField.ValidationRules.Add(new ModelClientValidationRule { ValidationType = "number", ErrorMessage = string.Format(SR.GetString("ClientDataTypeModelValidatorProvider_FieldMustBeNumeric"), column.Name) }); } if (column.Validations != null) { foreach (var validation in column.Validations) { foreach (var clientValidation in validation.GetClientValidationRule(column.Name)) { validationMetadataForField.ValidationRules.Add(clientValidation); } } } return(validationMetadataForField); }
public void StubFieldValidation(string prop, FieldValidationMetadata fieldValidation) { var formContext = new FormContext(); formContext.FieldValidators.Add(prop, fieldValidation); this.viewContext.Setup(r => r.FormContext).Returns(formContext); }
private static FieldValidationMetadata ApplyFieldValidationMetadata( HtmlHelper htmlHelper, ModelMetadata modelMetadata, string modelName ) { FormContext formContext = htmlHelper.ViewContext.FormContext; FieldValidationMetadata fieldMetadata = formContext.GetValidationMetadataForField( modelName, true /* createIfNotFound */ ); // write rules to context object IEnumerable <ModelValidator> validators = ModelValidatorProviders.Providers.GetValidators( modelMetadata, htmlHelper.ViewContext ); foreach ( ModelClientValidationRule rule in validators.SelectMany( v => v.GetClientValidationRules() ) ) { fieldMetadata.ValidationRules.Add(rule); } return(fieldMetadata); }
public void FieldNameProperty() { // Arrange FieldValidationMetadata metadata = new FieldValidationMetadata(); // Act & assert MemberHelper.TestStringProperty(metadata, "FieldName", String.Empty); }
public void FieldNameProperty() { // Arrange FieldValidationMetadata metadata = new FieldValidationMetadata(); // Act & assert MemberHelper.TestStringProperty(metadata, "FieldName", "", false /* testDefaultValue */); }
private static MvcHtmlString ValidationMessageHelper(this HtmlHelper htmlHelper, ModelMetadata modelMetadata, string expression, string validationMessage, IDictionary <string, object> htmlAttributes) { string modelName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(expression); FormContext formContext = htmlHelper.ViewContext.GetFormContextForClientValidation(); if (!htmlHelper.ViewData.ModelState.ContainsKey(modelName) && formContext == null) { return(null); } ModelState modelState = htmlHelper.ViewData.ModelState[modelName]; ModelErrorCollection modelErrors = (modelState == null) ? null : modelState.Errors; ModelError modelError = (((modelErrors == null) || (modelErrors.Count == 0)) ? null : modelErrors.FirstOrDefault(m => !String.IsNullOrEmpty(m.ErrorMessage)) ?? modelErrors[0]); if (modelError == null && formContext == null) { return(null); } TagBuilder builder = new TagBuilder("span"); builder.MergeAttributes(htmlAttributes); builder.AddCssClass((modelError != null) ? HtmlHelper.ValidationMessageCssClassName : HtmlHelper.ValidationMessageValidCssClassName); if (!String.IsNullOrEmpty(validationMessage)) { builder.SetInnerText(validationMessage); } else if (modelError != null) { builder.SetInnerText(GetUserErrorMessageOrDefault(htmlHelper.ViewContext.HttpContext, modelError, modelState)); } if (formContext != null) { bool replaceValidationMessageContents = String.IsNullOrEmpty(validationMessage); if (htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled) { builder.MergeAttribute("data-valmsg-for", modelName); builder.MergeAttribute("data-valmsg-replace", replaceValidationMessageContents.ToString().ToLowerInvariant()); } else { FieldValidationMetadata fieldMetadata = ApplyFieldValidationMetadata(htmlHelper, modelMetadata, modelName); // rules will already have been written to the metadata object fieldMetadata.ReplaceValidationMessageContents = replaceValidationMessageContents; // only replace contents if no explicit message was specified // client validation always requires an ID builder.GenerateId(modelName + "_validationMessage"); fieldMetadata.ValidationMessageId = builder.Attributes["id"]; } } return(builder.ToMvcHtmlString(TagRenderMode.Normal)); }
public ModelClientMetadataBuilder <TModel> Validate(string element, FieldValidationMetadata metadata) { var item = GetValidationMetadataForField(element, false); if (item == null) { this.FieldValidators.Add(element, metadata); } return(this); }
public void ValidationRulesProperty() { // Arrange FieldValidationMetadata metadata = new FieldValidationMetadata(); // Act ICollection<ModelClientValidationRule> validationRules = metadata.ValidationRules; // Assert Assert.IsNotNull(validationRules); Assert.AreEqual(0, validationRules.Count); }
public void GetValidationMetadataForField_NoCreate_ReturnsNullIfNotFound() { // Arrange FormContext context = new FormContext(); // Act FieldValidationMetadata result = context.GetValidationMetadataForField("fieldName"); // Assert Assert.Null(result); }
private void AppendFieldValidationMetadata(string element, ModelMetadata modelMetadata) { FieldValidationMetadata fieldMetadata = GetValidationMetadataForField(element, true /* createIfNotFound */); // write rules to context object IEnumerable <ModelValidator> validators = ModelValidatorProviders.Providers.GetValidators(modelMetadata, new ViewContext()); foreach (ModelClientValidationRule rule in validators.SelectMany(v => v.GetClientValidationRules())) { fieldMetadata.ValidationRules.Add(rule); } }
public void ValidationRulesProperty() { // Arrange FieldValidationMetadata metadata = new FieldValidationMetadata(); // Act ICollection<ModelClientValidationRule> validationRules = metadata.ValidationRules; // Assert Assert.NotNull(validationRules); Assert.Empty(validationRules); }
public void ValidationRulesProperty() { // Arrange FieldValidationMetadata metadata = new FieldValidationMetadata(); // Act ICollection <ModelClientValidationRule> validationRules = metadata.ValidationRules; // Assert Assert.IsNotNull(validationRules); Assert.AreEqual(0, validationRules.Count); }
public void ValidationRulesProperty() { // Arrange FieldValidationMetadata metadata = new FieldValidationMetadata(); // Act ICollection <ModelClientValidationRule> validationRules = metadata.ValidationRules; // Assert Assert.NotNull(validationRules); Assert.Empty(validationRules); }
private static FieldValidationMetadata ApplyFieldValidationMetadata(HtmlHelper htmlHelper, ModelMetadata modelMetadata, string modelName) { FieldValidationMetadata validationMetadataForField = htmlHelper.ViewContext.FormContext.GetValidationMetadataForField(modelName, true); foreach (IEnumerable <ModelClientValidationRule> rules in (from v in modelMetadata.GetValidators(htmlHelper.ViewContext.Controller.ControllerContext) select v.GetClientValidationRules())) { foreach (var rule in rules) { validationMetadataForField.ValidationRules.Add(rule); } } return(validationMetadataForField); }
public void GetValidationMetadataForField_NoCreate_ReturnsMetadataIfFound() { // Arrange FormContext context = new FormContext(); FieldValidationMetadata metadata = new FieldValidationMetadata(); context.FieldValidators["fieldName"] = metadata; // Act FieldValidationMetadata result = context.GetValidationMetadataForField("fieldName"); // Assert Assert.NotNull(result); Assert.Equal(metadata, result); }
private static FieldValidationMetadata EncodeRegularExpressionValidators(FieldValidationMetadata metadata) { metadata.ValidationRules.Each(validationRule => { if (validationRule.ValidationType == "regularExpression" || validationRule.ValidationType == "regex") { if (validationRule.ValidationParameters.ContainsKey("pattern")) { validationRule.ValidationParameters["pattern"] = new JavaScriptSerializer().Serialize(validationRule.ValidationParameters["pattern"]).Trim('"'); } } }); return(metadata); }
public void GetValidationMetadataForField_Create_CreatesNewMetadataIfNotFound() { // Arrange FormContext context = new FormContext(); // Act FieldValidationMetadata result = context.GetValidationMetadataForField("fieldName", true /* createIfNotFound */); // Assert Assert.IsNotNull(result); Assert.AreEqual("fieldName", result.FieldName); Assert.AreEqual(1, context.FieldValidators.Count, "New metadata should have been added to FieldValidators."); Assert.AreEqual(result, context.FieldValidators["fieldName"]); }
public void GetValidationMetadataForField_Create_CreatesNewMetadataIfNotFound() { // Arrange FormContext context = new FormContext(); // Act FieldValidationMetadata result = context.GetValidationMetadataForField("fieldName", true /* createIfNotFound */); // Assert Assert.NotNull(result); Assert.Equal("fieldName", result.FieldName); Assert.Single(context.FieldValidators); Assert.Equal(result, context.FieldValidators["fieldName"]); }
public static IHtmlString ValidationMessageForColumn(this HtmlHelper htmlHelper, IColumn column, IDictionary <string, object> htmlAttributes) { var validationMessage = ""; string fullHtmlFieldName = column.Name; FormContext formContextForClientValidation = null; if (htmlHelper.ViewContext.ClientValidationEnabled) { formContextForClientValidation = htmlHelper.ViewContext.FormContext; } ModelState modelState = htmlHelper.ViewData.ModelState[fullHtmlFieldName]; ModelErrorCollection errors = (modelState == null) ? null : modelState.Errors; ModelError error = ((errors == null) || (errors.Count == 0)) ? null : errors[0]; if ((error == null) && (formContextForClientValidation == null)) { return(null); } TagBuilder builder = new TagBuilder("span"); builder.MergeAttributes <string, object>(htmlAttributes); builder.AddCssClass((error != null) ? HtmlHelper.ValidationMessageCssClassName : HtmlHelper.ValidationMessageValidCssClassName); if (!string.IsNullOrEmpty(validationMessage)) { builder.SetInnerText(validationMessage); } else if (error != null) { builder.SetInnerText(GetUserErrorMessageOrDefault(htmlHelper.ViewContext.HttpContext, error, modelState)); } if (formContextForClientValidation != null) { bool replaceValidationMessageContents = String.IsNullOrEmpty(validationMessage); if (htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled) { builder.MergeAttribute("data-valmsg-for", fullHtmlFieldName); builder.MergeAttribute("data-valmsg-replace", replaceValidationMessageContents.ToString().ToLowerInvariant()); } else { builder.GenerateId(fullHtmlFieldName + "_validationMessage"); FieldValidationMetadata metadata = ApplyFieldValidationMetadata(htmlHelper, column, fullHtmlFieldName); metadata.ReplaceValidationMessageContents = string.IsNullOrEmpty(validationMessage); metadata.ValidationMessageId = builder.Attributes["id"]; } } return(new HtmlString(builder.ToString(TagRenderMode.Normal))); }
FieldValidationMetadata GetValidationMetadataForField(string fieldName, bool createIfNotFound) { //if (String.IsNullOrEmpty(fieldName)) //{ // throw Error.ParameterCannotBeNullOrEmpty("fieldName"); //} FieldValidationMetadata metadata; if (!FieldValidators.TryGetValue(fieldName, out metadata)) { if (createIfNotFound) { metadata = new FieldValidationMetadata() { FieldName = fieldName }; FieldValidators[fieldName] = metadata; } } return(metadata); }
private bool IsBooleanField(FieldValidationMetadata validationMetadata) { ModelMetadata modelMetadata = ModelMetadata.FromStringExpression(validationMetadata.FieldName, ViewContext.ViewData); return(modelMetadata.ModelType != typeof(bool)); }
public static IHtmlString ValidationMessage(this HtmlHelper htmlHelper, ModelMetadata modelMetadata, IDictionary <string, object> htmlAttributes) { htmlAttributes = htmlAttributes ?? new RouteValueDictionary(); var validationMessage = ""; string fullHtmlFieldName = htmlAttributes["name"] == null ? modelMetadata.PropertyName : htmlAttributes["name"].ToString(); if (!string.IsNullOrEmpty(htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix)) { fullHtmlFieldName = htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix + "." + fullHtmlFieldName; } FormContext formContextForClientValidation = htmlHelper.ViewContext.FormContext; //if (htmlHelper.ViewContext.ClientValidationEnabled) //{ // formContextForClientValidation = htmlHelper.ViewContext.FormContext; //} //if (!htmlHelper.ViewData.ModelState.ContainsKey(fullHtmlFieldName) && (formContextForClientValidation == null)) //{ // return null; //} ModelState modelState = htmlHelper.ViewData.ModelState[fullHtmlFieldName]; ModelErrorCollection errors = (modelState == null) ? null : modelState.Errors; ModelError error = ((errors == null) || (errors.Count == 0)) ? null : errors[0]; if ((error == null) && (formContextForClientValidation == null)) { return(null); } TagBuilder builder = new TagBuilder("span"); builder.MergeAttributes <string, object>(htmlAttributes); builder.AddCssClass((error != null) ? HtmlHelper.ValidationMessageCssClassName : HtmlHelper.ValidationMessageValidCssClassName); if (!string.IsNullOrEmpty(validationMessage)) { builder.SetInnerText(validationMessage); } else if (error != null) { builder.SetInnerText(GetUserErrorMessageOrDefault(htmlHelper.ViewContext.HttpContext, error, modelState)); } if (formContextForClientValidation != null) { bool replaceValidationMessageContents = String.IsNullOrEmpty(validationMessage); FieldValidationMetadata fieldMetadata = ApplyFieldValidationMetadata(htmlHelper, modelMetadata, fullHtmlFieldName); // rules will already have been written to the metadata object fieldMetadata.ReplaceValidationMessageContents = replaceValidationMessageContents; // only replace contents if no explicit message was specified if (htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled) { builder.MergeAttribute("data-valmsg-for", fullHtmlFieldName); builder.MergeAttribute("data-valmsg-replace", replaceValidationMessageContents.ToString().ToLowerInvariant()); } else { // client validation always requires an ID builder.GenerateId(fullHtmlFieldName + "_validationMessage"); fieldMetadata.ValidationMessageId = builder.Attributes["id"]; } } //if (formContext != null) //{ // bool replaceValidationMessageContents = String.IsNullOrEmpty(validationMessage); // FieldValidationMetadata fieldMetadata = ApplyFieldValidationMetadata(htmlHelper, modelMetadata, modelName); // // rules will already have been written to the metadata object // fieldMetadata.ReplaceValidationMessageContents = replaceValidationMessageContents; // only replace contents if no explicit message was specified // if (htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled) // { // builder.MergeAttribute("data-valmsg-for", modelName); // builder.MergeAttribute("data-valmsg-replace", replaceValidationMessageContents.ToString().ToLowerInvariant()); // } // else // { // // client validation always requires an ID // builder.GenerateId(modelName + "_validationMessage"); // fieldMetadata.ValidationMessageId = builder.Attributes["id"]; // } //} return(new HtmlString(builder.ToString(TagRenderMode.Normal))); }