Spanish [Solucionado] ¿Como evitar números negativos y valores máximos en un "edittext" numérico?

Sergio Castellari

Active Member
Licensed User
Situación:
a) Necesito poder controlar el valor ingresado:
- No permitir numero negativos
- Números mayores o iguales a cero y menores a 9,999,999.99

Un colega me ayudo anteriormente para controlar solo 2 decimales y números negativos con este código que funciona ok:
B4X:
'*** Se ejecuta durante los cambios de "edtImporte" ***
Private Sub edtImporte_TextChanged (Old As String, New As String)
    'Nota: En el diseñador, configuro EditText1 para esperar una entrada DECIMAL.
        'En los teclados numéricos, el signo menos requiere dos clics en mi dispositivo Samsung
    If New = "-" Then edtImporte.TextColor = xui.Color_Red
    Dim k As  Int = New.IndexOf(".")
    If k > -1 Then
        If New.Length - k > 3 Then
                         Main.Beep.beep  'Hace un pitido
            edtImporte.Text = Old
            edtImporte.SelectionStart = Old.length
        End If
    End If
End Sub
[/CÓDIGO]
No me doy cuenta como puedo "modificarlo" para NO permitir valores negativos y controlar el MÁXIMO valor permitido.
Saludos!
 

Gabino A. de la Gala

Active Member
Licensed User
Longtime User
Pues entiendo que más o menos igual.
En ese mismo evento, controlando el contenido que te venga en new y sobre la marcha, retocando el contenido de .Text.
Más o menos como cuando en el ejemplo que pones pregunta pro la longitud y se es > 3 mete en text el valor Old, para dejarlo como estaba antes de esa pulsación.
Y en el caso del "-" preguntar por si hay un "-" y sustituir también por el old.

B4X:
edtImporte.Text.IndexOf("-") <> -1 then edtImporte.Text = Old
 
Last edited:

angel_

Well-Known Member
Licensed User
Longtime User
Yo utilizo una función donde limito también el número de caracteres
B4X:
Sub IntroducirNumeros(NumMax As Double, MaxCaracteres As Byte, Anterior As String, Nuevo As String, edt As EditText)
    If Nuevo.StartsWith("-") Then
        edt.Text = Anterior
    End If
    
    If Nuevo.Length > MaxCaracteres Then
        edt.Text = Anterior
        edt.SelectionStart = edt.Text.Length
    End If
    
    If IsNumber(Nuevo) Then
        If Nuevo > NumMax Then
            edt.Text = Anterior
            edt.SelectionStart = edt.Text.Length
        End If
    End If
End Sub

Y después llamo así a la función

B4X:
Funciones.IntroducirNumeros(1, 5, Old, New, Sender)
 

Gabino A. de la Gala

Active Member
Licensed User
Longtime User
Yo utilizo una función donde limito también el número de caracteres
B4X:
Sub IntroducirNumeros(NumMax As Double, MaxCaracteres As Byte, Anterior As String, Nuevo As String, edt As EditText)
    If Nuevo.StartsWith("-") Then
        edt.Text = Anterior
    End If
    
    If Nuevo.Length > MaxCaracteres Then
        edt.Text = Anterior
        edt.SelectionStart = edt.Text.Length
    End If
    
    If IsNumber(Nuevo) Then
        If Nuevo > NumMax Then
            edt.Text = Anterior
            edt.SelectionStart = edt.Text.Length
        End If
    End If
End Sub

Y después llamo así a la función

B4X:
Funciones.IntroducirNumeros(1, 5, Old, New, Sender)
En el caso de @Sergio Castellari , "sólo" necesitaría añadir un parámetro más indicando el número de decimales y tenerlos en cuenta a la hora del recuento de número de dígitos, etc.
 

Sergio Castellari

Active Member
Licensed User
Yo utilizo una función donde limito también el número de caracteres
B4X:
Sub IntroducirNumeros(NumMax As Double, MaxCaracteres As Byte, Anterior As String, Nuevo As String, edt As EditText)
    If Nuevo.StartsWith("-") Then
        edt.Text = Anterior
    End If
   
    If Nuevo.Length > MaxCaracteres Then
        edt.Text = Anterior
        edt.SelectionStart = edt.Text.Length
    End If
   
    If IsNumber(Nuevo) Then
        If Nuevo > NumMax Then
            edt.Text = Anterior
            edt.SelectionStart = edt.Text.Length
        End If
    End If
End Sub

Y después llamo así a la función

B4X:
Funciones.IntroducirNumeros(1, 5, Old, New, Sender)
Hola @angel_

Muy interesante tu FUNCION !!!!
Disculpa mi ignorancia:
1) ¿Que seria el parámetro "sender" al llamarla?
2) ¿Llamas a la funcion desde TextChanged?

GRACIAS por tu aporte!
Saludos
 

Sergio Castellari

Active Member
Licensed User
Bueno con la ayuda de todos ustedes, logré el objetivo!
Les comparto mi función (pueden revisar si hago algo mal), pero las pruebas que hice funciona!

B4X:
'ValidoNumero() Valida NUMEROS en Editext Numericos
'************************************************************* 20-09-2021 ***
'Rango------> "T"=Todos, "P"=Positivos, "N"=Negativos
'MaxCar-----> Cantidad de caracteres máximo aceptado
'Decimales--> Cantidad Máxima de decimales permitidos
'Old--------> Valor Anterior del editext
'New--------> Valor Nuevo del editext
'edt--------> Vista objeto
Public Sub ValidoNumero(Rango As String, MaxCar As Int, Decimales As Int, Old As String, New As String, edt As EditText)
If New = "" Then Return                                    'Si es llamado vacíono hago nada!
Dim cPrimer As String
cPrimer = New.SubString2(0,1)                        'Si el primer caracter es "-"
If cPrimer = "-" Then
    edt.TextColor = xui.Color_Red                    'texto en Rojo
