Example #1
0
 internal override void RegisterClientRules(InputControlBase ctlInputControl)
 {
     if (!string.IsNullOrEmpty(this.Rule))
     {
         DoRegisterValidator(ctlInputControl, this.Rule, this.Params, null);
     }
 }
Example #2
0
        /// <summary>
        /// 1) Script to automatically check the associated button when the value in the input control is
        /// manipulated by the user.
        /// 2) Script to prevent all other validations if the filter is being disabled
        /// </summary>
        /// <param name="ctlInputControl">The control with which the filter is associated</param>
        /// <exception cref="NotImplementedException"></exception>
        /// <remarks>
        /// <para>
        /// A dummy validation rule, which always returns true, called <c>filter</c> is associated with the input control.
        /// A client script is associated with the <see cref="InputControlBase.ClientChangeEventName"/> event of the control
        /// specified in <see cref="ValidatorBase.DependsOn"/>. This client script toggles the
        /// <see cref="JQueryScriptManager.CssClassIgnoreValidation"/> depending on whether the dependency is satisfied or not.
        /// </para>
        /// </remarks>
        internal override void RegisterClientRules(InputControlBase ctlInputControl)
        {
            const string NEW_RULE = @"
$.validator.addMethod('filter', function() { return true; });
function filter_fixDependent(elementSelector) {
    var $element = $(elementSelector);
    var filter = $element.closest('form').validate().settings.rules[$element.attr('name')].filter;
    var keepRule = filter.depends.call($element[0], $element[0]);
    $element.toggleClass('val-ignore', !keepRule);
}
";

            JQueryScriptManager.Current.RegisterScriptBlock("filter_validator", NEW_RULE);
            //ctlInputControl.ClientIdRequired = true;    // Since we are referencing it in the function
            DoRegisterValidator(ctlInputControl, "filter", true, null);

            string onDependeeChange = string.Format(@"function (e) {{
filter_fixDependent('{0}');
}}", ctlInputControl.GetClientCode(ClientCodeType.InputSelector));

            if (this.DependsOnState == DependsOnState.Custom)
            {
                //TODO: The programmer is responsible for creating the client side vent handler
                throw new NotImplementedException();
            }
            InputControlBase ctlRadio = GetDependsOnControl(ctlInputControl);

            if (ctlRadio != null)
            {
                ctlRadio.ClientEvents.Add(ctlRadio.ClientChangeEventName, onDependeeChange);
            }
            return;
        }
Example #3
0
 /// <summary>
 /// Performs server side valdiation
 /// </summary>
 /// <param name="ctlInputControl">The control to be validated</param>
 /// <returns>true if validation succeeds</returns>
 /// <remarks>
 /// Accesses the abstract <see cref="P:EclipseLibrary.Web.JQuery.Input.InputControlBase.Value"/> property
 /// of <see cref="InputControlBase"/> base class and returns true if the returned value in non empty after trimming.
 /// </remarks>
 protected override bool OnServerValidate(InputControlBase ctlInputControl)
 {
     if (ctlInputControl.Value == null || string.IsNullOrEmpty(ctlInputControl.Value.Trim()))
     {
         ctlInputControl.ErrorMessage = string.Format("{0} is required", ctlInputControl.FriendlyName);
         ctlInputControl.IsValid      = false;
     }
     return(base.OnServerValidate(ctlInputControl));
 }
Example #4
0
        // ReSharper restore EventNeverSubscribedTo.Global

        /// <summary>
        /// This is called during the server validation cycle and performs the same validation on server side.
        /// Derived classes should override this function and call the base class first. If the base class
        /// returns false, they should do nothing else. Otherwise they must perform their validations.
        /// </summary>
        /// <param name="ctlInputControl"></param>
        /// <returns>true if validation should continue for this control, false otherwise</returns>
        public bool Validate(InputControlBase ctlInputControl)
        {
            bool bNeedsToBeValidated = string.IsNullOrEmpty(this.DependsOn) || PerformDependencyCheck(ctlInputControl);

            if (bNeedsToBeValidated)
            {
                ctlInputControl.IsValid = true;
                return(OnServerValidate(ctlInputControl));
            }
            return(ServerValidationBypassed(ctlInputControl));
        }
