RegularExpressionAttribute Clase

Definición

Especifica que un valor de campo de datos en los datos dinámicos de ASP.NET debe coincidir con la expresión regular especificada.Specifies that a data field value in ASP.NET Dynamic Data must match the specified regular expression.

public ref class RegularExpressionAttribute : System::ComponentModel::DataAnnotations::ValidationAttribute
[System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false)]
public class RegularExpressionAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
public class RegularExpressionAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
[System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false)]
public class RegularExpressionAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
[<System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false)>]
type RegularExpressionAttribute = class
    inherit ValidationAttribute
type RegularExpressionAttribute = class
    inherit ValidationAttribute
[<System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false)>]
type RegularExpressionAttribute = class
    inherit ValidationAttribute
Public Class RegularExpressionAttribute
Inherits ValidationAttribute
Herencia
RegularExpressionAttribute
Atributos

Ejemplos

En el ejemplo siguiente se muestra cómo usar el RegularExpressionAttribute atributo para validar los campos de datos FirstName y LastName.The following example shows how to use the RegularExpressionAttribute attribute to validate the FirstName and LastName data fields. La expresión regular permite hasta 40 caracteres en mayúsculas y minúsculas.The regular expression allows up to 40 uppercase and lowercase characters. En el ejemplo se realizan las tareas siguientes:The example performs the following tasks:

  • Implementa una clase parcial de metadatos y la clase de metadatos asociada.Implements a metadata partial class and the associated metadata class.

  • En la clase de metadatos asociada, aplica el RegularExpressionAttribute atributo a los campos de datos FirstName y LastName, especificando el patrón y los mensajes de error personalizados.In the associated metadata class, applies the RegularExpressionAttribute attribute to the FirstName and LastName data fields, specifying the pattern and custom error messages.

using System;
using System.Web.DynamicData;
using System.ComponentModel.DataAnnotations;

[MetadataType(typeof(CustomerMetaData))]
public partial class Customer
{
}

public class CustomerMetaData
{
   
    // Allow up to 40 uppercase and lowercase 
    // characters. Use custom error.
    [RegularExpression(@"^[a-zA-Z''-'\s]{1,40}$", 
         ErrorMessage = "Characters are not allowed.")]
    public object FirstName;

    // Allow up to 40 uppercase and lowercase 
    // characters. Use standard error.
    [RegularExpression(@"^[a-zA-Z''-'\s]{1,40}$")]
    public object LastName;
}

Imports System.Web.DynamicData
Imports System.ComponentModel.DataAnnotations


<MetadataType(GetType(CustomerMetaData))> _
Partial Public Class Customer

    
End Class

Public Class CustomerMetaData
    
    ' Allow up to 40 uppercase and lowercase 
    ' characters. Use custom error.
    <RegularExpression("^[a-zA-Z''-'\s]{1,40}$", _
                       ErrorMessage:="Characters are not allowed.")> _
    Public FirstName As Object

    ' Allow up to 40 uppercase and lowercase 
    ' characters. Use standard error.
    <RegularExpression("^[a-zA-Z''-'\s]{1,40}$")> _
    Public LastName As Object
End Class

Comentarios

Se aplica el atributo RegularExpressionAttribute a una propiedad cuando es necesario validar los valores de la propiedad en una expresión regular.You apply the RegularExpressionAttribute attribute to a property when you need to validate values for the property against a regular expression. La expresión regular le permite especificar muy exactamente el formato de los valores válidos.The regular expression enables you to specify very precisely the format of valid values. La propiedad Pattern contiene la expresión regular.The Pattern property contains the regular expression. Si el valor de la propiedad es null o una cadena vacía (""), el valor pasa automáticamente la validación para el atributo RegularExpressionAttribute.If the value of the property is null or an empty string (""), the value automatically passes validation for the RegularExpressionAttribute attribute. Para validar que el valor no es null o una cadena vacía, use el atributo RequiredAttribute .To validate that the value is not null or an empty string, use the RequiredAttribute attribute.

La expresión regular busca una coincidencia exacta, que no use ^ Before y $ al final del patrón, genera los mismos resultados que al utilizarla.The regular expression searches for an exact match, not using ^ before and $ at the end of the pattern produces the same results as using it. Para un acierto de búsqueda, anteponga y anexa el patrón con .* .For a search hit, prepend and append the pattern with .*.

Constructores

RegularExpressionAttribute(String)

Inicializa una nueva instancia de la clase RegularExpressionAttribute.Initializes a new instance of the RegularExpressionAttribute class.

