logo
Tags down

shadow

Custom formatting of validation summary and errors


By : franfaccin
Date : October 17 2020, 01:08 AM
should help you out Here are some extension points that you can consider to provide custom rendering for validation summary and field validation errors:
Customize existing validation tag helpers (Register new IHtmlGenerator) Create new validation tag helpers (Register new Tag Helpers) Customize existing validation tag helpers
code :
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddTransient<IHtmlGenerator, MyHtmlGenerator>();
}
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Mvc.ViewFeatures.Internal;
using Microsoft.Extensions.Options;
using System.Text.Encodings.Web;

namespace ValidationSampleWebApplication
{
    public class MyHtmlGenerator : DefaultHtmlGenerator
    {
        public MyHtmlGenerator(IAntiforgery antiforgery, IOptions<MvcViewOptions> optionsAccessor, IModelMetadataProvider metadataProvider, IUrlHelperFactory urlHelperFactory, HtmlEncoder htmlEncoder, ValidationHtmlAttributeProvider validationAttributeProvider) 
            : base(antiforgery, optionsAccessor, metadataProvider, urlHelperFactory, htmlEncoder, validationAttributeProvider)
        {
        }
        public override TagBuilder GenerateValidationMessage(ViewContext viewContext, ModelExplorer modelExplorer, string expression, string message, string tag, object htmlAttributes)
        {
            return base.GenerateValidationMessage(viewContext, modelExplorer, expression, message, tag, htmlAttributes);
        }
        public override TagBuilder GenerateValidationSummary(ViewContext viewContext, bool excludePropertyErrors, string message, string headerTag, object htmlAttributes)
        {
            return base.GenerateValidationSummary(viewContext, excludePropertyErrors, message, headerTag, htmlAttributes);
        }
    }
}
@using ValidationSampleWebApplication
@using ValidationSampleWebApplication.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, ValidationSampleWebApplication
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using Microsoft.AspNetCore.Mvc.TagHelpers;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace ValidationSampleWebApplication
{
    [HtmlTargetElement("div", Attributes = MyValidationForAttributeName)]
    public class MyValidationTagHelper : TagHelper
    {
        private const string MyValidationForAttributeName = "asp-myvalidation-for";

        [HtmlAttributeNotBound]
        [ViewContext]
        public ViewContext ViewContext { get; set; }

        [HtmlAttributeName(MyValidationForAttributeName)]
        public ModelExpression For { get; set; }
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            base.Process(context, output);
            ModelStateEntry entry;
            ViewContext.ViewData.ModelState.TryGetValue(For.Name, out entry);
            if (entry != null && entry.Errors.Count > 0)
            {
                var builder = new TagBuilder("div");
                builder.AddCssClass("hasError");
                output.MergeAttributes(builder);   
            }
        }
    }
}
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using Microsoft.AspNetCore.Mvc.TagHelpers;

namespace ValidationSampleWebApplication
{
    [HtmlTargetElement("div", Attributes = ValidationForAttributeName)]
    public class MytValidationMessageTagHelper : ValidationMessageTagHelper
    {
        private const string ValidationForAttributeName = "asp-validation-for";
        public MytValidationMessageTagHelper(IHtmlGenerator generator) : base(generator)
        {
        }
    }
}


Share : facebook icon twitter icon

displaying custom message on custom errors in validation summary control on client side?


By : user3211707
Date : March 29 2020, 07:55 AM
Does that help The key is to use the Custom Validation control. This control supports client side scripting (so you can still use your javascript code to do it) but still ties into the validation framework asp.net provides.
From the microsoft article, something like this:
code :
<SCRIPT LANGUAGE="JavaScript">
function validateLength(oSrc, args){
   args.IsValid = (args.Value.length >= 8);
}
</SCRIPT>

<asp:Textbox id="text1" runat="server" text="">
</asp:Textbox>

<asp:CustomValidator id="CustomValidator1" runat=server 
      ControlToValidate = "text1"
      ErrorMessage = "You must enter at least 8 characters!"
   ClientValidationFunction="validateLength" >
</asp:CustomValidator>

Return Custom Errors to ajax post error function from JsonResult Method and display it under Validation Summary


By : 陈伟城
Date : March 29 2020, 07:55 AM
seems to work fine From my understanding, when you do an ajax post, it doesn't care if the Model Validation passed or not, it only cares if it got a response from the server. If an Exception gets thrown from the server, then it will hit your ajax error function.
So what I would do is return a json object that lets me know the validation status.
code :
if(!ModelState.IsValid){
        var modelStateErrors = this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors);
        var message = "Please fix the following: " + Environment.NewLine;

        foreach (var modelStateError in modelStateErrors)
        {
            message += modelStateError.ErrorMessage + Environment.NewLine;
        }

     return Json(new {success = false, response = message})
}


 // Do other logic

return Json(new {success = true, response = "Successful message"})
success: function (result) {
            if(result.success === true){
                 $('#status-div').empty().html('<div class="success">' + result.response + '</div>');
            }
            if(result.success === false){
                 $('#status-div').empty().html('<div class="fail">' + result.response + '</div>');
            }

        }