Example #5
0
        // ReSharper restore EventNeverSubscribedTo.Global

        /// <summary>
        /// Provide code to perform server side validation
        /// </summary>
        /// <param name="ctlInputControl"></param>
        /// <returns>true if other validators should be invoked</returns>
        /// <remarks>
        /// <para>
        /// Validation is stopped if the validator fails
        /// </para>
        /// </remarks>
        protected virtual bool OnServerValidate(InputControlBase ctlInputControl)
        {
            if (ServerValidate != null)
            {
                ServerValidateEventArgs args = new ServerValidateEventArgs
                {
                    ControlToValidate = ctlInputControl
                };
                ServerValidate(this, args);
            }
            return(ctlInputControl.IsValid);
        }
Example #6
0
        /// <summary>
        /// Helper function to register the validation rule with the script manager.
        /// If ID has been specified, cloneScript is used to clone the rule
        /// </summary>
        /// <param name="ctlInputControl">The control for which client validation needs to be registered</param>
        /// <param name="ruleName">The name of the client validation rule</param>
        /// <param name="jqRuleParams">Parameters to pass to the rule in javascript syntax</param>
        /// <param name="defaultMsg">Used only if MessageFormatString is empty</param>
        protected void DoRegisterValidator(InputControlBase ctlInputControl, string ruleName, object jqRuleParams, object defaultMsg)
        {
            object script = GetDependencyFunction(ctlInputControl);

            if (script != null)
            {
                JQueryOptions options = new JQueryOptions();
                options.Add("param", jqRuleParams);
                options.Add("depends", script);
                jqRuleParams = options;
            }

            object msg;

            if (!string.IsNullOrEmpty(this.ClientMessageFunction))
            {
                msg = new JScriptCode(this.ClientMessageFunction);
            }
            else if (!string.IsNullOrEmpty(this.ClientMessage))
            {
                // Special handling. Show row number when control within grid.
                GridViewRow row = ctlInputControl.NamingContainer as GridViewRow;
                if (row == null)
                {
                    msg = this.ClientMessage;
                }
                else
                {
                    msg = string.Format("Row {0}: ", row.RowIndex + 1) + this.ClientMessage;
                }
            }
            else if (defaultMsg is string)
            {
                // Special handling. Show row number when control within grid.
                GridViewRow row = ctlInputControl.NamingContainer as GridViewRow;
                if (row == null)
                {
                    msg = defaultMsg;
                }
                else
                {
                    msg = string.Format("Row {0}: ", row.RowIndex + 1) + defaultMsg;
                }
            }
            else
            {
                msg = defaultMsg;
            }

            JQueryScriptManager.Current.AddValidationRule(ctlInputControl, ruleName, jqRuleParams, msg);
        }
Example #7
0
        /// <summary>
        /// Crete rules for Min and Max.
        /// </summary>
        /// <param name="ctlInputControl"></param>
        private void RegisterNumericRules(InputControlBase ctlInputControl)
        {
            string script;

            if (this.Min.HasValue)
            {
                // Sharad 21 Sep 2010: making min numeric specific. Tolerates commas
                script = @"$.validator.addMethod('greaterthan', function(value, element, params) {
    if (this.optional(element)) {
        return true;
    }
    var val = Number(value.replace(/,/g, ''));
    return isNaN(val) || val >= params;
});";
                JQueryScriptManager.Current.RegisterScriptBlock("greaterthan_validator", script);
                DoRegisterValidator(ctlInputControl, "greaterthan", this.Min,
                                    string.Format("{0} must be {{0}} or more", ctlInputControl.FriendlyName));
            }
            if (this.Max.HasValue)
            {
                // Sharad 21 Sep 2010: making min numeric specific. Tolerates commas
                script = @"$.validator.addMethod('lessthan', function(value, element, params) {
    if (this.optional(element)) {
        return true;
    }
    var val = Number(value.replace(/,/g, ''));
    return isNaN(val) || val <= params;
});";
                JQueryScriptManager.Current.RegisterScriptBlock("lessthan_validator", script);
                DoRegisterValidator(ctlInputControl, "max", this.Max,
                                    string.Format("{0} must be {{0}} or less", ctlInputControl.FriendlyName));
            }
            if (!string.IsNullOrEmpty(this.MinControlID))
            {
                // param is the selector of the associated control
                script = @"if (this.optional(element)) return true;
var thisVal = Number(value);
var otherVal = Number($(param).val());
if (isNaN(otherVal) || isNaN(thisVal)) return true;
return thisVal >= otherVal;";
                string newRule = "$.validator.addMethod('minfromctl', function(value, element, param) {"
                                 + script + "});";
                JQueryScriptManager.Current.RegisterScriptBlock("minfromctl_validator", newRule);

                InputControlBase ctlMin  = (InputControlBase)ctlInputControl.NamingContainer.FindControl(this.MinControlID);
                string           jqParam = ctlMin.ClientSelector;
                string           jqMsg   = string.Format("'{0} must be same as or more than {1}'",
                                                         ctlInputControl.FriendlyName, ctlMin.FriendlyName);
                DoRegisterValidator(ctlInputControl, "minfromctl", jqParam, jqMsg);
            }
        }
