VB 2003 – Función para validar campos Hora Inicio y Hora Final
A continuación una función que debí crear para validar el formato de dos textBox destinados a recibir hora de inicio y fin de un evento.
La función valida que los textos cumplan con el formato “hh:mm tt” ó con el formato “HH:mm” y además verifica que la fecha final sea mayor que la fecha inicial.
Public Function ValidarTextosFecha() As Boolean
Dim blnValido As Boolean = True
Dim Expresion As System.Text.RegularExpressions.Regex
Expresion = New System.Text.RegularExpressions.Regex("^((([0]?[1-9]|1[0-2])(:)[0-5][0-9]( )?" & _
"(AM|am|aM|Am|PM|pm|pM|Pm))|(([0]?[0-9]|1[0-9]|2[0-3])(:)[0-5][0-9]))$", _
System.Text.RegularExpressions.RegexOptions.IgnoreCase)
If Not Expresion.IsMatch(txtHoraFin.Text) Then
Windows.Forms.MessageBox.Show("Formato inválido fecha inicio")
blnValido = False
End If
If Not Expresion.IsMatch(txtHoraInicio.Text) Then
Windows.Forms.MessageBox.Show("Formato inválido fecha final")
blnValido = False
End If
If blnValido Then
Dim inthorainicio As Integer = 0
Dim inthorafin As Integer = 0
Dim strTemporal As String = ""
If txtHoraInicio.Text.ToLower.IndexOf("pm") > 0 Then
inthorainicio = 1200
End If
strTemporal = txtHoraInicio.Text.Trim.Replace("am", "").Replace("pm", "").Replace(":", "")
If txtHoraInicio.Text.ToLower.IndexOf("pm") > 0 Or _
txtHoraInicio.Text.ToLower.IndexOf("am") > 0 Then
strTemporal = strTemporal.Substring(0, 2).Replace("12", "00") & _
strTemporal.Substring(2, strTemporal.Length - 2)
End If
inthorainicio += CInt(strTemporal)
If txtHoraFin.Text.ToLower.IndexOf("pm") > 0 Then
inthorafin = 1200
End If
strTemporal = txtHoraFin.Text.Trim.Replace("am", "").Replace("pm", "").Replace(":", "")
If txtHoraFin.Text.ToLower.IndexOf("pm") > 0 Or _
txtHoraFin.Text.ToLower.IndexOf("am") > 0 Then
strTemporal = strTemporal.Substring(0, 2).Replace("12", "00") & _
strTemporal.Substring(2, strTemporal.Length - 2)
End If
inthorafin += CInt(strTemporal)
If inthorafin <= inthorainicio Then
Windows.Forms.MessageBox.Show("La hora final debe ser mayor que la hora inicial")
blnValido = False
End If
End If
Return blnValido
End Function
Espero sea de ayuda.
Un Saludo.
Advertisement