Validación de DataAnnotations (Expresión regular) en asp.net mvc 4-vista de maquinilla de afeitar


El validador de DataAnnotations no funciona en asp.net mvc 4 razor view, cuando se utilizan los caracteres especiales en la expresión regular.

Modelo:

[StringLength(100)]
[Display(Description = "First Name")]
[RegularExpression("^([a-zA-Z0-9 .&'-]+)$", ErrorMessage = "Invalid First Name")]
public string FirstName { get; set; }

Vista de maquinilla de afeitar:

@Html.TextBoxFor(model => Model.FirstName, new { })
@Html.ValidationMessageFor(model => Model.FirstName)

La validación discreta se presenta como:

<input type="text" value="" tabindex="1" style="height:auto;" name="FirstName" maxlength="100" id="FirstName" data-val-regex-pattern="^([a-zA-Z0-9 .&amp;amp;&amp;#39;-]+)$" data-val-regex="Invalid First Name" data-val-length-max="100" data-val-length="The field FirstName must be a string with a maximum length of 100." data-val="true" class="textfield ui-input-text ui-body-d ui-corner-all ui-shadow-inset valid">

El patrón de expresiones regulares en el html anterior no se representa como se especifica en la RegularExpression del Modelo, lo que resulta en error incluso al ingresar los datos válidos (Sam's).

¿Cómo puedo manejar ¿esto?

--ACTUALIZAR {

He actualizado el código según la sugerencia de @Rick

[StringLength(100)]
[Display(Description = "First Name")]
[RegularExpression("([a-zA-Z0-9 .&'-]+)", ErrorMessage = "Enter only alphabets and numbers of First Name")]
public string FirstName { get; set; }

Ver el código fuente muestra lo siguiente:

<input data-val="true" data-val-length="The field FirstName must be a string with a maximum length of 100." data-val-length-max="100" data-val-regex="Enter only alphabets and numbers of First Name" data-val-regex-pattern="([a-zA-Z0-9 .&amp;amp;&amp;#39;-]+)" id="FirstName" maxlength="100" name="FirstName" type="text" value="" />

Todavía tengo el mismo problema.

Author: Prasad, 2011-11-23

8 answers

ACTUALIZACIÓN 9 Julio 2012 - Parece que esto está arreglado en RTM.

  1. Ya implicamos ^ y $ por lo que no es necesario agregarlos. (No parece ser un problema incluirlos, pero no los necesitas)
  2. Esto parece ser un error en ASP.NET MVC 4 / Vista previa / Beta. He abierto un error

Ver el código fuente muestra lo siguiente:

data-val-regex-pattern="([a-zA-Z0-9 .&amp;&#39;-]+)"                  <-- MVC 3
data-val-regex-pattern="([a-zA-Z0-9&#32;.&amp;amp;&amp;#39;-]+)"      <-- MVC 4/Beta

Parece que tenemos doble codificación.

 34
Author: RickAndMSFT,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-21 13:13:27

Intenta escapar de esos caracteres:

[RegularExpression(@"^([a-zA-Z0-9 \.\&\'\-]+)$", ErrorMessage = "Invalid First Name")]
 10
Author: Darin Dimitrov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-23 15:22:37

Intente @ sign al inicio de la expresión. Por lo tanto, no necesitará escribir caracteres de escape, solo copie y pegue la expresión regular en "" y coloque el signo@. Así:

[RegularExpression(@"([a-zA-Z\d]+[\w\d]*|)[a-zA-Z]+[\w\d.]*", ErrorMessage = "Invalid username")]
public string Username { get; set; }
 5
Author: Bahtiyar Özdere,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-07 15:39:30

¿Qué navegador está utilizando? Ingresé su ejemplo y lo intenté tanto en IE8 como en Chrome y se validó bien cuando escribí el valor Sam's

 public class IndexViewModel
 {
    [Required(ErrorMessage="Required")]
    [RegularExpression("^([a-zA-Z0-9 .&'-]+)$", ErrorMessage = "Invalid First Name")]
    public string Name { get; set; }
 }

Cuando inspecciono el DOM usando IE Developer toolbar y Chrome Developer Mode no muestra ningún carácter especial.

 1
Author: Dismissile,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-23 16:13:20

Hemos tenido problemas similares en el pasado (como mencionó TweeZz). En nuestro caso estamos controlando la salida de TextBoxFor por nuestro método de extensión HtmlHelper personalizado que está construyendo MvcHtmlString, allí en un paso necesitamos agregar estos atributos de validación discretos, lo que se hace a través de

var attrs = htmlHelper.GetUnobtrusiveValidationAttributes(name, metadata)

Después de la llamada a este método, los atributos están codificados en html, por lo que simplemente verificamos si había un validador de expresiones regulares allí y, si es así, descodificamos html este atributo y luego los fusionamos en TagBuilder (para construir la etiqueta "input")

if(attrs.ContainsKey("data-val-regex"))
    attrs["data-val-regex"] = ((string)attrs["data-val-regex"]).Replace("&amp;","&");
tagBuilder.MergeAttributes(attrs);

Solo nos preocupamos por los amplificadores, es por eso que este reemplazo literal

 1
Author: petho,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-05 14:27:40

Intente usar el código ASCII para esos valores:

^([a-zA-Z0-9 .\x26\x27-]+)$
  • \x26 = &
  • \x27 = '

El formato es \xnn donde nn es el código de carácter hexadecimal de dos dígitos. También puede usar \unnnn para especificar un código de carácter hexadecimal de cuatro dígitos para el carácter Unicode.

 0
Author: Ahmad Mageed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-23 15:50:09

El problema es que el patrón de expresiones regulares está codificado en HTML dos veces, una vez cuando se está construyendo la expresión regular, y una vez cuando se está renderizando en su vista.

Por ahora, intente envolver su TextBoxFor en un Html.Raw, así:

@Html.Raw(Html.TextBoxFor(model => Model.FirstName, new { }))
 0
Author: counsellorben,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-23 23:03:14

Pruebe este en la clase modelo

    [Required(ErrorMessage = "Enter full name.")]
    [RegularExpression("([A-Za-z])+( [A-Za-z]+)", ErrorMessage = "Enter valid full name.")]

    public string FullName { get; set; }
 0
Author: prashant shivhare,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-18 07:18:10