Example #8
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="ctlInputControl"></param>
        /// <returns>true if dependency check succeeds</returns>
        internal bool PerformDependencyCheck(InputControlBase ctlInputControl)
        {
            bool             bNeedsToBeValidated;
            InputControlBase ctlDependsOn;

            switch (this.DependsOnState)
            {
            case DependsOnState.Checked:
                // Validate only of value is non empty
                ctlDependsOn        = GetDependsOnControl(ctlInputControl);
                bNeedsToBeValidated = !string.IsNullOrWhiteSpace(ctlDependsOn.Value);
                break;

            case DependsOnState.Unchecked:
                // Validate only if value is empty
                ctlDependsOn        = GetDependsOnControl(ctlInputControl);
                bNeedsToBeValidated = string.IsNullOrWhiteSpace(ctlDependsOn.Value);
                break;

            case DependsOnState.Value:
                ctlDependsOn        = GetDependsOnControl(ctlInputControl);
                bNeedsToBeValidated = ctlDependsOn.Value.Trim() == this.DependsOnValue;
                break;

            case DependsOnState.AnyValue:
                ctlDependsOn        = GetDependsOnControl(ctlInputControl);
                bNeedsToBeValidated = this.DependsOnValue.Contains(ctlDependsOn.Value.Trim());
                break;

            case DependsOnState.Selector:
            case DependsOnState.Custom:
                DependencyCheckEventArgs args = new DependencyCheckEventArgs
                {
                    ControlToValidate = ctlInputControl
                };
                OnServerDependencyCheck(args);
                bNeedsToBeValidated = args.NeedsToBeValdiated;
                break;

            case DependsOnState.NotSet:
                bNeedsToBeValidated = false;
                break;

            default:
                throw new NotImplementedException();
            }
            return(bNeedsToBeValidated);
        }
Example #9
0
        /// <summary>
        /// Returns the associated From control
        /// </summary>
        /// <param name="ctlInputControl"></param>
        /// <returns></returns>
        public TextBoxEx GetFromControl(InputControlBase ctlInputControl)
        {
            TextBoxEx tbFrom;

            if (string.IsNullOrEmpty(this.AssociatedControlID))
            {
                // Previous control is From Date
                tbFrom = ctlInputControl.Parent.Controls.OfType <TextBoxEx>().Reverse()
                         .SkipWhile(p => p != ctlInputControl).Skip(1).First();
            }
            else
            {
                tbFrom = (TextBoxEx)ctlInputControl.FindControl(this.AssociatedControlID);
            }
            return(tbFrom);
        }
Example #10
0
        /// <summary>
        /// Attach a datepicker with the textbox
        /// </summary>
        /// <param name="ctlInputControl"></param>
        private void RegisterDatePicker(InputControlBase ctlInputControl)
        {
            JQueryOptions options = new JQueryOptions();

            options.Add("showOn", "button");
            string script;

            if (this.Min.HasValue)
            {
                options.Add("minDate", this.Min.Value);
                options.Add("origMinDays", this.Min.Value);
            }
            if (this.Max.HasValue)
            {
                options.Add("maxDate", this.Max.Value);
                options.Add("origMaxDays", this.Max.Value);
            }

            script = string.Format("$('{0}').datepicker({1});", ctlInputControl.ClientSelector, options);
            JQueryScriptManager.Current.RegisterReadyScript(script);
        }
Example #11
0
        /// <summary>
        /// Attempts to find the control in the naming container of the passed control and all naming containers
        /// above it. Throws an exception if the control cannot be resolved.
        /// </summary>
        /// <param name="ctl"></param>
        /// <exception cref="NotImplementedException"></exception>
        /// <returns></returns>
        protected InputControlBase GetDependsOnControl(InputControlBase ctl)
        {
            switch (this.DependsOnState)
            {
            case DependsOnState.Checked:
            case DependsOnState.Unchecked:
            case DependsOnState.Value:
            case DependsOnState.AnyValue:
                break;

            case DependsOnState.NotSet:
            case DependsOnState.Custom:
            case DependsOnState.Selector:
                return(null);

            default:
                throw new NotImplementedException();
            }

            if (_dependsOnControl == null && !string.IsNullOrEmpty(this.DependsOn))
            {
                InputControlBase ctlReturn    = null;
                Control          curContainer = ctl;
                while (ctlReturn == null && !(curContainer is Page))
                {
                    curContainer = curContainer.NamingContainer;
                    ctlReturn    = (InputControlBase)curContainer.FindControl(this.DependsOn);
                }
                if (ctlReturn == null)
                {
                    string str = string.Format("Control {0} could not be found in any of the naming containers above {1}",
                                               this.DependsOn, ctl.ID);
                    throw new ArgumentException(str);
                }
                _dependsOnControl = ctlReturn;
            }
            return(_dependsOnControl);
        }
