MaskedTextBox.ValidatingType Propiedad

Definición

Obtiene o establece el tipo de datos utilizado para comprobar la entrada de datos por parte del usuario.

public:
 property Type ^ ValidatingType { Type ^ get(); void set(Type ^ value); };
[System.ComponentModel.Browsable(false)]
public Type ValidatingType { get; set; }
[System.ComponentModel.Browsable(false)]
public Type? ValidatingType { get; set; }
[<System.ComponentModel.Browsable(false)>]
member this.ValidatingType : Type with get, set
Public Property ValidatingType As Type

Valor de propiedad

Type que representa el tipo de datos utilizado en la validación. De manera predeterminada, es null.

Atributos

Ejemplos

En el ejemplo de código siguiente se intenta analizar la entrada del usuario como válida DateTime. Si se produce un error, el TypeValidationCompleted controlador de eventos muestra un mensaje de error al usuario. Si el valor es válido DateTime, el código realiza una comprobación adicional para asegurarse de que la fecha proporcionada no es anterior a la fecha de hoy. Este ejemplo de código requiere que el proyecto de Windows Forms contenga un MaskedTextBox control denominado MaskedTextBox1 y un ToolTip control denominado ToolTip1.

private void Form1_Load(object sender, EventArgs e)
{
    maskedTextBox1.Mask = "00/00/0000";
    maskedTextBox1.ValidatingType = typeof(System.DateTime);
    maskedTextBox1.TypeValidationCompleted += new TypeValidationEventHandler(maskedTextBox1_TypeValidationCompleted);
    maskedTextBox1.KeyDown += new KeyEventHandler(maskedTextBox1_KeyDown);

    toolTip1.IsBalloon = true;
}

void maskedTextBox1_TypeValidationCompleted(object sender, TypeValidationEventArgs e)
{
    if (!e.IsValidInput)
    {
        toolTip1.ToolTipTitle = "Invalid Date";
        toolTip1.Show("The data you supplied must be a valid date in the format mm/dd/yyyy.", maskedTextBox1, 0, -20, 5000);
    }
    else
    {
        //Now that the type has passed basic type validation, enforce more specific type rules.
        DateTime userDate = (DateTime)e.ReturnValue;
        if (userDate < DateTime.Now)
        {
            toolTip1.ToolTipTitle = "Invalid Date";
            toolTip1.Show("The date in this field must be greater than today's date.", maskedTextBox1, 0, -20, 5000);
            e.Cancel = true;
        }
    }
}

// Hide the tooltip if the user starts typing again before the five-second display limit on the tooltip expires.
void maskedTextBox1_KeyDown(object sender, KeyEventArgs e)
{
    toolTip1.Hide(maskedTextBox1);
}
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Me.MaskedTextBox1.Mask = "00/00/0000"
    Me.MaskedTextBox1.ValidatingType = GetType(System.DateTime)

    Me.ToolTip1.IsBalloon = True
End Sub

Private Sub MaskedTextBox1_TypeValidationCompleted(ByVal sender As Object, ByVal e As TypeValidationEventArgs) Handles MaskedTextBox1.TypeValidationCompleted
    If (Not e.IsValidInput) Then
        Me.ToolTip1.ToolTipTitle = "Invalid Date"
        Me.ToolTip1.Show("The data you supplied must be a valid date in the format mm/dd/yyyy.", Me.MaskedTextBox1, 0, -20, 5000)
    Else
        ' Now that the type has passed basic type validation, enforce more specific type rules.
        Dim UserDate As DateTime = CDate(e.ReturnValue)
        If (UserDate < DateTime.Now) Then
            Me.ToolTip1.ToolTipTitle = "Invalid Date"
            Me.ToolTip1.Show("The date in this field must be greater than today's date.", Me.MaskedTextBox1, 0, -20, 5000)
            e.Cancel = True
        End If
    End If
End Sub

' Hide the tooltip if the user starts typing again before the five-second display limit on the tooltip expires.
Private Sub MaskedTextBox1_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs) Handles MaskedTextBox1.KeyDown
    Me.ToolTip1.Hide(Me.MaskedTextBox1)
End Sub

Comentarios

Las máscaras no garantizan que la entrada de un usuario represente un valor válido para un tipo determinado. El código de C# siguiente muestra una máscara:

maskedTextBox1.Mask = "99/99/9999";  

El siguiente código de Visual Basic muestra una máscara:

MaskedTextBox1.Mask = "99/99/9999"

Esta máscara puede exigir que el usuario escriba ocho dígitos, pero no puede comprobar que el usuario escriba los valores de mes, fecha y año en el intervalo correcto; "20/12/2003" y "70/90/0000" son igualmente válidos en lo que respecta a la máscara.

Puede usar ValidatingType para comprobar si los datos especificados por el usuario están dentro del intervalo correcto; en el caso mencionado anteriormente, asígnele una instancia del DateTime tipo . El texto actual del control se validará cuando el usuario salga del control. Puede determinar si los datos no se valida o no mediante la supervisión del TypeValidationCompleted evento. MaskedTextBox solo realizará la comprobación en ValidatingType si MaskCompleted es true.

Si desea usar sus propios tipos de datos personalizados con ValidatingType, debe implementar un método estático Parse que tome una cadena como parámetro. Este método debe implementarse con una o ambas firmas:

public static Object Parse(string)

public static Object Parse(string, IFormatProvider)

Se aplica a

Consulte también