Removing <ul> <li> tag in validation-summary-errors


By : Mali Abhijit
Date : March 29 2020, 07:55 AM
should help you out I have this site that the error message is on this format , Apply list-style property on ul not li. So try something like this
code :
.validation-summary-errors ul { 
        list-style: none;
        margin-left:-40px
    }

Knockout Validation: Validation Summary displays required field errors at page load even though no edits were made


By : ashswet
Date : March 29 2020, 07:55 AM
wish help you to fix your issue I found a way to filter for errors corresponding to modified observables.
code :
  self.visibleErrors = ko.computed(function() {
    var errors = [];
    self.errors.forEach(function(observable) {
      if (ko.validation.utils.isValidatable(observable) && !observable.isValid() && observable.isModified()) {
        errors.push(observable.error.peek());
      }
    })
    return errors;
  });

asp-validation-summary shows custom but not model errors


By : Minhazul Hossain
Date : March 29 2020, 07:55 AM
it should still fix some issue Asp-validation-summary in view shows errors added via ModelState.AddModelError, but don't show any model validation errors ("The User field is required."). I'm using Microsoft.AspNetCore.Mvc 1.0.0-rc2-final. Btw: User field is not displayed via the view but correctly identified by EF as a model level error before add. , Change your html:
Related Posts Related Posts :
  • How to add a property that will be passed through more than one class
  • Programmatically check authenticoded files in NuGet Package
  • Using properties depending of the content of a class
  • MSTest Unit Test Adapter Failing to Connect to Data Source When Tests From New Test Project Are Introduced to Solution
  • AForge download comes with no .dll files, how to use it?
  • LINQ to DataSet multi-table left join
  • after migrate to .net core 2.0 session stop working correctly
  • How to make sure a user completes their profile in aspnet core 2.0?
  • Is rapidly creating BouncyCastle SecureRandom instances problematic?
  • Cannot display Fetched JSON data from Web API call since backslashes are in response
  • C# - Responsive Winforms application positioning of pictureboxes
  • How to wait for response from NamedPipeServer?
  • What's the user parameter to PasswordHasher's methods used for?
  • How to show an exception message if the user doesn't check a radio button in Xamarin Android?
  • Left Align UICollectionView Cell When it has one item in Xamarin.ios
  • Entity Framework Core - First returning duplicate results after migrating to .net core
  • LINQ Query to put data in a nested object
  • Chart bind to non-primitive type
  • ASP.NET Core 2 - global filters registration multiple ways?
  • How do i get my check boxes to display and add numbers into a label on C#
  • IIS Express bad hostname android studio
  • Combining Frames of a Tiff into a single png gives Out of Memory Exception C#
  • Return HTML from ASP.NET Web API ASP.NET Core 2 and get http status 406
  • When inheriting a base class, is there a reason why C# defaults to new instead of override?
  • Simulator mode hangs at Registering the application to run from layout
  • Multiple ExpectedException in MsTest
  • JSON Differing names
  • Keeping hexadecimal characters of a xml file unchanged after save?
  • How do you test Azure Queue trigger functions locally?
  • OfficeOpenXML excel Resize rows with cells merged across them
  • Get the length of jsonResults.Data in C#
  • Does Stopwatch have a maximum time it can run?
  • How do you add two values into a list as one key? C#
  • How can I UPDATE specific GridView columns based on a CheckBox in one column
  • Delete where in clause in sqlite
  • MSBuild failing. Missing Release/WinRTXamlToolkit
  • binding an asp.net checkbox on serverside
  • WPF Datagrid Column Visibility not working with MultiBinding
  • Why am I getting error CS0116 when building using a .rsp file?
  • OpenFileDialog on .NET Core
  • c# - Auto increment in sqlite stops at number 10
  • How to access specific controls in a ASP.Net Repeater
  • Is it possible to use a file upload control to upload only image and video type of file at one time?
  • Linq left joining 3 tables
  • Bind UI values to object instance of model in WPF
  • C# beginner - Callback in the same function
  • Outlook AddIn for filtering recipients
  • C# web form - Looking to get the date of the first monday of the month after the selected date from the calendar
  • C# tcp async listener gets stuck on my on_receive callback after client closes socket
  • For Input.Gettouch(0).phase==TouchPhase.Moved , How to store all touch positions in a array?
  • WPF, Telerik: Change control style when disabled
  • Publishing a .NET Core / Angular 4 Project to Netlify
  • Exclude folder in ASP.NET Core 2
  • Binding background of datatemplate in contentcontrol
  • How to access inner stringified JSON data using JavaScriptSerializer
  • Creating COM interface pointer in DLL method works when called from one application but does not when called from anothe
  • C# post chunks of ids and merge response using async and await
  • Event initialization on declaration
  • How to validate a DbType.Guid as a Valid Parameter before calling a stored procedure?
  • Weird symbols instead of cyrillic
  • shadow
    Privacy Policy - Terms - Contact Us © soohba.com