Example #12
0
        internal void CreateCascadeScripts(InputControlBase ctlPassed)
        {
            if (string.IsNullOrEmpty(this.WebMethod))
            {
                // We are not cascadable. Nothing to do.
                return;
            }
            string loadData = ctlPassed.GetClientCode(ClientCodeType.LoadData);

            // If there is no way to load data, then we are not cascadable even if web method has been specified.
            // AutoComplete provides its own implementation for cascadable properties
            if (string.IsNullOrEmpty(loadData))
            {
                return;
            }
            string str;

            // JSON stringifies data passed to the web method
            JQueryScriptManager.Current.RegisterScripts(ScriptTypes.Json | ScriptTypes.Core | ScriptTypes.Cascade);
            JQueryOptions options = new JQueryOptions();

            if (!string.IsNullOrEmpty(this.CascadeParentId))
            {
                InputControlBase ctlParent = (InputControlBase)ctlPassed.NamingContainer.FindControl(this.CascadeParentId);
                if (ctlParent == null)
                {
                    str = string.Format("Could not find cascade parent {0}", this.CascadeParentId);
                    throw new InvalidOperationException(str);
                }
                options.Add("parentChangeEventName", ctlParent.ClientChangeEventName);
                options.AddRaw("parentValue", ctlParent.GetClientCode(ClientCodeType.GetValue));
                options.Add("cascadeParentSelector", ctlParent.ClientSelector);
                //ctlParent.ClientIdRequired = true;
            }
            if (string.IsNullOrEmpty(this.WebServicePath))
            {
                options.Add("webServicePath", ctlPassed.Page.Request.Path);
            }
            else
            {
                options.Add("webServicePath", ctlPassed.Page.ResolveUrl(this.WebServicePath));
            }
            options.Add("webMethodName", this.WebMethod);
            options.AddRaw("loadData", loadData);
            str = ctlPassed.GetClientCode(ClientCodeType.PreLoadData);
            if (!string.IsNullOrEmpty(str))
            {
                options.AddRaw("preLoadData", str);
            }
            options.Add("interestEvent", ctlPassed.GetClientCode(ClientCodeType.InterestEvent));
            //if (!ctlPassed.Page.IsPostBack && this.InitializeAtStartup)
            if (this.InitializeAtStartup)
            {
                options.Add("initializeAtStartup", this.InitializeAtStartup);
            }
            //if (this.HideParentsFromChildren)
            //{
            //    options.Add("hideParentsFromChildren", true);
            //}
            str = string.Format(".cascade({0})", options.ToJson());
            ctlPassed.ReadyScripts.Add(str);
        }
Example #13
0
 protected virtual bool ServerValidationBypassed(InputControlBase ctlInputControl)
 {
     return(false);
 }
Example #14
0
        /// <summary>
        /// Registers the rules for client validation
        /// </summary>
        /// <param name="ctlInputControl"></param>
        internal override void RegisterClientRules(InputControlBase ctlInputControl)
        {
            string msg;

            if (_isDirty && !ctlInputControl.EnableViewState)
            {
                msg = string.Format("Since you are updating validator property values dynamically, EnableViewState must be true for {0}",
                                    ctlInputControl.ID);
                throw new HttpException(msg);
            }
            //string script;
            switch (this.ValueType)
            {
            case ValidationValueType.String:
                if (this.Min.HasValue || this.Max.HasValue)
                {
                    throw new NotSupportedException(ctlInputControl.ID + ": Min and Max are not supported for string values");
                }
                break;

            case ValidationValueType.Integer:
                if (this.Min.HasValue && this.Min >= 0)
                {
                    DoRegisterValidator(ctlInputControl, "digits", true,
                                        string.Format("{0} must contain only digits", ctlInputControl.FriendlyName));
                }
                else
                {
                    // Creating a new rule which allows leading negative character
                    string newRule = @"$.validator.addMethod('integer', function(value, element, params) {
    return this.optional(element) || /^-{0,1}\d+$/.test(value);
});";
                    JQueryScriptManager.Current.RegisterScriptBlock("integer_validator", newRule);
                    DoRegisterValidator(ctlInputControl, "integer", true,
                                        string.Format("{0} must contain only digits, with an optional leading minus sign",
                                                      ctlInputControl.FriendlyName));
                }
                RegisterNumericRules(ctlInputControl);
                break;

            case ValidationValueType.Decimal:
                DoRegisterValidator(ctlInputControl, "number", true,
                                    string.Format("{0} must be a valid decimal number", ctlInputControl.FriendlyName));
                RegisterNumericRules(ctlInputControl);
                break;

            default:
                throw new NotImplementedException();
            }

            if (this.MinLength > 0)
            {
                msg = ctlInputControl.GetClientCode(ClientCodeType.MinLengthErrorMessage);
                DoRegisterValidator(ctlInputControl, "minlength", this.MinLength, msg);
            }
            if (this.MaxLength > 0)
            {
                msg = ctlInputControl.GetClientCode(ClientCodeType.MaxLengthErrorMessage);
                DoRegisterValidator(ctlInputControl, "maxlength", this.MaxLength, msg);
            }
        }
