GeorgeB

How to restrict inputboxes to specific characters only?

13 posts in this topic

I'm having trouble in making an input box where I can limit the characters that can be inputted.  Anybody have an idea how this can be done in Auto IT?

Specifically I would like to create an input field where the user would enter a MAC address.  What I would like to do is to limit the characters that can be inputted to only HEX values (A-F and 0-9 as well as the - character).  This is so that the user cannot input invalid characters. The program is going to be used by very non-technical people, so the idea is to remove as many chances for errors that we can think of.  I would also prefer to limit the field to only 17 characters, so that there is only enough space to enter the MAC address with the - character as the separator.

Thank you all in advance for any suggestions!

Share this post


Link to post
Share on other sites



#2 ·  Posted (edited)

I have been trying to learn more about RegEx recently, so I'm no expert, but I think this will work.

Do
   Local $sValue = InputBox("Testing", "Enter the MAC Address.", "", " M17")
Until StringRegExp($sValue, '([0-9a-fA-F]{2}[-]){5}([0-9a-fA-F]{2})') = 1

 

Edited by MuffinMan
Slight edit to allow for lowercase a-f

Share this post


Link to post
Share on other sites

NEW:     ADO.au3 UDF     POP3.au3 UDF     XML.au3 UDF    How to use IE.au3  UDF with  AutoIt v3.3.14.x  for other useful stuff click the following button:

Spoiler

Last update: 2016-11-12
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 Components * TeamViewer API -UDF * JavaManagement UDF * VIES over SOAPPOP3.au3 UDF *  RTF Printer - UDF * XML.au3 - BETA * ADO.au3 UDF SMTP Mailer UDF * WinSCP UDF *

My contribution to others projects: * _sql.au3 UDF  *

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 * Best coding practices * 

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 *

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 *

"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."

 

Share this post


Link to post
Share on other sites

This should work to do it dynamically  :)

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

Opt("GUIOnEventMode", 1)

$hGUI = GUICreate("Test", 232, 90)
$Label = GUICtrlCreateLabel("Enter MAC address", 22, 8, 163, 17)
$input = GUICtrlCreateInput("", 22, 30, 165, 24)
GUICtrlSetLimit(-1, 17)
GUICtrlSetFont(-1, 12)
GUISetState()

GUIRegisterMsg($WM_COMMAND, '_WM_COMMAND')
GUISetOnEvent($GUI_EVENT_CLOSE, "_Exit")

While 1
  Sleep(10)
WEnd

Func _WM_COMMAND($hWnd, $Msg, $wParam, $lParam)
 Local $id = BitAND($wParam, 0x0000FFFF)
 Local $code = BitShift($wParam, 16)
   If $id = $input AND $code = $EN_UPDATE Then
       Local $content = GUICtrlRead($input)
       Local $len = StringLen($content)
       Local $char = StringRight($content, 1)
       Local $mod = Mod($len, 3)
       If not (( ($mod = 1 or $mod = 2) and StringRegExp($char, '[[:xdigit:]]') ) OR _ 
           ($mod = 0 and $char = "-")) Then GUICtrlSetData($input, StringTrimRight($content, 1)) 
    EndIf
    Return $GUI_RUNDEFMSG
EndFunc

Func _Exit()
    Exit
EndFunc

 

1 person likes this

Share this post


Link to post
Share on other sites

Mikell,

Thank you very much!  That is EXACTLY what I was looking for!    mLipok and Muffinman, thank you as well for your suggestions!

Share this post


Link to post
Share on other sites

A slight optional addition for a better look  :D

Func _WM_COMMAND($hWnd, $Msg, $wParam, $lParam)

   ;....

   If not (( ($mod = 1 or $mod = 2) and StringRegExp($char, '[[:xdigit:]]') ) OR _ 
           ($mod = 0 and $char = "-")) Then 
       GUICtrlSetData($input, StringTrimRight($content, 1)) 
   Else
       GUICtrlSetData($input, StringUpper($content))
   EndIf

 

