Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

155
Views
Realizar la validación del lado del cliente para el atributo personalizado

He creado un atributo de validación personalizado:

 public class FutureDateAttribute : ValidationAttribute { public override bool IsValid(object value) { if (value == null|| (DateTime)value < DateTime.Now) return false; return true; } }

¿Cómo puedo hacer que esto funcione también en el lado del cliente con jquery?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

He aquí cómo proceder:

Comience definiendo el atributo de validación personalizado:

 public class FutureDateAttribute : ValidationAttribute, IClientValidatable { public override bool IsValid(object value) { if (value == null || (DateTime)value < DateTime.Now) return false; return true; } public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { yield return new ModelClientValidationRule { ErrorMessage = this.ErrorMessage, ValidationType = "futuredate" }; } }

Observe cómo implementa IClientValidatable . A continuación escribimos nuestro modelo:

 public class MyViewModel { [FutureDate(ErrorMessage = "Should be in the future")] public DateTime Date { get; set; } }

Entonces un controlador:

 public class HomeController : Controller { public ActionResult Index() { return View(new MyViewModel { // intentionally put in the past Date = DateTime.Now.AddDays(-1) }); } [HttpPost] public ActionResult Index(MyViewModel model) { return View(model); } }

y finalmente una vista:

 @using (Html.BeginForm()) { @Html.LabelFor(x => x.Date) @Html.TextBoxFor(x => x.Date) @Html.ValidationMessageFor(x => x.Date) <input type="submit" value="OK" /> }

La última parte para que ocurra la magia es definir el adaptador personalizado:

 <script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script> <script type="text/javascript"> // we add a custom jquery validation method jQuery.validator.addMethod('greaterThan', function (value, element, params) { if (!/Invalid|NaN/.test(new Date(value))) { return new Date(value) > new Date($(params).val()); } return isNaN(value) && isNaN($(params).val()) || (parseFloat(value) > parseFloat($(params).val())); }, ''); // and an unobtrusive adapter jQuery.validator.unobtrusive.adapters.add('futuredate', { }, function (options) { options.rules['greaterThan'] = true; options.messages['greaterThan'] = options.message; }); </script>
over 4 years ago · Santiago Trujillo Report

0

Tomó un poco de tiempo desde que se hizo su pregunta, pero si todavía le gustan los metadatos y todavía está abierto a alternativas simplificadas, puede resolver su problema usando las siguientes anotaciones:

 [Required] [AssertThat("Date > Now()")] public DateTime? Date { get; set; }

Funciona tanto para el servidor como para el cliente, listo para usar. Para obtener más detalles, consulte la biblioteca ExpressiveAnnotations .

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!