Example #15
0
        /// <summary>
        /// TODO: Date validation
        /// </summary>
        /// <param name="ctlInputControl"></param>
        /// <returns></returns>
        protected override bool OnServerValidate(InputControlBase ctlInputControl)
        {
            if (string.IsNullOrEmpty(ctlInputControl.Value))
            {
                return(true);        // Empty values are valid
            }
            if (this.MinLength > 0)
            {
                if (ctlInputControl is CheckBoxListEx)
                {
                    ctlInputControl.IsValid      = ctlInputControl.Value.Split(new char[] { ',' }).Length >= this.MinLength;
                    ctlInputControl.ErrorMessage = string.Format("Select at least {1} {0}", ctlInputControl.FriendlyName, this.MinLength);
                }
                else
                {
                    ctlInputControl.IsValid      = ctlInputControl.Value.Length >= this.MinLength;
                    ctlInputControl.ErrorMessage = string.Format("{0} must contain at least {1} characters", ctlInputControl.FriendlyName, this.MinLength);
                }
            }
            if (!ctlInputControl.IsValid)
            {
                return(base.OnServerValidate(ctlInputControl));
            }
            if (this.MaxLength > 0)
            {
                if (ctlInputControl is CheckBoxListEx)
                {
                    ctlInputControl.IsValid      = ctlInputControl.Value.Split(new char[] { ',' }).Length <= this.MaxLength;
                    ctlInputControl.ErrorMessage = string.Format("Select at most {1} {0}", ctlInputControl.FriendlyName, this.MaxLength);
                }
                else
                {
                    ctlInputControl.IsValid      = ctlInputControl.Value.Length <= this.MaxLength;
                    ctlInputControl.ErrorMessage = string.Format("{0} must contain at most {1} characters",
                                                                 ctlInputControl.FriendlyName, this.MaxLength);
                }
            }
            if (!ctlInputControl.IsValid)
            {
                return(base.OnServerValidate(ctlInputControl));
            }
            decimal d;

            switch (this.ValueType)
            {
            case ValidationValueType.String:
                ctlInputControl.IsValid = true;
                d = 0;
                break;

            case ValidationValueType.Integer:
                Int64 n;
                ctlInputControl.IsValid = Int64.TryParse(ctlInputControl.Value, out n);
                if (ctlInputControl.IsValid)
                {
                    d = n;
                }
                else
                {
                    ctlInputControl.ErrorMessage = string.Format("{0} must be a valid integer", ctlInputControl.FriendlyName);
                    d = 0;
                }
                break;

            case ValidationValueType.Decimal:
                ctlInputControl.IsValid = decimal.TryParse(ctlInputControl.Value, out d);
                if (!ctlInputControl.IsValid)
                {
                    ctlInputControl.ErrorMessage = string.Format("{0} must be a valid decimal", ctlInputControl.FriendlyName);
                }
                break;

            default:
                throw new NotImplementedException();
            }

            if (!ctlInputControl.IsValid)
            {
                return(base.OnServerValidate(ctlInputControl));
            }

            if (this.Min.HasValue || this.Max.HasValue)
            {
                if (this.Min.HasValue && this.Max.HasValue)
                {
                    ctlInputControl.IsValid = d >= this.Min.Value && d <= this.Max.Value;
                    if (!ctlInputControl.IsValid)
                    {
                        ctlInputControl.ErrorMessage = string.Format(MSG2_BETWEEN, ctlInputControl.FriendlyName);
                    }
                }
                else if (this.Min.HasValue)
                {
                    ctlInputControl.IsValid = d >= this.Min.Value;
                    if (!ctlInputControl.IsValid)
                    {
                        ctlInputControl.ErrorMessage = string.Format(MSG1_MIN, ctlInputControl.FriendlyName, this.Min);
                    }
                }
                else if (this.Max.HasValue)
                {
                    ctlInputControl.IsValid = d <= this.Max.Value;
                    if (!ctlInputControl.IsValid)
                    {
                        ctlInputControl.ErrorMessage = string.Format(MSG1_MAX, ctlInputControl.FriendlyName, this.Max);
                    }
                }
            }
            if (!ctlInputControl.IsValid)
            {
                return(base.OnServerValidate(ctlInputControl));
            }
            if (!string.IsNullOrEmpty(this.MinControlID))
            {
                InputControlBase ctlMin = (InputControlBase)ctlInputControl.NamingContainer.FindControl(this.MinControlID);
                decimal          otherVal;
                if (decimal.TryParse(ctlMin.Value, out otherVal))
                {
                    ctlInputControl.IsValid = d >= otherVal;
                    if (!ctlInputControl.IsValid)
                    {
                        ctlInputControl.ErrorMessage = string.Format("{0} must be greater than or equal to {1}",
                                                                     ctlInputControl.FriendlyName, ctlMin.FriendlyName);
                        return(base.OnServerValidate(ctlInputControl));
                    }
                }
            }
            return(base.OnServerValidate(ctlInputControl));
        }
