user2408588
user2408588

Reputation:

Multipe validation control on single textbox

I have following code snippet in asp.net In which I am validating a Textbox.I have added two validation control in which first validate the format of date and second validates the future data.

Now the problem is both validations fire at the same time. I want that first it's check that date is valid or not then I want to fire rangevalidator.

 <asp:TextBox Enabled="True"  runat="server" size="8" MaxLength="10" meta:resourcekey="txtTravelerDOBResource2">mm/dd/yyyy</asp:TextBox>   
<asp:RangeValidator ID="rangeValidator" ControlToValidate="txtTravelerDOB" MaximumValue="09/25/2013"  MinimumValue="1/1/2012" Type="Date" ErrorMessage="Future Date Not allowed"  runat="server"></asp:RangeValidator>

        <asp:RegularExpressionValidator Enabled="True" ID="rgxDOB" runat="server" ControlToValidate="txtTravelerDOB"
                                                Display="Dynamic" ErrorMessage="Date is not valid"
 ValidationExpression="^(((0?[13578]|1[02])[\/](0?[1-9]|[12]\d|3[01])[\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[13456789]|1[012])[\/](0?[1-9]|[12]\d|30)[\/]((1[6-9]|[2-9]\d)?\d{2}))|(0?2[\/](0?[1-9]|1\d|2[0-8])[\/]((1[6-9]|[2-9]\d)?\d{2}))|(0?2[\/]29[\/]((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00)))$"
                                               ></asp:RegularExpressionValidator>

I tried to enable disable the validation control using javascript as below.

function isGoodDate(){
        var value=$("#ctl09_ctl00_ctl00_ctl00_rptTravelers_ctl01_txtTravelerDOB").val();
        var v=$("#ctl09_ctl00_ctl00_ctl00_rptTravelers_ctl02_txtTravelerDOB").val();

        var reGoodDate = /^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2})*$/;
        console.log(value);
        if(reGoodDate.test(value))
        {

            $.each(Page_Validators, function (index, validator){
                if (validator.validationGroup == "x"){

                    ValidatorEnable(validator, true);

                }
            });
        }
        else
        {
            ValidatorEnable(validator, false);
        }
        if(reGoodDate.test(v))
        {

            $.each(Page_Validators, function (index, validator){
                if (validator.validationGroup == "y"){

                    ValidatorEnable(validator, true);

                }
            });
        }
        else
        {
            ValidatorEnable(validator, false);
        }
    }

Upvotes: 3

Views: 1554

Answers (1)

R.C
R.C

Reputation: 10565

Firstly, all the validators don't fire exactly at same time. They seem so as it happens in a fraction of seconds.

The validators that you add in a .aspx page, they are added to Page.Validators collection in the same order they are created/added to page. The validation runs in the order they are present in the Page.Validators collection.Thus the first validator in the aspx file is first in Page.Validators. If you want to rearrange the order, then the correct way is to arrange your validators in the page in the same order you want them to fire.

NOTE: The validators will fire one by one. in case you don't want the very next validators to fire you may use Javascript to disable the next ones. call a ClientValidation function in first validator

<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="TextBox3"
     ClientValidationFunction="disableNextVal" .... />

// Sample JavaScript code

function disableNextVal()
{
 // firstly check here for first condition, if First condition fails,
 // disable the next validator as below.
  var nextVal = document.getElementById('nextValidatorClientID');
  ValidatorEnable(myVal, false); 
// or use this one:
  myVal.enabled = false;
}

However, one more solution and possibly the better one is mentioned below.

In these scenarios where the value entered in TextBox should pass multiple conditions like:data format, Value should be greater than some minimum required value etc.. it is always good to use a CustomValidator control.

In this custom validator control check one by one each of your conditions. If first condition fails: date is not valid, do not check others and display the error message for first one only. Similarly, if second condition fails: range is not valid, display message for second failed condition only.

<asp:CustomValidator ID= "valxTextBox" runat="server"Enabled="true" 
                            ControlToValidate="txtDate"  
                            ClientValidationFunction ="ValidateTxtDate"   
                            ValidateEmptyText="true"
                            OnServerValidate="valxTextBox_ValidatePostalCode"
></asp:CustomValidator>

As you see, this gives the flexibility to define your custom Client Side as well as server side events for Validation.

In your server validation, check for conditions one by one, and return as soon as you find one failing.

For validating data against regularExpressions, use Regex class of System.Text.RegularExpressions namespace.

protected void valeEmailAddress_txtEmailAddressValidate(object sender,
                                                      ServerValidateEventArgs e)
            {
              string MaximumValue="09/25/2013";
              string MinimumValue="1/1/2012";
               // check for first condition
             if(txtTravelerDOB >MaximumValue ||txtTravelerDOB < MinimumValue )
             {

               // sample code here
              // if failing, set IsValid to false
                 e.IsValid = false; 
                 // dynamically set the error message as per first condition
                 valxTextBox.ErrorMessage ="Not a valid date";  
              }

             // check for second condition
             // read the expression pattern from appSettings
             if(!Regex.Match(txtTravelerDOB.Text.Trim(),
                WebConfigurationManager.AppSettings("travelerDOBRegEX")).Success)
            {
              // if fails, 
                 e.IsValid = false;
                 valxTextBox.ErrorMessage ="Format is Invalid";  
            }
}

Appsettings Value:

<add key="travelerDOBRegEX" value="^(((0?[13578]|1[02])[\/](0?[1-9]|[12]\d|3[01])[\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[13456789]|1[012])[\/](0?[1-9]|[12]\d|30)[\/]((1[6-9]|[2-9]\d)?\d{2}))|(0?2[\/](0?[1-9]|1\d|2[0-8])[\/]((1[6-9]|[2-9]\d)?\d{2}))|(0?2[\/]29[\/]((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00)))$"/>

Upvotes: 1

Related Questions