0
votes

I am trying to enter a valid date in a specified format in a text-box. Can anyone help me to validate the date is entered in a text box is a valid date and its in a DD/MM/YYYY format?

If its not a valid date entered by a user then after pressing tab (click outside from textbox) it should say: date wrongly entered.

View Model:

private DateTime? _txtDateDeRec;

    public DateTime? TxtDateDeRec
    {
        get
        {
            return this._txtDateDeRec;
        }
        set
        {
            this._txtDateDeRec = value;
            OnPropertyChanged("TxtDateDeRec");
        }
    }

XAML Code is:

TextBox x:Name="txtDateDeRec" HorizontalAlignment="Left" Height="23" Margin="555,65,0,0" TextWrapping="Wrap" Text="{Binding TxtDateDeRec}" VerticalAlignment="Top" Width="163"

2
Create an event on field and try to parse with Datetime in c#. Use DateTime.Parse or DateTime.TryParse with your DD/MM/YYYY format. Check here dotnetperls.com/datetime-parse and dotnetperls.com/datetime-tryparseManishM
Thanks a lot, Its working now.... I used as you suggested.Naman
<TextBox x:Name="txtDateDeRec" Text="{Binding TxtDateDeRec, StringFormat={0:dd/MM/yyyy} }" />. You can use StringFormat for the Text binding. This works fine with MVVM pattern.binh nguyen

2 Answers

0
votes
        textBox1.Leave += new EventHandler((sender2, ee) => 
        {
            var textBox = (Control)sender2;
            var date = new DateTime();
            if(DateTime.TryParse(textBox.Text,out date))
            {
                textBox.Text= String.Format("{0:dd/MM/yyyy}", date);
            }
            else
            {
                textBox.Text = "date wrongly entered.";
            }

        });

Update 1: Only format DD/MM/YYY

textBox1.Leave += new EventHandler((sender2, ee) => 
            {
                var textBox = (Control)sender2;
                var date = new DateTime();
                var testResult = DateTime.TryParse(textBox.Text, out date);
                var dateToString = String.Format("{0:dd/MM/yyyy}", date);
                if(testResult==true && textBox.Text.Trim() == dateToString)//Format is the same
                {

                    textBox.Text =dateToString ;
                }

                else
                {
                    textBox.Text = "date wrongly entered.";
                }

            });
0
votes

To validate the datetime format, the Validation Rule can be used in the binding on the text box.

public class DateValidation : ValidationRule 
    { 
        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) 
        { 
            ValidationResult result; 
            try 
            { 
               Regex regex = new Regex(@"^([0]?[0-9]|[12][0-9]|[3][01])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{2})$");

               DateTime? date;

               //Verify whether date entered in dd/mm/yyyy format.
               bool isValid = regex.IsMatch(value.ToString());

               //Verify whether entered date is Valid date.       
               isValid = isValid && DateTime.TryParseExact(value.ToString(), "dd/MM/yyyy", new CultureInfo("en-GB"), DateTimeStyles.None, out date);                                                                                                             

               result = isValid ? new ValidationResult(true,null) : new ValidationResult(false,"Date wrongly entered");  
            }catch(Exception ) 
            { 
                result = new ValidationResult(false,"Date wrongly entered"); 
            } 
            return result; 
        } 
    } 

For textbox add the validation rule as below

<TextBox  x:Name="txtDateDeRec" HorizontalAlignment="Left" Height="23" Margin="555,65,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="163">
    <TextBox.Text>
        <Binding Path="TxtDateDeRec" UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <local:DateValidation/>
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>