944 views

CustomValidation ASP.NET

Interfaz

  • Caja de Texto (TextBox)
  • Control CustomValidator
    • Propiedades:
      • ErrorMessage (mensaje a mostrar si falla la validación)
      • ClientValidationFunction (nombre de la función javascript en cliente)
      • ControlToValidate (id de la caja de texto)

Parte cliente (por ejemplo validando que el número introducido debe ser par)

Javascript
  1. function esPar(origen, args){
  2.  
  3.     if (args.Value % 2 == 0)
  4.  
  5.         args.isValid = true;
  6.     else
  7.         args.isValid = false;
  8. }
  9.  

­

Parte servidor, programación del evento ServerValidate del control

C#
  1. CustomValidator
  2.  
  3. protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
  4.     {
  5.  
  6. try
  7.         {
  8.  
  9.  int numero;
  10.  
  11.             numero = int.Parse(args.Value);
  12.             args.IsValid = numero % 2 == 0;
  13.  
  14.         }
  15.         catch (Exception)
  16.         {
  17.             args.IsValid = false;
  18.             throw;
  19.         }
  20.     }
  21.  

­

Tags: C# JavaScript asp.net .net custom validation

Embed: