Sign in to follow this  
Followers 0
rudi

check for valid file name while entering text

16 posts in this topic

Hi.

I'm 100% sure, that there is some posting with a nice sample code, that uses some GUI with a GUICtrlCreateInput(), and that checks the entered string for not allowed characters for file names. If such a Char was entered, the previous content is restored. By that it was impossible to enter invalid Chars.

I cannot find it. :)

Who, please, can open my blind eyes?

Regards, Rudi.


Earth is flat, pigs can fly, and Nuclear Power is SAFE!

Share this post


Link to post
Share on other sites



#2 ·  Posted (edited)

File name cannot contain this characters "\/:*?"<>|" so using StringRegExp($sFile, '[\\/:*?"<>|]) will return true to indicate a non-valid file name in this case, most of the quantifiers or metacharacters don't retain their special meaning withing a class so use \Q...\E if you're not sure.

Same for the path\filename.exe:

Dim $aFile = StringRegExp($sFile, '(.*\\)(.*)', 3)

Results in an array with two elements if it's a valid path or 1 or non-array if it's not a valid file string. The rest is to check whether the file exists.

Edit: My bad... search for subclassing of the control's message loop and assign yours and return the rest unhandled events to the previous or original message loop of the control.

Edited by Authenticity

Share this post


Link to post
Share on other sites

#3 ·  Posted (edited)

I forget the list of invalid Characters but all you have to do is check the last character of the input against the list and if it exists in the list then use GUICtrlSetData() to trim that character.

$sNotAllowed = "?\;"

While 1
    $sCurrentChar = StringRight(GUICtrlRead($input), 1)
    If StringInStr($sNotAllowed, $sCurrentChar) Then GUICtrlSetData($input, StringTrimRight(GUICtrlRead($input), 1))
Wend
Edited by GEOSoft

George

Question about decompiling code? Read the decompiling FAQ and don't bother posting the question in the forums.

Be sure to read and follow the forum rules. -AKA the AutoIt Reading and Comprehension Skills test.***

The PCRE (Regular Expression) ToolKit for AutoIT - (Updated Oct 20, 2011 ver:3.0.1.13) - Please update your current version before filing any bug reports. The installer now includes both 32 and 64 bit versions. No change in version number.

Visit my Blog .. currently not active but it will soon be resplendent with news and views. Also please remove any links you may have to my website. it is soon to be closed and replaced with something else.

"Old age and treachery will always overcome youth and skill!"

Share this post


Link to post
Share on other sites

#include <Constants.au3>
#include <WinAPI.au3>
#include <WindowsConstants.au3>
Opt('MustDeclareVars', 1)


Dim $hUser32 = DllOpen('user32.dll')
Dim $hGUI = GUICreate ('Title', 200, 100)
Dim $Input = GUICtrlCreateInput ('', 0, 0, 200, 100)
Dim $hInput_Handler = DllCallbackRegister ('Input_Handler', 'lparam', 'hwnd;uint;wparam;lparam')
    If 0 = $hInput_Handler Then Exit

Dim $hOldProc = _WinAPI_GetWindowLong (GUICtrlGetHandle($Input), $GWL_WNDPROC)
_WinAPI_SetWindowLong (GUICtrlGetHandle($Input), $GWL_WNDPROC, DllCallbackGetPtr($hInput_Handler))

GUISetState()

Do
    Sleep (20)
Until GUIGetMsg() = -3


GUIDelete($hGUI)
DllCallbackFree($hInput_Handler)
DllClose($hUser32)
Exit


Func Input_Handler($hWnd, $uMsg, $wParam, $lParam)
    If $uMsg = $WM_CHAR Then
        If StringRegExp(Chr($wParam), '[\Q\/:*?"<>|\E]') Then Return 0
    EndIf
    
    Local $Ret = DllCall($hUser32, 'int', 'CallWindowProc', 'ptr', $hOldProc, 'hwnd', $hWnd, 'uint', $uMsg, 'wparam', $wParam, 'lparam', $lParam)
    If Not @error Then Return $Ret[0]
EndFunc

You can modify it to get the window text of $hWnd to restore the old text or...

Share this post


Link to post
Share on other sites

#5 ·  Posted (edited)

Hi.

I will have a closer look to your code right now.

What I've seen was about this, but *MUCH* better code:

[edit] I think it was just 15 lines, about... [/edit]