Example #16
0
 /// <summary>
 /// Set <see cref="InputControlBase.FilterDisabled"/> to true.
 /// </summary>
 /// <param name="ctlInputControl"></param>
 /// <returns>false to indicate that validation should not continue</returns>
 protected override bool ServerValidationBypassed(InputControlBase ctlInputControl)
 {
     ctlInputControl.FilterDisabled = true;
     return(false);
 }
Example #17
0
 /// <summary>
 /// Always returns true.
 /// </summary>
 /// <param name="ctlInput"></param>
 /// <returns>true</returns>
 /// <remarks>
 /// <para>
 /// This valdiator does not perform any server side validation so this function always returns true.
 /// The base class is not called to prevent arising hte <see cref="ValidatorBase.ServerValidate"/> event.
 /// </para>
 /// </remarks>
 protected override bool OnServerValidate(InputControlBase ctlInput)
 {
     return(true);
 }
Example #18
0
        private object GetDependencyFunction(InputControlBase ctlInputControl)
        {
            switch (this.DependsOnState)
            {
            case DependsOnState.Custom:
                // DependsOn is the custom function
                if (string.IsNullOrEmpty(this.DependsOn))
                {
                    string msg = string.Format("Control {0}: DependsOn must be specified when DependsOnState=Custom",
                                               ctlInputControl.ID);
                    throw new InvalidOperationException(msg);
                }
                return(new JScriptCode(this.DependsOn));

            case DependsOnState.Selector:
                // DependsOn is the custom function
                if (string.IsNullOrEmpty(this.DependsOn))
                {
                    string msg = string.Format("Control {0}: DependsOn must be specified when DependsOnState=Custom",
                                               ctlInputControl.ID);
                    throw new InvalidOperationException(msg);
                }
                return(this.DependsOn);

            case DependsOnState.NotSet:
                return(null);
            }

            InputControlBase ctlDependsOn = GetDependsOnControl(ctlInputControl);

            if (ctlDependsOn == null)
            {
                return(null);
            }
            StringBuilder sb = new StringBuilder("function(element) {");

            // We must ensure that the client id of ctlDependsOn is generated because our script will be referencing it
            //ctlDependsOn.ClientIdRequired = true;
            sb.AppendFormat("var $dependee = $('#{0}', $(element).closest('form'));", ctlDependsOn.ClientID);
            sb.AppendFormat("var valDependee = ({0}).call($dependee[0]);", ctlDependsOn.GetClientCode(ClientCodeType.GetValue));

            switch (this.DependsOnState)
            {
            case DependsOnState.Checked:
                sb.Append("var okToValidate = (valDependee != '');");
                break;

            case DependsOnState.Unchecked:
                sb.Append("var okToValidate = (valDependee == '');");
                break;

            case DependsOnState.Value:
                sb.AppendFormat("var okToValidate = (valDependee == '{0}');",
                                this.DependsOnValue);
                break;

            case DependsOnState.AnyValue:
                JavaScriptSerializer ser = new JavaScriptSerializer();
                string str = ser.Serialize(this.DependsOnValue.Split(','));
                sb.AppendFormat("var okToValidate = ($.inArray(valDependee, {0}) >= 0);", str);
                break;

            default:
                throw new NotImplementedException();
            }
            sb.Append("return okToValidate;");
            sb.Append("}");
            return(new JScriptCode(sb.ToString()));
        }
