Compare Validator for two dates

2.3k Views Asked by At

I have two labels and two text boxes, a Compare validator and a button.

I need it to compare two dates (rental date , return date ) and when the rental date is less or equal to return date are the same. No validation message.

While when when the rental date is less than the return date, display an input error message.

The compare validator has been set with :

controltocompare : txtrental,
controltovalidate: txtreturndate,
operator :greater than equal,
type:date,
errormessage: return date must be greater or equal than rental date,

I am not sure how to get the btn to display it ?

3

There are 3 best solutions below

0
On
  1. Create a method to display message.

    private void AlertBox(string Msg) { string s = "alert('" + Msg + "')"; ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ckey", s, true); }

  2. find the code to validate and throw alert message.

                if (!String.IsNullOrEmpty(txtrental.Text) && !String.IsNullOrEmpty(txtreturndate.Text))
                        {
                            DateTime ssSD = Convert.ToDateTime(txtrental.Text);
                            DateTime qsED = Convert.ToDateTime(txtreturndate.Text);
                            int chktxtfd1_sd = ssSD.CompareTo(qsSD);
    
                            if ((chktxtfd1_sd == 0 || chktxtfd1_sd == -1) )
                            {
                                //do something bcoz condition is true
    
                            }
                            else
                            {
    
                                lvflag = false;
                                AlertBox("date must be greater or equal than rental date");
    
                            }
                        }
    

If you find it useful, please mark it as your answer else let me know...

1
On

You need to set the property "CausesValidation" of your button to "true" to trigger validation on its click.

1
On

Make sure the CompareValidator has runat="server"