#include <guiconstantsEx.au3>
; ['<', '>', '|', '"', '\', '/', ':', '*', '?']

$w = 200
$h = 100
$MyGui = GUICreate("Enter valid file name", $w, $h)
$input = GUICtrlCreateInput("", 20, 20, $w - 40, 20)
$button = GUICtrlCreateButton("Done", 20, 70)
GUISetState(@SW_SHOW)

$start = TimerInit()
While 1
    $WinPos = WinGetPos($MyGui)
    $msg = GUIGetMsg()
    Select
        Case $msg = $GUI_EVENT_CLOSE
            If GUICtrlRead($input) = "" Then
                MsgBox(48, "Nothing entered", "Empty file names are *NOT* allowed")
            Else
                ExitLoop
            EndIf
        Case $msg = $button
            If GUICtrlRead($input) = "" Then
                MsgBox(48, "Nothing entered", "Empty file names are *NOT* allowed")
            Else
                ExitLoop
            EndIf
    EndSelect
    $String = GUICtrlRead($input)
    $valid = StringRegExpReplace($String, "[\[\]/\|\:\?""\*\\<>]", "")
    If Not ($valid = $String) Then
        $start = TimerInit()
        ToolTip("Not allowed Characters: '<', '>', '|', '""', '\', '/', ':', '*', '?'", $WinPos[0], $WinPos[1] + 70)
    EndIf
    GUICtrlSetData($input, $valid)
    If TimerDiff($start) > 2000 Then ToolTip("")
    Sleep(10)
WEnd

$final = GUICtrlRead($input)
GUIDelete()

MsgBox(0, "Valid Filename:", $final)

Regards, Rudi.

Edited by rudi

Earth is flat, pigs can fly, and Nuclear Power is SAFE!

Share this post


Link to post
Share on other sites

StringRegExp(Chr($wParam), '[\Q\/:*?"<>|\E]')
Ah! I didn't know this "\Q" ...."\E" to "bulk escape" a string. Very nice!

The rest I will have to dig though step by step.

Thanks, Rudi.


Earth is flat, pigs can fly, and Nuclear Power is SAFE!

Share this post


Link to post
Share on other sites

Hi.

I forget the list of invalid Characters ...

It's these: '<', '>', '|', '"', '\', '/', ':', '*', '?'

Thanks, regards, Rudi.


Earth is flat, pigs can fly, and Nuclear Power is SAFE!

Share this post


Link to post
Share on other sites

One thing to consider: '/' is translated by Windows functions to '\', so if anything contains a path keep that in mind.

Also invalid for files/foldernames are whitespace before or after a filename (it's okay between). But to test that in real-time wouldn't work.

Share this post


Link to post
Share on other sites

This is for the FileExist function. The rest deal with what is not valid for a filename, file path can contain \ or it must lol so filtering it was taken as consideration that the input box meant to hold only valid file names. Whether the input box contain a space in front of the text? it's for the FileExist to test it.

Share this post


Link to post
Share on other sites

Also invalid for files/foldernames are whitespace before or after a filename (it's okay between).

Sorry, but that's nonsense:

LEADING whitspaces are fine for Windows.

TRAILING whitespaces simply are truncated.

Check yourself:

--------- whitespacechecker.cmd------------
@echo off
echo. > "     with spaces   . txt   "
for %%a in (*with*) do echo "%%a"
------------------ EOF -------------------------

But to test that in real-time wouldn't work.

Why not? StringRegExp is offering the matches "^\s" and "\s$", but I can't see the need for it?

Regards, Rudi.


Earth is flat, pigs can fly, and Nuclear Power is SAFE!

Share this post


Link to post
Share on other sites

....

LEADING whitspaces are fine for Windows.

TRAILING whitespaces simply are truncated.

...

Actually, the opposite is the correct one:

" some.txt" is truncated to "some.txt" while,

"some.txt " remains "some.txt "

Share this post


Link to post
Share on other sites

#12 ·  Posted (edited)

Sorry, but that's nonsense:

LEADING whitspaces are fine for Windows.

TRAILING whitespaces simply are truncated.

...

Regards, Rudi.

For *filenames*, yes, TRAILING whitespace is okay. NO leading whitespace is okay though.

If Not FileExists(@ScriptDir & '\ ' & @ScriptName) Then ConsoleWriteError('"' & @ScriptDir & '\ ' & @ScriptName & '" does NOT exist' & @CRLF)

For FOLDERnames *within* a path, BOTH are not okay, but since we are only dealing with filenames, you don't have to deal with that.

*also, testing for trailing whitespace in realtime is not possible, as there can be spaces within folder\filenames

Edited by ascendant

Share this post


Link to post
Share on other sites

Actually, the opposite is the correct one:

" some.txt" is truncated to "some.txt" while,

"some.txt " remains "some.txt "

Pls save my sample CMD batch file, open a CMD box, run it and see, what I mean :)

Regards, Rudi.


Earth is flat, pigs can fly, and Nuclear Power is SAFE!

Share this post


Link to post
Share on other sites

Okay, I gave it a test with DirCreate() and FileWrite(), and you're right - It *does* allow leading whitespace.

It doesn't allow it when you create something through Explorer though - that's probably where I got my mistaken belief from.

Anyway, thanks for enlightening me

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
Sign in to follow this  
Followers 0