Example #19
0
 /// <summary>
 /// You can set the control directly instead of setting <see cref="DependsOn"/>
 /// </summary>
 /// <param name="dependsOnControl"></param>
 public void SetDependsOnControl(InputControlBase dependsOnControl)
 {
     _dependsOnControl = dependsOnControl;
 }
Example #20
0
        /// <summary>
        /// We only validate that to is less than from. There is no need to validate that from is greter than to.
        /// </summary>
        /// <param name="ctlInput"></param>
        /// <exception cref="NotImplementedException"></exception>
        /// <returns></returns>
        protected override bool OnServerValidate(InputControlBase ctlInput)
        {
            // We only expect to be associated with a text box
            TextBoxEx tb = (TextBoxEx)ctlInput;

            if (string.IsNullOrEmpty(tb.Text))
            {
                return(true);        // Empty values are valid
            }

            DateTime?value = tb.ValueAsDate;

            if (!value.HasValue)
            {
                ctlInput.ErrorMessage = string.Format(MSG1_VALID, ctlInput.FriendlyName);
                ctlInput.IsValid      = false;
                return(false);
            }

            switch (this.DateType)
            {
            case DateType.Default:
                break;

            case DateType.ToDate:
                // Get the previous TextBoxEx
                TextBoxEx tbFrom   = GetFromControl(ctlInput);
                DateTime? dateFrom = tbFrom.ValueAsDate;
                if (dateFrom.HasValue)
                {
                    if (value < dateFrom)
                    {
                        ctlInput.ErrorMessage = string.Format(MSG2_TO_GE_FROM, ctlInput.FriendlyName, tbFrom.FriendlyName);
                        ctlInput.IsValid      = false;
                        return(false);
                    }
                    if (this.MaxRange > 0 && (value.Value - dateFrom.Value).TotalDays > this.MaxRange)
                    {
                        ctlInput.IsValid = false;
                        return(false);
                    }
                }
                break;

            default:
                throw new NotImplementedException();
            }

            if (this.Min.HasValue)
            {
                DateTime minDate = DateTime.Today + TimeSpan.FromDays(this.Min.Value);
                if (value < minDate)
                {
                    ctlInput.ErrorMessage = string.Format(CultureInfo.CurrentUICulture, MSG2_MINDATE, ctlInput.FriendlyName, minDate);
                    ctlInput.IsValid      = false;
                    return(false);
                }
            }
            if (this.Max.HasValue)
            {
                DateTime maxDate = DateTime.Today + TimeSpan.FromDays(this.Max.Value);
                if (value > maxDate)
                {
                    ctlInput.ErrorMessage = string.Format(CultureInfo.CurrentUICulture, MSG2_MAX, ctlInput.FriendlyName, maxDate);
                    ctlInput.IsValid      = false;
                    return(false);
                }
            }
            return(true);
        }