Propiedades

ErrorMessage

Obtiene o establece un mensaje de error que se va a asociar a un control de validación si se produce un error de validación.Gets or sets an error message to associate with a validation control if validation fails.

(Heredado de ValidationAttribute)
ErrorMessageResourceName

Obtiene o establece el nombre de recurso del mensaje de error que se va a usar para buscar el valor de la propiedad ErrorMessageResourceType si se produce un error en la validación.Gets or sets the error message resource name to use in order to look up the ErrorMessageResourceType property value if validation fails.

(Heredado de ValidationAttribute)
ErrorMessageResourceType

Obtiene o establece el tipo de recurso que se va a usar para buscar el mensaje de error si se produce un error de validación.Gets or sets the resource type to use for error-message lookup if validation fails.

(Heredado de ValidationAttribute)
ErrorMessageString

Obtiene el mensaje de error de validación traducido.Gets the localized validation error message.

(Heredado de ValidationAttribute)
MatchTimeoutInMilliseconds

Obtiene o establece el tiempo disponible en milisegundos para ejecutar una única operación coincidente antes de que se agote el tiempo de espera de la operación.Gets or sets the amount of time in milliseconds to execute a single matching operation before the operation times out.

Pattern

Obtiene el modelo de expresión regular.Gets the regular expression pattern.

RequiresValidationContext

Obtiene un valor que indica si el atributo requiere contexto de validación.Gets a value that indicates whether the attribute requires validation context.

(Heredado de ValidationAttribute)
TypeId

Cuando se implementa en una clase derivada, obtiene un identificador único para este Attribute.When implemented in a derived class, gets a unique identifier for this Attribute.

(Heredado de Attribute)

Métodos

Equals(Object)

Devuelve un valor que indica si esta instancia es igual que un objeto especificado.Returns a value that indicates whether this instance is equal to a specified object.

(Heredado de Attribute)
FormatErrorMessage(String)

Da formato al mensaje de error que debe mostrarse si se produce un error de validación de la expresión regular.Formats the error message to display if the regular expression validation fails.

GetHashCode()

Devuelve el código hash de esta instancia.Returns the hash code for this instance.

(Heredado de Attribute)
GetType()

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

(Heredado de Object)
GetValidationResult(Object, ValidationContext)

Comprueba si el valor especificado es válido con respecto al atributo de validación actual.Checks whether the specified value is valid with respect to the current validation attribute.

(Heredado de ValidationAttribute)
IsDefaultAttribute()

Si se reemplaza en una clase derivada, indica si el valor de esta instancia es el valor predeterminado de la clase derivada.When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class.

(Heredado de Attribute)
IsValid(Object)

Comprueba si el valor escrito por el usuario coincide con el modelo de expresión regular.Checks whether the value entered by the user matches the regular expression pattern.

IsValid(Object, ValidationContext)

Valida el valor especificado con respecto al atributo de validación actual.Validates the specified value with respect to the current validation attribute.

(Heredado de ValidationAttribute)
Match(Object)

Cuando se invalida en una clase derivada, devuelve un valor que indica si esta instancia es igual a un objeto especificado.When overridden in a derived class, returns a value that indicates whether this instance equals a specified object.

(Heredado de Attribute)
MemberwiseClone()

Crea una copia superficial del Object actual.Creates a shallow copy of the current Object.

(Heredado de Object)
ToString()

Devuelve una cadena que representa el objeto actual.Returns a string that represents the current object.

(Heredado de Object)
Validate(Object, String)

Valida el objeto especificado.Validates the specified object.

(Heredado de ValidationAttribute)
Validate(Object, ValidationContext)

Valida el objeto especificado.Validates the specified object.

(Heredado de ValidationAttribute)

Implementaciones de interfaz explícitas

_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Asigna un conjunto de nombres a un conjunto correspondiente de identificadores de envío.Maps a set of names to a corresponding set of dispatch identifiers.

(Heredado de Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Obtiene la información de tipos de un objeto, que puede utilizarse para obtener la información de tipos de una interfaz.Retrieves the type information for an object, which can be used to get the type information for an interface.

(Heredado de Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Recupera el número de interfaces de información de tipo que proporciona un objeto (0 ó 1).Retrieves the number of type information interfaces that an object provides (either 0 or 1).

(Heredado de Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Proporciona acceso a las propiedades y los métodos expuestos por un objeto.Provides access to properties and methods exposed by an object.

(Heredado de Attribute)

Se aplica a