Else
    edt.TextColor = xui.Color_White                'texto en Blanco
End If
If Rango = "P" Then
    If New = "-" Then       'Verifico que sea POSITIVO (mayor o igual a CERO)
         Main.Beep.beep          'Hace un pitido
        edt.Text = Old
        edt.SelectionStart = Old.length
    End If
Else If Rango = "N" Then
    If Not (New.StartsWith("-")) Then
        edt.Text = Old
        edt.SelectionStart = Old.length
    End If
End If
If New.Length > MaxCar Then
    edt.Text = Old
    edt.SelectionStart = Old.length
End If
Dim k As  Int = New.IndexOf(".")
If k > -1 Then
    If New.Length - k > (Decimales + 1) Then
        Main.Beep.beep  'Hace un pitido
        edt.Text = Old
        edt.SelectionStart = Old.length
    End If
End If
End Sub

Y la llamo desde TextChanged:

B4X:
    Main.Func.ValidoNumero("T",9,2,Old,New,edtImporte1)

GRACIAS TOTALES!

PD: Como adicional: ¿Como se puede pasar un valor en formato String a un formato Double?
 

TILogistic

Expert
Licensed User
Longtime User
ver:

1632168084050.png
 

TILogistic

Expert
Licensed User
Longtime User
PD: Como adicional: ¿Como se puede pasar un valor en formato String a un formato Double?

ojo :
tener cuidado como muestra el valor en el log

B4X:
    Dim s As String = "12345678.23"
    Log(s)
    Dim d As Double = s
    Log(d)
    Log(NumberFormat(d,3,3).Replace(",",""))

1632168677993.png
 

TILogistic

Expert
Licensed User
Longtime User
Vi su publicación en el foro ingles y comento su necesidades, ha visto esta biblioteca si su app es solo para B4A.

 

Sergio Castellari

Active Member
Licensed User
Vi su publicación en el foro ingles y comento su necesidades, ha visto esta biblioteca si su app es solo para B4A.

mmmm...muy interesante....me voy a poner a ver como funciona...
 

Sergio Castellari

Active Member
Licensed User
La traduje a B4X que ocupo cuando deseo validar y limitar el ingreso de datos a un formato especificado.

SALUDOS TOTALES!!

😁😁😁
@oparra ....no estoy entendiendote....TU la tradujiste a B4X a la LIB que me muestras en el post anterior????

Recuerda que soy novato! jajaj

GRACIAS TOTALES!!!;)
 

Sergio Castellari

Active Member
Licensed User
Durante todo este proceso, creo que mejoré la FUNCIÓN que necesitaba para "controlar" las entradas numéricas:

B4X:
'ValidoNumero() Valida NUMEROS en Editext Numericos
'************************************************************* 20-09-2021 ***
'Rango------> "T"=Todos, "P"=Positivos, "N"=Negativos
'MaxNum-----> Numero Maximo permitido
'MinNum-----> Numero Minimo permitido
'Decimales--> Cantidad Máxima de decimales permitidos
'Old--------> Valor Anterior del editext
'New--------> Valor Nuevo del editext
'edt--------> Vista objeto
'alert------> Muestra carteles (True o False)
Public Sub ValidoNumero(Rango As String, MaxNum As Double, MinNum As Double, Decimales As Int, Old As String, New As String, edt As EditText, alert As Boolean)
If New = "" Then Return        'Si es llamado vacíono hago nada!
Dim nNum As Double

'Veo si es Negativo o Positivo y doy COLOR
Dim cPrimer As String
cPrimer = New.SubString2(0,1)        'Si el primer caracter es "-"
If cPrimer = "-" Then
    edt.TextColor = xui.Color_Red
Else
    edt.TextColor = xui.Color_White
End If

'Verifico si ya es un NUMERO para comprobar si supera el MAXIMO/MINIMO indicado
If Not (New.Length = 1 And (cPrimer = "-" Or cPrimer = ".")) Then
    nNum = New
    If nNum > MaxNum Then
        If alert Then ToastMessageShow("ATENCION !!!. Ha superado el MAXIMO permitido ["&MaxNum&"].",False) : Main.Beep.beep
        edt.Text = Old
        edt.SelectionStart = Old.length
    End If
    If nNum < MinNum Then
        If alert Then ToastMessageShow("ATENCION !!!. Ha superado el MINIMO permitido ["&MinNum&"].",False) : Main.Beep.beep
        edt.Text = Old
        edt.SelectionStart = Old.length
    End If
End If

'Verifico por Rango POSITIVO
If Rango = "P" Then
    If New = "-" Then       'Verifico que sea POSITIVO (mayor o igual a CERO)
        If alert Then ToastMessageShow("ATENCION !!!. Unicamente valores POSITIVOS.",False) : Main.Beep.beep
        edt.Text = Old
        edt.SelectionStart = Old.length
    End If
'Verifico por Rango NEGATIVO
Else If Rango = "N" Then
    If Not (New.StartsWith("-")) Then
        If alert Then ToastMessageShow("ATENCION !!!. Unicamente valores NEGATIVOS.",False) : Main.Beep.beep
        edt.Text = Old
        edt.SelectionStart = Old.length
    End If
End If

'Verifico cantidad de DECIMALES
Dim k As  Int = New.IndexOf(".")
If k > -1 Then
    If New.Length - k > (Decimales + 1) Then
        If alert Then ToastMessageShow("ATENCION !!!. Máximo " & Decimales & " decimales permitido.",False) : Main.Beep.beep
        edt.Text = Old
        edt.SelectionStart = Old.length
    End If
End If
End Sub

Espero sea de utilidad para alguien más!
Saludos totales!
 
Top