IsAlpha/IsDigit

Dupla de validacao de caractere. IsAlpha = e letra (A-Z, a-z)? IsDigit = e digito (0-9)? Bloco de construcao classico pra validar input.

Assinatura: IsAlpha(cChar) -> lLetra // IsDigit(cChar) -> lDigito

Retorna: Logical

Pequenas mas indispensaveis em validacao de input. IsAlpha testa se char e letra; IsDigit testa se char e numero.

Sintaxe

IsAlpha(cChar)    --> .T./.F.
IsDigit(cChar)    --> .T./.F.

Exemplos

IsAlpha("A")          // .T.
IsAlpha("z")          // .T.
IsAlpha("0")          // .F.
IsAlpha("@")          // .F.
IsAlpha("")           // .F.

IsDigit("5")          // .T.
IsDigit("A")          // .F.
IsDigit(" ")          // .F.
IsDigit("")           // .F.

Casos praticos

1. Validar se string e numerica

Static Function EhNumerico(cStr)
    Local i
    Local cStr2 := AllTrim(cStr)

    If Empty(cStr2)
        Return .F.
    EndIf

    For i := 1 To Len(cStr2)
        If !IsDigit(SubStr(cStr2, i, 1))
            Return .F.
        EndIf
    Next
Return .T.

EhNumerico("12345")    // .T.
EhNumerico("12a45")    // .F.
EhNumerico("")          // .F.

2. Validar codigo (so letras e digitos)

Static Function EhAlnum(cStr)
    Local i
    Local c
    For i := 1 To Len(cStr)
        c := SubStr(cStr, i, 1)
        If !(IsAlpha(c) .Or. IsDigit(c))
            Return .F.
        EndIf
    Next
Return .T.

EhAlnum("ABC123")      // .T.
EhAlnum("ABC-123")     // .F. (tem traco)

3. Sanitizar input — remover nao-digitos de CPF

Static Function _SoDigitos(cTxt)
    Local cRet := ""
    Local i, c

    For i := 1 To Len(cTxt)
        c := SubStr(cTxt, i, 1)
        If IsDigit(c)
            cRet += c
        EndIf
    Next
Return cRet

_SoDigitos("123.456.789-01")    // "12345678901"
_SoDigitos("(11) 99999-8888")    // "11999998888"

Pegadinhas

Veja também