Jump to content

_GUICtrlUSPS_Create()


Go to solution Solved by argumentum,

Recommended Posts

Posted

image.png.5e8073b470330f4b14c1daa782e8cfbb.png

#include <GuiConstants.au3>
#include <GuiIPAddress.au3>
#include <WindowsConstants.au3>
Opt("MustDeclareVars", 1)
test()
Func test()
    Local $hgui, $nMsg, $iBtn_Get, $hIPAddress
    $hgui = GUICreate("IP Address Control Example", 500, 150)
    Local $hIPAddress = _GUICtrlIpAddress_Create($hgui, 10, 10, 200, 20)
    _GUICtrlIpAddress_Set($hIPAddress, @IPAddress1)
    $iBtn_Get = GUICtrlCreateButton("Get IP", 220, 10, 75, 20)

    GUICtrlCreateInput("1234 1234 1234 1234 1234", 10, 40, 200)
    GUICtrlCreateButton("Get USPS", 220, 40, 75, 20)
    GUICtrlCreateInput("1234 1234 1234 1234 1234 12", 10, 70, 200)
    GUICtrlCreateButton("Get USPS", 220, 70, 75, 20)

    GUISetState(@SW_SHOW)

    While 1
        Switch GUIGetMsg()
            Case $GUI_EVENT_CLOSE
                GUIDelete($hgui)
                ExitLoop
            Case $iBtn_Get
                Local $sIP = _GUICtrlIpAddress_Get($hIPAddress)
                MsgBox(4160, "Information", "IP Address entered: " & $sIP)
        EndSwitch
    WEnd
EndFunc   ;==>test

 

I'd like to have an input control that behaves like the one for IPv4 ( grouping the octets ) grouping  the 4 symbols of the number and the optional 2 at the end. Because the number can be 20 or 22 char long.

Help :baby:

Follow the link to my code contribution ( and other things too ).
FAQ - Please Read Before Posting.
autoit_scripter_blue_userbar.png

  • Solution
Posted (edited)

This behaves nicely 
image.png.b0c4535e979dd540f902a2bb4dcde338.png

 

#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
#include <EditConstants.au3>
#include <GuiEdit.au3>
#include <Misc.au3>

Global $idInput = -1

Exit Example()
Func Example()
    Local $hGUI = GUICreate("USPS thing", 340, 50)
    Local $iStrLen, $idBttn = GUICtrlCreateButton("Validate USPS number", 210, 15, 120, 20)
    $idInput = GUICtrlCreateInput("1234 1234 1234 1234 1234 17", 10, 15, 200, 20)
    GUICtrlSetLimit(-1, 27) ; 22 digits + 5 spaces
    GUISetState()
    GUIRegisterMsg($WM_COMMAND, "_WM_COMMAND")
    While 1
        Switch GUIGetMsg()
            Case $GUI_EVENT_CLOSE
                GUIDelete($hGUI)
                ExitLoop
            Case $idBttn
                $iStrLen = StringLen(GUICtrlRead($idInput))
                If $iStrLen = 24 Or $iStrLen = 27 And _USPS_Mod10_Check(GUICtrlRead($idInput)) Then
                    MsgBox(64, "Valid", "Checksum Passed! This is a validly formatted USPS number.", 60, $hGUI)
                Else
                    ConsoleWrite('! the last digit should have been ' & @extended & ', or wrong length.' & @CRLF)
                    MsgBox(16, "Error", "Checksum Failed! Please check for typos.", 60, $hGUI)
                EndIf
        EndSwitch
    WEnd
EndFunc   ;==>Example

Func _WM_COMMAND($hWnd, $iMsg, $wParam, $lParam)
    Local $iIDFrom = BitAND($wParam, 0xFFFF)
    Local $iCode = BitShift($wParam, 16)

    If $iIDFrom = $idInput And $iCode = $EN_UPDATE Then _USPS_InputFormatting($idInput)

    Return $GUI_RUNDEFMSG
EndFunc   ;==>_WM_COMMAND

