Foros del Web » Programando para Internet » ASPX (.net) »

RegularExpressionValidator + Required

Estas en el tema de RegularExpressionValidator + Required en el foro de ASPX (.net) en Foros del Web. Podria controlar mediante un control de validación del tipo <asp:RegularExpressionValidator id="val1" ValidationExpression="^\d+$"> si un campo es requerido y ademas es numerico ??? Mi idea inicial ...
  #1 (permalink)  
Antiguo 28/07/2006, 05:23
Avatar de txarly  
Fecha de Ingreso: marzo-2003
Ubicación: Eibar (Gipuzkoa)
Mensajes: 455
Antigüedad: 21 años, 1 mes
Puntos: 2
RegularExpressionValidator + Required

Podria controlar mediante un control de validación del tipo <asp:RegularExpressionValidator id="val1" ValidationExpression="^\d+$"> si un campo es requerido y ademas es numerico ???

Mi idea inicial es cubrir con una expresion regular las dos validaciones, tanto de formato como de campo requerido.

Gracias
__________________
¿Por qué Uri Geller doblaba cucharas?
  #2 (permalink)  
Antiguo 28/07/2006, 08:24
 
Fecha de Ingreso: mayo-2004
Ubicación: Guadalajara, Jalisco, México
Mensajes: 724
Antigüedad: 20 años
Puntos: 6
Hola.. hace tiempo hize una clase que hace ambas en un solo validador.. más bien es una clase que herede de textbox...

Puedes hacer pruebas si gustas...
Cita:
'//Agregada unicamente para validar...
'// Hecha por Stream el 05 de Enero de 2006
#Region " TextBoxRequired Options "
Public Class TextBoxRequired
Inherits TextBox

'//Texto requerido...
<System.ComponentModel.Category("TextBoxRequired Options"), System.ComponentModel.Description("Texto que se desplagara por default al ser el campo invalido. Esta propiedad es ignorada si la propiedad TextResourseString se esta usando ")> _
Public Property TextRequiredDefault() As String
Get
Return ViewState("TextRequiredDefault")
End Get
Set(ByVal Value As String)
ViewState("TextRequiredDefault") = Value
End Set
End Property

<System.ComponentModel.Category("TextBoxRequired Options"), System.ComponentModel.Description("Para determinar si el campo sera requerido. True haga las validaciones correspondientes, False no hara valicacion")> _
Public Property IsRequired() As Boolean
Get
If ViewState("IsRequired") Is Nothing Then
ViewState("IsRequired") = True
End If
Return ViewState("IsRequired")
End Get
Set(ByVal Value As Boolean)
ViewState("IsRequired") = Value
End Set
End Property

<System.ComponentModel.Category("TextBoxRequired Options"), System.ComponentModel.Description("Nombre o numero del recurso muitiidioma.")> _
Public Property TextResourseString() As String
Get
Return ViewState("TextResourseString")
End Get
Set(ByVal Value As String)
ViewState("TextResourseString") = Value
End Set
End Property

<System.ComponentModel.Category("TextBoxRequired Options"), System.ComponentModel.Description("Hoja de estilo para el mensaje de error")> _
Public Property CssError() As String
Get
Return ViewState("CssError")
End Get
Set(ByVal Value As String)
ViewState("CssError") = Value
End Set
End Property

<System.ComponentModel.Category("TextBoxRequired Options"), System.ComponentModel.Description("Expresion de validacion; Por ejemplo para email: \w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)* ")> _
Public Property TextRegExpStringValidation() As String
Get
Return ViewState("TextRegExpStringValidation")
End Get
Set(ByVal Value As String)
ViewState("TextRegExpStringValidation") = Value
End Set
End Property

<System.ComponentModel.Category("TextBoxRequired Options"), System.ComponentModel.Description("Esta funcion sirve para determinar si se hara la validacion con la expresion de validacion de la propiedad TextRegExpStringValidation, True intentara hacer la validacio, Falso omitira la expresion.")> _
Public Property TextDoRegExpValidation() As Boolean
Get
If ViewState("TextDoRegExpValidation") Is Nothing Then
ViewState("TextDoRegExpValidation") = False
End If
Return ViewState("TextDoRegExpValidation")
End Get
Set(ByVal Value As Boolean)
ViewState("TextDoRegExpValidation") = Value
End Set
End Property

Public Overrides Sub RenderBeginTag(ByVal writer As System.Web.UI.HtmlTextWriter)
If Me.IsRequired Then 'si es requerido
Dim DivName As String = "cDiv" & Me.ClientID
Me.Attributes.Add("onkeypress", "TextBoxRequired_Onchange(this,'" & DivName & "');")
Me.Attributes.Add("onblur", "TextBoxRequired_OnBlur(this,'" & DivName & "');")
Me.Attributes.Add("TextBoxRequired", DivName)

If Me.TextDoRegExpValidation Then
Me.Attributes.Add("TextRegExpString", Me.TextRegExpStringValidation)
End If