1 person likes this

Share this post


Link to post
Share on other sites

Mikell,

I'm not sure what I am missing, but when I paste in your additional code, it errors out. (the original one works great!)

By the way, excuse my ignorance, but where in the code does it specifically state that only a-f and 0-9 and - are allowed?  I'm trying to figure this out, because your code is very useful, and I could see myself using it for other projects as well, where I would want to limit what characters can be inputted.  Seeing as how in other projects I might want to limit the input to a different set of characters, I would like to know how to change it.

 

 

Share this post


Link to post
Share on other sites

#8 ·  Posted (edited)

When you create an input box you can set the length of characters, digits only, Uppercase, Center like this.

GUICtrlCreateInput Style Options

$ES_NUMBER        ==  Accepts only digits [0-9]
$ES_UPPERCASE   ==  Converts all characters to uppercase
$ES_LOWERCASE  ==  Converts all characters to lowercase
$ES_CENTER          ==  Centers text

GUICtrlSetLimit ( controlID, max , OPTIONAL min )  == so you can set a max and min character length for an input control
 

 $UserInput = GUICtrlCreateInput("", 120, 292, 161, 21, BitOR($GUI_SS_DEFAULT_INPUT, $ES_CENTER,$ES_NUMBER))
  GUICtrlSetLimit($UserInput, 10) ; Limit User Input to 10 Characters, can also just use -1 instead of variable of input box if this line is directly under like here

 

 

Edited by iAmNewbe
1 person likes this

Share this post


Link to post
Share on other sites

iAmNewbe,

Thanks! that worked great!  I see that the additional code that mikell sent me was to make the MAC address always appear as uppercase, no matter how it was typed, but thanks to the style options you showed me for GUICtrlCreateInputStyle, I simply added the "$ES_UPPERCASE" style command and it now displays the MAC address always in upper case, no matter how it is typed.

 

Share this post


Link to post
Share on other sites

#10 ·  Posted

There are more options but the rest are mainly display of the box itself those I put above are the most useful. You can also use RegEx as MuffinMan shows for more involved things but if all you want is to limit to digits only that is built in using that style option.  The manual is an important read, I think over the last two weeks I went through it like a 100 times.  

Share this post


Link to post
Share on other sites

#11 ·  Posted (edited)

10 hours ago, GeorgeB said:

where in the code does it specifically state that only a-f and 0-9 and - are allowed?

Sorry for the lack of explanations  :>

In fact the code actually forbids the last character written if not Hex or '-' depending on the length of the string
Here it is, detailed

Local $content = GUICtrlRead($input)
; get the string length
Local $len = StringLen($content)   
; get the last character entered
Local $char = StringRight($content, 1)  
; Mod returns 1 if length=1, 2 if length=2, 0 if length=3, 1 if length=4, etc
Local $mod = Mod($len, 3) 
 
; if NOT ( Mod = 1 or 2 AND the last char is hexadecimal, or Mod = 0 AND the last char is '-' )
If not (( ($mod = 1 or $mod = 2) and StringRegExp($char, '[[:xdigit:]]') ) OR _ 
           ($mod = 0 and $char = "-")) Then 
; then remove the last char and write to the input
       GUICtrlSetData($input, StringTrimRight($content, 1)) 

; i.e. if the last character written is in 5th position, then string length = 5, Mod = 2, so this char must be hexa. If it is not then it will not be written
; and so on

:)

Edited by mikell

Share this post


Link to post
Share on other sites

#12 ·  Posted

I was working on this a while back, wanted to make it a UDF but never put the time to write it to standards.

I used it for quite a few things however.

#include <EditConstants.au3>
#include <GUIConstantsEx.au3>
#include <StaticConstants.au3>
#include <WindowsConstants.au3>

