5

Tengo un ValidationAttribute que he creado que se comparte entre el servidor y el cliente. Para que el atributo de validación se genere correctamente en el cliente cuando se hace referencia a él en una clase de ayudante de datos, tenía que ser muy específico en la forma en que lo construí.validaciónErrores de ValidationAttribute personalizado no se muestra correctamente

El problema que tengo es que, por algún motivo, cuando devuelvo un ValidationResult de mi clase de atributo de validación personalizada, no se gestiona igual que otros atributos de validación en la interfaz de usuario del cliente. En lugar de mostrar el error, no hace nada. Sin embargo, validará correctamente el objeto, simplemente no muestra el resultado de la validación fallida.

A continuación se muestra el código de una de mis clases de validación personalizadas.

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.ComponentModel.DataAnnotations; 

namespace Project.Web.DataLayer.ValidationAttributes 
{ 
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] 
    public class DisallowedChars : ValidationAttribute 
    { 
     public string DisallowedCharacters 
     { 
      get 
      { 
       return new string(this.disallowedCharacters); 
      } 

      set 
      { 
       this.disallowedCharacters = (!this.CaseSensitive ?  value.ToLower().ToCharArray() : value.ToCharArray()); 
      } 
     } 

     private char[] disallowedCharacters = null; 

     private bool caseSensitive; 

     public bool CaseSensitive 
     { 
      get 
      { 
       return this.caseSensitive; 
      } 

      set 
      { 
       this.caseSensitive = value; 
      } 
     } 

     protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
     { 
      if (value != null && this.disallowedCharacters.Count() > 0) 
      { 
       string Value = value.ToString(); 

       foreach(char val in this.disallowedCharacters) 
       { 
        if ((!this.CaseSensitive && Value.ToLower().Contains(val)) ||  Value.Contains(val)) 
        { 
         return new ValidationResult(string.Format(this.ErrorMessage != null ? this.ErrorMessage : "'{0}' is not allowed an allowed character.", val.ToString())); 
        } 
       } 
      } 

      return ValidationResult.Success; 
     } 
    } 
} 

Así es como lo uso sobre mis Propiedades tanto en el servidor como en el cliente.

[DisallowedChars(DisallowedCharacters = "=")] 

Y he intentado varias formas diferentes de configurar el encuadernado.

{Binding Value, NotifyOnValidationError=True} 

Así como

{Binding Value, NotifyOnValidationError=True, ValidatesOnDataErrors=True, ValidatesOnExceptions=True, ValidatesOnNotifyDataErrors=True} 

Ninguno de ellos parece tener las formas que están obligados también validar las entradas. Intenté usar este atributo en valores que están vinculados a TextBoxes, XamGrids, y ninguno de los que valida correctamente como deberían.

Este problema solo parece ser cuando estoy intentando usar el ValidationResult en el lado del servidor. Si utilizo el resultado de validación en un valor en mi modelo de vista, se validará correctamente. Sin embargo, tengo que encontrar la manera de validarlo correctamente a partir del código generado.

Cualquier idea sería muy apreciada.

Respuesta

4

Debe especificar los MemberNames que están asociados con ValidationResult. El constructor de ValidationResult tiene un parámetro adicional para especificar las propiedades que están asociadas con el resultado. Si no especifica ninguna propiedad, el resultado se maneja como un error de validación en el nivel de la entidad.

Por lo tanto, en su caso, se debe corregir, cuando se pasa el nombre de la propiedad al constructor del ValidationResult.

protected override ValidationResult IsValid(object value, ValidationContext validationContext) { 
if (value != null && this.disallowedCharacters.Count() > 0) { 
    string Value = value.ToString(); 

    foreach(char val in this.disallowedCharacters) { 
    if ((!this.CaseSensitive && Value.ToLower().Contains(val)) || Value.Contains(val)) { 
     //return new ValidationResult(string.Format(this.ErrorMessage != null ? this.ErrorMessage : "'{0}' is not allowed an allowed character.", val.ToString())); 
     string errorMessage = string.Format(this.ErrorMessage != null ? this.ErrorMessage : "'{0}' is not allowed an allowed character.", val.ToString()); 
     return new ValidationResult(errorMessage, new string[] { validationContext.MemberName}); 
    } 
    } 
} 

return ValidationResult.Success; 
} 

Para las encuadernaciones no necesita especificar nada más. Por lo que la unión sencilla

{Binding Value} 

debe mostrar errores, causa ValidatesOnNotifyDataErrors se establece en true de forma implícita. NotifyOnValidationError rellena ValidationErrors a otros elementos como ValidationSummary.

Jeff Handly tiene una realmente goog blog post sobre Validación en WCF Ria Services y Silverlight, puedo recomendar para leer.

+0

Muchas gracias. Eso solucionó mi problema. –

Cuestiones relacionadas