'//Si la propiedad TextRequiredDefault no tiene texto entonces usa el TextResourseString
If Me.TextResourseString <> "" Then
Me.TextRequiredDefault = PortalCulture.GetString(Me.TextResourseString())
End If
If Me.TextRequiredDefault = "" Then
Me.TextRequiredDefault = "*"
End If
'If Page.IsPostBack Then
' 'If Me.Text.Trim = "" Then
' ' writer.Write("<div id=""" & DivName & """ class=""" & Me.CssError & """ style=""display:block""><font color=""red"">" & Me.TextRequiredDefault.Split("$")(0) & "</font></div> ")
' 'End If
'Else
writer.Write("<div id=""" & DivName & """ class=""" & Me.CssError & """ style=""display:none""><font color=""red"">" & Me.TextRequiredDefault.Split("$")(0) & "</font></div> ")
''End If
If Not Page.IsStartupScriptRegistered("sc_textboxesRequir ed") Then
Dim scr As New System.Text.StringBuilder
Dim b = ControlChars.CrLf
With scr
.Append("<script>" & b)
.Append(" function TextBoxRequired_Onchange(txt, divname){ " & b)
.Append(" var div = document.getElementById(divname); " & b)
.Append(" if (div) " & b)
.Append(" { " & b)
.Append(" div.style.display='none';" & b)
.Append(" } " & b)
.Append(" }" & b)
.Append(" function TextBoxRequired_OnBlur(txt, divname){ " & b)
.Append(" var div = document.getElementById(divname); " & b)
.Append(" if (txt.value==''){" & b)
.Append(" if (div) " & b)
.Append(" { " & b)
.Append(" div.style.display='block';" & b)
.Append(" } " & b)
.Append(" }else{" & b)
.Append(" if (txt.getAttribute('TextRegExpString')!=null){" & b)
.Append(" var regExpString = txt.getAttribute('TextRegExpString'); " & b)
.Append(" var myRegxp = new RegExp(regExpString); " & b)
.Append(" var div = document.getElementById(txt.getAttribute('TextBoxR equired'));" & b)
.Append(" if (!myRegxp.test(txt.value)){" & b)
.Append(" valid=false;" & b)
.Append(" if (div){" & b)
.Append(" div.style.display='block';" & b)
.Append(" }" & b)
.Append(" }else{ if (div) div.style.display='none';" & b)
.Append(" }" & b)
.Append(" }" & b)
.Append(" }" & b)
.Append(" }" & b)
.Append(" document.forms[0].onsubmit = function() " & b)
.Append(" {" & b)
.Append(" var txts = document.getElementsByTagName('input');" & b)
.Append(" var i;" & b)
.Append(" var valid = true;" & b)
.Append(" for (i=0; i<=txts.length-1; i++){" & b)
.Append(" if (txts[i].getAttribute('TextBoxRequired')!= null){" & b)
.Append(" if (txts[i].value==''){" & b)
.Append(" valid=false;" & b)
.Append(" var div = document.getElementById(txts[i].getAttribute('TextBoxRequired'));" & b)
.Append(" if (div){" & b)
.Append(" div.style.display='block';" & b)
.Append(" }" & b)
.Append(" }else{" & b)
.Append(" if (txts[i].getAttribute('TextRegExpString')!=null){" & b)
.Append(" var regExpString = txts[i].getAttribute('TextRegExpString'); " & b)
.Append(" var myRegxp = new RegExp(regExpString); " & b)
.Append(" var div = document.getElementById(txts[i].getAttribute('TextBoxRequired'));" & b)
.Append(" if (!myRegxp.test(txts[i].value)){" & b)
.Append(" valid=false;" & b)
.Append(" if (div){" & b)
.Append(" div.style.display='block';" & b)
.Append(" }" & b)
.Append(" }else{ if (div) div.style.display='none';" & b)
.Append(" }" & b)
.Append(" }" & b)
.Append(" }" & b)
.Append(" }" & b)
.Append(" }" & b)
.Append(" return valid;" & b)
.Append(" }" & b)
.Append("</script>" & b)
End With
Page.RegisterStartupScript("sc_textboxesRequired", scr.ToString)
End If
End If
MyBase.RenderBeginTag(writer)
End Sub

End Class
#End Region
  #3 (permalink)  
Antiguo 28/07/2006, 08:26
 
Fecha de Ingreso: mayo-2004
Ubicación: Guadalajara, Jalisco, México
Mensajes: 724
Antigüedad: 20 años
Puntos: 6
'Para registrar el control en tu pagina, en el top de tu aspx
<%@ Register TagPrefix="ucx" Namespace="EnsambladoDetuAPP"" Assembly="EnsambladoDetuAPP" %>

para usar el control:
<ucx:textboxrequired id="txtDescripcion" runat="server" CssClass="cText" TextRequiredDefault="La descripcion es requerida" MaxLength="600" Width="213px" Visible="True"></ucx:textboxrequired>

ok, al agregar el control a tu pagina, al hacer submit se validará que los que sean requeridos contengan datos...

Tip: Si quieres que un boton haga postback, asignale un null al onsubmit
BtnClear.Attributes.Add("onclick", "document.forms[0].onsubmit = null;")

A lo mejor y no te sirve esto.. al menos te comparto que yo lo usé y si me funciono..

Saludos...
  #4 (permalink)  
Antiguo 01/08/2006, 08:12
 
Fecha de Ingreso: mayo-2004
Ubicación: Guadalajara, Jalisco, México
Mensajes: 724
Antigüedad: 20 años
Puntos: 6
Bueno.. al parecer no te sirvio hee.. ó a un no regresas a ver el post...
  #5 (permalink)  
Antiguo 06/09/2006, 02:40
Avatar de txarly  
Fecha de Ingreso: marzo-2003
Ubicación: Eibar (Gipuzkoa)
Mensajes: 455
Antigüedad: 21 años, 1 mes
Puntos: 2
¿No hay una forma más sencilla? eso me obligaria a cambiar todos los controles que quiera validar. Con el validador de expresiones regulares no puedo controlar que el campo sea requerido?
__________________
¿Por qué Uri Geller doblaba cucharas?
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 13:30.