Example #21
0
        /// <summary>
        /// Add client rules for main and max values. Also add a compare validator to the to date
        /// </summary>
        /// <param name="ctlInputControl"></param>
        /// <exception cref="NotImplementedException"></exception>
        internal override void RegisterClientRules(InputControlBase ctlInputControl)
        {
            string param;

            // date picker utility function provides robust date validation
            string script  = @"
if (this.optional(element)) return true;
var fmt = $(element).datepicker('option', 'dateFormat');
try {
    var dt = $.datepicker.parseDate(fmt, value);
    return true;
}
catch (err) {
    return false;
}
";
            string newRule = "$.validator.addMethod('checkdate', function(value, element, param) {"
                             + script + "});";

            JQueryScriptManager.Current.RegisterScriptBlock("checkdate_validator", newRule);
            string msg = string.Format(MSG1_VALID, ctlInputControl.FriendlyName);

            DoRegisterValidator(ctlInputControl, "checkdate", true, msg);

            if (this.Min.HasValue)
            {
                script  = @"
if (this.optional(element)) return true;
try {
    var fmt = $(element).datepicker('option', 'dateFormat');
    var dt = $.datepicker.parseDate(fmt, value);
    var minDate = $.datepicker.parseDate(fmt, param);
    return dt >= minDate;
}
catch (err) {
    // If any of the dates is not parseable, we deem ourselves to be valid
    return true;
}
";
                newRule = "$.validator.addMethod('mindate', function(value, element, param) {"
                          + script + "});";
                JQueryScriptManager.Current.RegisterScriptBlock("mindate_validator", newRule);
                DateTime minDate = DateTime.Today + TimeSpan.FromDays(this.Min.Value);
                param = string.Format(CultureInfo.CurrentUICulture, "{0:d}", minDate);
                msg   = string.Format(CultureInfo.CurrentUICulture, MSG2_MINDATE, ctlInputControl.FriendlyName, minDate);
                DoRegisterValidator(ctlInputControl, "mindate", param, msg);
            }

            if (this.Max.HasValue)
            {
                script  = @"
if (this.optional(element)) return true;
try {
    var fmt = $(element).datepicker('option', 'dateFormat');
    var dt = $.datepicker.parseDate(fmt, value);
    var maxDate = $.datepicker.parseDate(fmt, param);
    return dt <= maxDate;
}
catch (err) {
    return true;
}
";
                newRule = "$.validator.addMethod('maxdate', function(value, element, param) {"
                          + script + "});";
                JQueryScriptManager.Current.RegisterScriptBlock("maxdate_validator", newRule);
                DateTime maxdate = DateTime.Today + TimeSpan.FromDays(this.Max.Value);
                param = string.Format(CultureInfo.CurrentUICulture, "{0:d}", maxdate);
                msg   = string.Format(CultureInfo.CurrentUICulture, MSG2_MAX, ctlInputControl.FriendlyName, maxdate);
                DoRegisterValidator(ctlInputControl, "maxdate", param, msg);
            }
            switch (this.DateType)
            {
            case DateType.Default:
                break;

            case DateType.ToDate:
                // Ensure to date is more than from date
                script = @"
if (this.optional(element)) return true;
try {
    var fmt = $(element).datepicker('option', 'dateFormat');
    var val = $.datepicker.parseDate(fmt, value);
    var from = $.datepicker.parseDate(fmt, $(param).textBoxEx('getval'));
    if (from == '') return true;
    var fromDate = new Date(from);
    return val >= fromDate;
}
catch (err) {
    return true;
}
";
                // Creating a new rule which ensures to date is greater than from date
                newRule = "$.validator.addMethod('todate', function(value, element, param) {"
                          + script + "});";
                JQueryScriptManager.Current.RegisterScriptBlock("todate_validator", newRule);
                TextBoxEx tbFrom = GetFromControl(ctlInputControl);
                param = tbFrom.ClientSelector;
                msg   = string.Format(MSG2_TO_GE_FROM, ctlInputControl.FriendlyName, tbFrom.FriendlyName);
                DoRegisterValidator(ctlInputControl, "todate", param, msg);

                if (this.MaxRange > 0)
                {
                    // getDate can return a garbage date if any input control contains an invalid date.
                    // This is OK since the checkdate validator will fail first.
                    newRule = @"$.validator.addMethod('maxdaterange', function(value, element, param) {
var val = $(element).datepicker('getDate');
var fromDate = $(param[0]).datepicker('getDate');
return !val || !fromDate || (val.getTime() - fromDate.getTime()) <= (param[1] * 1000*60*60*24);
                        });";
                    JQueryScriptManager.Current.RegisterScriptBlock("maxdaterange_validator", newRule);
                    object[] ruleParams = new object[2];
                    ruleParams[0] = tbFrom.ClientSelector;
                    ruleParams[1] = string.Format("{0}", this.MaxRange);
                    msg           = string.Format("{0} must be within {1} days of {2}",
                                                  ctlInputControl.FriendlyName, this.MaxRange, tbFrom.FriendlyName);
                    DoRegisterValidator(ctlInputControl, "maxdaterange", ruleParams, msg);
                }
                break;

            default:
                throw new NotImplementedException();
            }
            //RegisterDatePicker(ctlInputControl);
        }
Example #22
0
 /// <summary>
 /// This function is called by InputControlBase to give us a chance to register our client scripts.
 /// Derived classes must register their validation rules. They can use the helper DoRegisterValidator()
 /// which will add the dependency, if any, to the validation rule
 /// </summary>
 /// <param name="ctlInputControl"></param>
 internal abstract void RegisterClientRules(InputControlBase ctlInputControl);
Example #23
0
 internal override void RegisterClientRules(InputControlBase ctlInputControl)
 {
     DoRegisterValidator(ctlInputControl, "required", true,
                         string.Format("{0} is required", ctlInputControl.FriendlyName));
 }