MAUI Entry field validation to accept month/year

ahmed omar 181 Reputation points
2023-04-23T15:54:17.6333333+00:00

Hello is there any way to make the entry field takes a value month/year, for example, 01/23? like visa expiration date field so the first value should be from 01 to 30

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,696 questions
0 comments No comments
{count} votes

Accepted answer
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 45,181 Reputation points Microsoft Vendor
    2023-04-24T03:14:48.34+00:00

    Hello,

    In MAUI, you could use regular expressions to make judgments in the Completed event of entry to achieve this requirement.

    You could refer to the following code example:

    Xaml:

    <Entry Placeholder="Please enter the date in mm/yy format" Completed="Entry_Completed"/> 
    <Label x:Name="alert_lab" TextColor="Red" Text="Please re-enter to match mm/yy format, e.g. 01/23." IsVisible="false"/>
    <Button x:Name="submit" Text="Submit" IsEnabled="False"/>
    

    In the xaml code, I declare an alert label to display when the input does not meet the requirements and a button to click when the input is compliant.

    Code-behind:

    private void Entry_Completed(object sender, EventArgs e) 
        {
            var entry = sender as Entry;
            string pattern = @"^(0[1-9]|[12]\d|30)(\-|\/|\.)\d{2}$"; //Regular expressions used to match 01-30
            if(Regex.IsMatch(entry.Text, pattern))
            {
                submit.IsEnabled = true;
                alert_lab.IsVisible = false;
            }
            else
            {
                alert_lab.IsVisible = true;
                submit.IsEnabled = false;
            }
        }
    
    

    Best Regards,

    Alec Liu.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.