$Form1 = GUICreate("Test GUI", 618, 276, 192, 124)
$Label1 = GUICtrlCreateLabel("Test GUI", 168, 24, 47, 17)
$Button1 = GUICtrlCreateButton("Toggle Validation", 290, 24, 110, 40)
$Input1 = GUICtrlCreateInput("Max 10 Characters", 40, 72, 553, 21)
$Input2 = GUICtrlCreateInput("Numb3rs 0nly", 40, 97, 553, 21)
$Edit1 = GUICtrlCreateEdit("Max 10 Chars Numbers Only + Auto Line Break", 40, 120, 553, 105)
GUISetState(@SW_SHOW)

$iToggle = 1

While 1
 Sleep(10)
 If Mod($iToggle, 2) = 0 Then
;Example 1 Limit to 10 Characters
 _GUIRegExValidate($Input1, "(.{10})(.)", "$1")
;Example 2 Can only type numbers
 _GUIRegExValidate($Input2, "[^\d]", "")
;Example 3 Combind More Than One On Same Input limit to 10 characters, limit to numbers only, line break @ 10 characters to new line
 _GUIRegExValidate($Edit1, "(.{10})(.)", "$1" & @CRLF)
 _GUIRegExValidate($Edit1, "[^\d\r\n]", "")
 EndIf
    $nMsg = GUIGetMsg()
    Switch $nMsg
        Case $GUI_EVENT_CLOSE
            Exit
        Case $Button1
            $iToggle = $iToggle + 1
    EndSwitch
WEnd

Func _GUIRegExValidate($sInputLabel, $sRegExCapture, $sRegExReplace)
    $Step1Read = GUICtrlRead($sInputLabel)
    $Step2Validate = StringRegExpReplace($Step1Read, $sRegExCapture, $sRegExReplace)
    If @Extended = 0 Then Return
    GUICtrlSetData($sInputLabel, $Step2Validate)
EndFunc

Func _WM_COMMAND($hWnd, $Msg, $wParam, $lParam)
 _GUIRegExValidate($Edit1, "(.{20})(.)", "$1")
EndFunc

 

Share this post


Link to post
Share on other sites

#13 ·  Posted

Thanks Mikell for the clarification, and viciousxusmc for that code as well!

Thanks to everybody for all of the great info!  It has been extremely helpful!

 

Share this post


