validar vacios solo sintaxis regulares numeros net mvc letras formulario expresiones data comentarios campos asp c# asp.net validation asp.net-core asp.net-core-mvc

c# - vacios - validar solo letras en mvc



ASP.Net Core MVC-ValidaciĆ³n del lado del cliente para atributo personalizado (1)

En versiones anteriores del marco MVC, la validación personalizada se lograría mediante la implementación de IClientValidatable y el método GetClientValidationRules .

Sin embargo, en ASP.Net Core MVC no tenemos esta interfaz , aunque sí tenemos IClientModelValidator que define un método muy similar. La implementación de la que nunca se llama sin embargo.

Entonces, ¿cómo implementamos la validación del lado del cliente para un atributo personalizado en ASP.NET Core MVC?


El IClientModelValidator es, de hecho, la interfaz correcta. He hecho una implementación de ejemplo artificial a continuación.

Nota: Hubo un cambio importante en la interfaz de IClientModelValidator entre RC1 y RC2. Ambas opciones se presentan a continuación: el resto del código es el mismo entre ambas versiones.

Atributo (RC2 y más allá)

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] public sealed class CannotBeRedAttribute : ValidationAttribute, IClientModelValidator { public override bool IsValid(object value) { var message = value as string; return message?.ToUpper() == "RED"; } public void AddValidation(ClientModelValidationContext context) { MergeAttribute(context.Attributes, "data-val", "true"); var errorMessage = FormatErrorMessage(context.ModelMetadata.GetDisplayName()); MergeAttribute(context.Attributes, "data-val-cannotbered", errorMessage); } private bool MergeAttribute( IDictionary<string, string> attributes, string key, string value) { if (attributes.ContainsKey(key)) { return false; } attributes.Add(key, value); return true; } }

Atributo (RC1)

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] public sealed class CannotBeRedAttribute : ValidationAttribute, IClientModelValidator { public override bool IsValid(object value) { var message = value as string; return message?.ToUpper() == "RED"; } public IEnumerable<ModelClientValidationRule> GetClientValidationRules( ClientModelValidationContext context) { yield return new ModelClientValidationRule( "cannotbered", FormatErrorMessage(ErrorMessage)); } }

Modelo

public class ContactModel { [CannotBeRed(ErrorMessage = "Red is not allowed!")] public string Message { get; set; } }

Ver

@model WebApplication22.Models.ContactModel <form asp-action="Contact" method="post"> <label asp-for="Message"></label> <input asp-for="Message" /> <span asp-validation-for="Message"></span> <input type="submit" value="Save" /> </form> @section scripts { <script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script> <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script> <script> $.validator.addMethod("cannotbered", function (value, element, parameters) { return value.toUpperCase() !== "RED"; }); $.validator.unobtrusive.adapters.add("cannotbered", [], function (options) { options.rules.cannotbered = {}; options.messages["cannotbered"] = options.message; }); </script> }