Func _USPS_InputFormatting($idCtrl)
    Local $iKeyBACKSPACE = _IsPressed("08")
    Local $iKeyDEL = _IsPressed("2E")     ; what did the user do ?
    Local $aSel = _GUICtrlEdit_GetSel($idCtrl)
    Local $sCurrent = GUICtrlRead($idCtrl)

    ; 1. REGEX: Remove everything that is NOT a digit [^0-9]
    Local $sClean = StringRegExpReplace($sCurrent, "[^0-9]", "")

    ; 2. REGEX: Insert space every 4 digits
    Local $sFormatted = StringStripWS(StringRegExpReplace($sClean, ".{4}", "$0 "), 3)

    ; 3. Adjust cursor position if text length changed
    If $sCurrent <> $sFormatted Then
        GUICtrlSetData($idCtrl, StringLeft($sFormatted, 27))
        If (StringLen($sCurrent) = $aSel[0]) Or _
                ($iKeyBACKSPACE = 0 And (Mod($aSel[0], 5) = 4)) Or _
                ($iKeyBACKSPACE = 0 And StringMid($sCurrent, $aSel[0] + 1, 1) = " ") Then
            $aSel[0] += 1
        ElseIf $iKeyDEL = 1 And (Mod($aSel[0], 5) = 4) Then
            $aSel[0] -= 1
        EndIf
        If $aSel[0] < 0 Then $aSel[0] = 0
        _GUICtrlEdit_SetSel($idCtrl, $aSel[0], $aSel[0])
    EndIf
EndFunc   ;==>_USPS_InputFormatting

Func _USPS_Mod10_Check($sNum) ; The official USPS MOD10 Algorithm
    ; https://www.autoitscript.com/forum/topic/213428-_guictrlusps_create/#findComment-1549245
    $sNum = StringStripWS($sNum, 8) ; remove the spaces if any, and count 20 or 22
    If StringLen($sNum) <> 22 And StringLen($sNum) <> 20 Then Return SetError(1, -1, False)
    Local $aDigits = StringSplit($sNum, "")
    Local $iSum = 0, $iWeight = 3 ; The digit just before the check digit always gets a weight of 3

    ; Start from the one before the check digit and move LEFT
    For $i = $aDigits[0] - 1 To 1 Step -1
        $iSum += Int($aDigits[$i]) * $iWeight
        $iWeight = ($iWeight = 3 ? 1 : 3) ; Alternate weight between 3 and 1
    Next

    ; The check digit is the number needed to reach the next multiple of 10
    Local $iRemainder = Mod($iSum, 10)
    Local $iCalculatedCheck = ($iRemainder = 0) ? 0 : (10 - $iRemainder)

    ; Return True if the last digit matches the calculation
    Return SetError(0, $iCalculatedCheck, $iCalculatedCheck = Int($aDigits[$aDigits[0]]))
EndFunc   ;==>_USPS_Mod10_Check

...if you come up with something better, do post :)

Edit: added a validation function.

Edit: fixed cursor position.

Edited by argumentum
better

Follow the link to my code contribution ( and other things too ).
FAQ - Please Read Before Posting.
autoit_scripter_blue_userbar.png

Posted

Interesting
Here is my variation.

#include <EditConstants.au3>
#include <GUIConstantsEx.au3>
#include <GuiEdit.au3>
#include <WindowsConstants.au3>
#include <String.au3>

Global $idInput = -1

Test2()
Exit

Func Test2()
    Local $hgui = GUICreate("USPS thing", 300, 100)
    #forceref $hgui

    $idInput = GUICtrlCreateInput("", 20, 35, 260, 20)
    GUICtrlSetLimit(-1, 27) ; 22 digits + 5 spaces
    GUISetState()
    GUIRegisterMsg($WM_COMMAND, "_WM_COMMAND")

    While 1
        If GUIGetMsg() = $GUI_EVENT_CLOSE Then Exit
    WEnd
EndFunc   ;==>Test2