Link to post
Share on other sites

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

  • Similar Content

    • kneze
      search value in text file
      By kneze
      Hi all,
      i would like to enter a vlaue to Inputbox 1 an press button1. Script should search value in a text file and put value after "; " to Inputbox 2.
      #cs ---------------------------------------------------------------------------- AutoIt Version: 3.3.14.2 Author: myName Script Function: Template AutoIt script. #ce ---------------------------------------------------------------------------- ; Script Start - Add your code below here #include <ButtonConstants.au3> #include <EditConstants.au3> #include <GUIConstantsEx.au3> #include <WindowsConstants.au3> #include <file.au3> $Form1 = GUICreate("Form1", 257, 119, 192, 124) $Input1 = GUICtrlCreateInput("Input1", 15, 35, 121, 21) $Input2 = GUICtrlCreateInput("Input2", 15, 60, 121, 21) $Button1 = GUICtrlCreateButton("Button1", 145, 35, 75, 25) GUISetState(@SW_SHOW) $iLines = _FileCountLines(@ScriptDir & "\data.txt") ;MsgBox(0, "Char read:", $ilines) While 1 $nMsg = GUIGetMsg() Switch $nMsg Case $GUI_EVENT_CLOSE Exit Case $Button1 EndSwitch WEnd can anyone help?
      data.txt
    • DavidFigueroa
      Automatically adding leading zero's to inputbox
      By DavidFigueroa
      I'm trying to create an inputbox that automatically formats numbers with leading zeroes when the updown control is used.  I found an example from Melba23 (see below) that shows a step incremented inputbox, and based on that, I tried to create one that would work, but it does not.
      I am creating separate inputs for hours and minutes, and I want to make sure the inputbox is always 2 digits. And right up front, I don't pretend to really understand the DLLStruct* calls.. 
      Melba23's sample:
      #include <GUIConstantsEx.au3> #include <WindowsConstants.au3> #include <UpDownConstants.au3> $hGUI = GUICreate("Test", 500, 500) $hInput = GUICtrlCreateInput("5000", 10, 10, 100, 20) $hUpDown = GUICtrlCreateUpdown($hInput, BitOR($UDS_WRAP, $UDS_NOTHOUSANDS)) GUICtrlSetLimit($hUpDown, 6000, 5000) GUISetState() GUIRegisterMsg($WM_NOTIFY, "_WM_NOTIFY") While 1     Switch GUIGetMsg()         Case $GUI_EVENT_CLOSE             Exit     EndSwitch WEnd Func _WM_NOTIFY($hWnd, $iMsg, $wParam, $lParam)     ; Is it from the UpDown?     If BitAND($wParam, 0xFFFF) = $hUpDown Then         ; Create NMUPDOWN structure         Local $tStruct = DllStructCreate("hwnd;long;int;long;long", $lParam)         ; Is it a change message?         If DllStructGetData($tStruct, 3) = 0xFFFFFD2E Then ; $UDN_DELTAPOS             ; Alter the change value             DllStructSetData($tStruct, 5, 100 * DllStructGetData($tStruct, 5))         EndIf     EndIf EndFunc ;~ The NMUPDOWN structure holds: ;~ 1 - Handle of UpDown ;~ 2 - ControlID of UpDown ;~ 3 - Message type sent by UpDown ;~ 4 - Current value of UpDown ;~ 5 - Change to apply to input (+/-1) And here is my non-working sample (it runs, and the initial value shows correctly, but when you hit the updown, you lose the leading zeroes.
      #include <WindowsConstants.au3> #include <GUIConstantsEx.au3> $hGUI = GUICreate("Window", 300, 100, -1, -1) $Count = 1 Global $hEdit = GUICtrlCreateInput($Count, 15, 15, 100, 30) GUICtrlSetFont(-1, 12, 400, "", "Tahoma") GUICtrlSetData(-1, StringFormat("%03u",$Count)) Global $hUpDown = GUICtrlCreateUpdown(-1) GUICtrlSetLimit(-1, 100, 0) GUISetState() While 1     $hMsg = GUIGetMsg()     Switch $hMsg         Case $GUI_EVENT_CLOSE             Exit     EndSwitch WEnd Func _WM_NOTIFY($hWnd, $iMsg, $wParam, $lParam)     ; Is it from the UpDown?     If BitAND($wParam, 0xFFFF) = $hUpDown Then         ; Create NMUPDOWN structure         Local $tStruct = DllStructCreate("hwnd;long;int;long;long", $lParam)         ; Is it a change message?         If DllStructGetData($tStruct, 3) = 0xFFFFFD2E Then ; $UDN_DELTAPOS             ; Alter the change value             $ValueToSet = DllStructGetData($tStruct, 4)             $ValueToSet = StringFormat("%03u", $ValueToSet)             GUICtrlSetData($hEdit, $ValueToSet)         EndIf     EndIf EndFunc  
    • Comboku
      Recognizing when focus leaves the input field?
      By Comboku
      Hi Guys,
      i am working on a translation app. There are a couple of regular input fields with text that the user is supposed to change to a new language. 
      I want to change the color of the input field  as soon as the user leaves the input field. Is there a way to do that? 
      I know how to do this with a button, but i don't know how i can work with focus. Has any of you done something like this before?
       
      Thanks!
    • cookiemonster
      Allow right click copy on disabled input box
      By cookiemonster
      Hi,
      I have an input box which is disabled, and populates with a value after a button is pressed.
      I want to leave this box disabled after there is a value in it, but still allow the user to right click and copy the boxes contents, is this kind of thing possible somehow?
    • farhadrahman2
      InputBox
      By farhadrahman2
      hey guys, i have a problem .
      I want to search a file in a particular folder and after inserting the name  in the input box i want to make a drop down menu of all the matches and then select it and open it.
      I need the full code .
      so please anyone help me on this one.