validate mvc isvalid for errors dataannotations custom asp asp.net-mvc validation model

asp.net-mvc - isvalid - mvc required field validation



No se puede aplicar la validaciĆ³n personalizada en Asp.Net MVC Model (1)

Así que tengo este problema. Tengo 2 campos: Date of birth y Date of birth Start working date . Deseo aplicar una validación personalizada después de esto si

comenzar la fecha de trabajo - fecha de nacimiento es> = 22

entonces es válido. Así que aquí está mi código

[AttributeUsage(AttributeTargets.Property)] public class MiniumAgeAttribute:ValidationAttribute { private DateTime dob { get; set; } private DateTime startDate { get; set; } public MiniumAgeAttribute(DateTime DOB, DateTime StartDate) { dob = DOB; startDate = StartDate; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { int age; age = startDate.Year - dob.Year; if (age >= 22) { return ValidationResult.Success; } else { return new ValidationResult("Age is required to be 22 or more"); } } }

Pero cuando aplico mis reglas de validación en el modelo obtengo este error.

Entonces, ¿cómo puedo solucionarlo? Saludo cordial.


Los atributos son metadatos y deben conocerse en tiempo de compilación y, por lo tanto, deben ser constantes. No puede pasar el valor de una propiedad que no se conoce hasta el tiempo de ejecución. En cambio, pasa el nombre de la propiedad y utiliza el reflejo para obtener el valor de la propiedad.

Normalmente decora una propiedad modelo con el atributo, por lo que solo es necesario pasar el nombre de la otra propiedad, no tanto dob como startDate . Además, su atributo no permite flexibilidad porque ha codificado la edad en el método, y ese valor también debe pasarse al método para que pueda usarse como (por ejemplo)

[MiminumAge(22, "DateOfBirth")] // or [MiminumAge(18, "DateOfBirth")] public DateTime StartDate { get; set; } public DateTime DateOfBirth { get; set; }

startDate.Year - dob.Year lógica también es incorrecta porque startDate.Year - dob.Year no tiene en cuenta los valores de día y mes de las fechas.

Tu atributo debe ser

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public class MiminumAgeAttribute : ValidationAttribute { private const string _DefaultErrorMessage = "You must be at least {0} years of age."; private readonly string _DOBPropertyName; private readonly int _MinimumAge; public MiminumAgeAttribute (string dobPropertyName, int minimumAge) { if (string.IsNullOrEmpty(dobPropertyName)) { throw new ArgumentNullException("propertyName"); } _DOBPropertyName= dobPropertyName; _MinimumAge = minimumAge; ErrorMessage = _DefaultErrorMessage; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { DatetTime startDate; DateTime dateOfBirth; bool isDateValid = DateTime.TryParse((string)value, out startDate); var dobPropertyName = validationContext.ObjectInstance.GetType().GetProperty(_DOBPropertyName); var dobPropertyValue = dobPropertyName.GetValue(validationContext.ObjectInstance, null); isDOBValid = DateTime.TryParse((string)dobPropertyValue, out dateOfBirth); if (isDateValid && isDOBValid) { int age = startDate.Year - dateOfBirth.Year; if (dateOfBirth > startDate.AddYears(-age)) { age--; } if (age < _MinimumAge) { return new ValidationResult(string.Format(ErrorMessageString, _MinimumAge)); } } return ValidationResult.Success; } }

También puede mejorar esto implementando IClientValidatable y agregando scripts a la vista para darle una validación del lado del cliente usando los jquery.validate.js y jquery.validate.unobtrusive.js . Para obtener más detalles, consulte LA GUÍA COMPLETA PARA LA VALIDACIÓN EN ASP.NET MVC 3 - PARTE 2