Func _WM_COMMAND($hWnd, $iMsg, $wParam, $lParam)
    #forceref $hWnd, $iMsg, $lParam

    Local $iIDFrom = BitAND($wParam, 0xFFFF)
    Local $iCode = BitShift($wParam, 16)

    If $iIDFrom = $idInput And $iCode = $EN_CHANGE Then
        Local $aSel = _GUICtrlEdit_GetSel($idInput)
        Local $iPos = $aSel[0]

        Local $sCurrent = GUICtrlRead($idInput)

        ; 1. REGEX: Remove everything that is NOT a digit [^0-9]
        Local $sClean = StringRegExpReplace($sCurrent, "[^0-9]", "")
        Local Static $sEmptyMask = '*********************'
        $sClean = $sClean & StringLeft($sEmptyMask, 21 - StringLen($sClean))

        ; 2. REGEX: Insert space every 4 digits
        ; Local $sFormatted = StringRegExpReplace($sClean, "(.{4})", "$1 ")
        Local $sFormatted = StringRegExpReplace($sClean, ".{4}", "$0.")
        $sFormatted = StringStripWS($sFormatted, 2) ; Remove trailing space

        If $sCurrent <> $sFormatted Then
            GUICtrlSetData($idInput, $sFormatted)

            ; 3. Adjust cursor position if text length changed
            If StringLen($sFormatted) > StringLen($sCurrent) Then $iPos += 1
            If StringLen($sFormatted) < StringLen($sCurrent) Then $iPos -= 1

            _GUICtrlEdit_SetSel($idInput, $iPos, $iPos)
        EndIf
    EndIf
    Return $GUI_RUNDEFMSG
EndFunc   ;==>_WM_COMMAND


ISSUES / TODO :

  1. to use 22 * not 21
  2. to see all * at start
  3. to works well when you type numbers
  4. to works well when you use delete/backspace key

 

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Posted
3 hours ago, pixelsearch said:

For the record, does this pattern works for you, without any group ?

Yes, worked well. Replaced the original with yours ( yes, I am the king of copy and paste :lol: ). Thanks.
Still don't know what's the difference, functionally. Unless I didn't test enough 🤔

44 minutes ago, mLipok said:

Here is my variation.

Didn't behave well and the one I put together ( yes, I edited the 2nd post ) works good enough.

But always welcome new ideas :) 

Follow the link to my code contribution ( and other things too ).
FAQ - Please Read Before Posting.
autoit_scripter_blue_userbar.png

Posted
43 minutes ago, argumentum said:

Didn't behave well and the one I put together ( yes, I edited the 2nd post ) works good enough.

But always welcome new ideas :) 

Thank you.
My version was a case study of sorts, a proof of concept that it could be achieved this way.
I'm curious if anyone can solve my list:

1 hour ago, mLipok said:

ISSUES / TODO :

  1. to use 22 * not 21
  2. to see all * at start
  3. to works well when you type numbers
  4. to works well when you use delete/backspace key

 

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Posted
5 hours ago, argumentum said:

Still don't know what's the difference, functionally.

Guess I'm "Pavlovian conditioned" because each time I see a StringRegExpReplace (SRER) with captured groups, it remembers me our late friend @mikell We exchanged a PM a few years ago, concerning captured groups, SRER... and he wrote a sentence I didn't forget. Here it is below :

mikellsadviceaboutSRER.png.83f84c4c13c77aa4b1b2b151429f3f4a.png

Translation :

Yes, what we sometimes tend to forget is that SRER replaces everything in the pattern, except lookarounds and what is before \K
(ab)c: SRE returns ab, SRER replaces abc

Legend :
SRER = StringRegExpReplace
SRE  = StringRegExp

argumentum, the difference is that the pattern with $0 doesn't create unnecessary capture groups.
Capture groups would have been necessary if (for instance) we replaced with "$2-$1" or if they were alternations (|) in the pattern etc... As we don't have any of these in the pattern, then we don't need captured groups... I guess.

Maybe our RegExp guru @jchd could explain it better, if he got some time.
Thanks :)

"I think you are searching a bug where there is no bug... don't listen to bad advice."

Posted

@pixelsearch is correct in pointing out that behavior.

I don't have access to the C++ source for these functions, but notice that while SRE uses published PCRE v1 API, the "Replace" part in SRER is homebrew since there is no "replace" support API in PCRE v1.

Yet AutoIt implementation of SRER matches legacy behavior of other PCRE v1 libraries.

Play with this example, using Match or Substitute, $0 or $1:

https://regex101.com/r/URSZPk/1

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Posted

@jchd thanks for the regex101 example
In the regex101 example, there is a /g (global) flag (a Perl option ?) and PCRE doc establishes a comparison between /g and "our" \G ... complications start :D

"I think you are searching a bug where there is no bug... don't listen to bad advice."

Posted

You can remove the /gm options: nothing changes.

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...