Inheritance: System.Web.UI.WebControls.Label, System.Web.UI.IValidator
Exemple #1
0
		public void StartValidationTest (BaseValidator validator)
		{
			Page = new Page();
			Validator = validator;
			Validator.Page = Page;
			Page.Controls.Add (Validator);
		}
Exemple #2
0
        public static void RenderValidatedControlEndTag(System.Web.UI.WebControls.BaseValidator validator,
                                                        bool required, bool designMode, string errorMessage, HtmlTextWriter writer)
        {
            if (writer == null)
            {
                return;
            }

            writer.RenderEndTag(); // Td2
            writer.RenderEndTag(); // Tr1

            if (required)
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Tr); // Tr2
                writer.RenderBeginTag(HtmlTextWriterTag.Td); // Td3
                writer.RenderEndTag();                       // Td3
                writer.AddStyleAttribute(HtmlTextWriterStyle.PaddingLeft, "2px");
                writer.RenderBeginTag(HtmlTextWriterTag.Td); // Td4

                if (validator != null)
                {
                    if (designMode)
                    {
                        validator.ErrorMessage = errorMessage;
                    }
                    validator.CssClass = "Error";
                    validator.RenderControl(writer);
                }

                writer.RenderEndTag(); // Td4
                writer.RenderEndTag(); // Tr2
            }

            writer.RenderEndTag(); // Table
        }
 /// <summary>
 /// Sets the error CssClass if an error is present.
 /// </summary>
 /// <param name="validator"></param>
 /// <param name="control"></param>
 /// <param name="className"></param>
 internal static void SetError(BaseValidator validator, WebControl control, string className)
 {
     if (validator.IsValid == false)
     {
         AddCssClass(control, className);
     }
 }
Exemple #4
0
        public virtual void SetIsRequired(string ControlName, string Value)
        {
            EnsureChildControls();
            //get the controls row and make it visisble
            BasePage p            = (BasePage)this.Page;
            Control  reqIndicator = p.FindControlRecursive(String.Format("{0}_Required_Indicator", ControlName));

            if (reqIndicator != null)
            {
                LiteralControl indicator = (LiteralControl)reqIndicator;
                indicator.Visible = Convert.ToBoolean(Value);
            }

            Control reqValidator = p.FindControlRecursive(String.Format("RequiredFieldValidator{0}", ControlName));

            if (reqValidator != null)
            {
                System.Web.UI.WebControls.BaseValidator val = (System.Web.UI.WebControls.BaseValidator)reqValidator;
                if (Convert.ToBoolean(Value))
                {
                    val.Enabled           = true;
                    val.ControlToValidate = ControlName;
                }
                else
                {
                    val.Enabled = false;
                }
            }
        }
        protected string GetControlValidationValue(string name)
        {
            Control control = NamingContainer.FindControl(name);

            if (control == null)
            {
                return(null);
            }

            PropertyDescriptor prop = BaseValidator.GetValidationProperty(control);

            if (prop == null)
            {
                return(null);
            }

            object o = prop.GetValue(control);

            if (o == null)
            {
                return(String.Empty);
            }

            if (o is ListItem)
            {
                return(((ListItem)o).Value);
            }

            return(o.ToString());
        }
 protected override void AddAttributesToRender(HtmlTextWriter writer)
 {
     if (this.renderUplevel)
     {
         base.EnsureID();
         string         clientID = this.ClientID;
         HtmlTextWriter writer2  = base.EnableLegacyRendering ? writer : null;
         if (this.HeaderText.Length > 0)
         {
             BaseValidator.AddExpandoAttribute(this, writer2, clientID, "headertext", this.HeaderText, true);
         }
         if (this.ShowMessageBox)
         {
             BaseValidator.AddExpandoAttribute(this, writer2, clientID, "showmessagebox", "True", false);
         }
         if (!this.ShowSummary)
         {
             BaseValidator.AddExpandoAttribute(this, writer2, clientID, "showsummary", "False", false);
         }
         if (this.DisplayMode != ValidationSummaryDisplayMode.BulletList)
         {
             BaseValidator.AddExpandoAttribute(this, writer2, clientID, "displaymode", PropertyConverter.EnumToString(typeof(ValidationSummaryDisplayMode), this.DisplayMode), false);
         }
         if (this.ValidationGroup.Length > 0)
         {
             BaseValidator.AddExpandoAttribute(this, writer2, clientID, "validationGroup", this.ValidationGroup, true);
         }
     }
     base.AddAttributesToRender(writer);
 }
        public static void OnLoad(BaseValidator validator)
        {
            ClientScriptManager cs = validator.Page.ClientScript;
            IEnhancedFormValidator enhancedFormControl = (IEnhancedFormValidator)validator;

            if(validator.EnableClientScript == true)
            {
                cs.RegisterClientScriptResource(typeof(IEnhancedFormValidator), "RDC.EnhancedForm.EnhancedClientValidation.js");

                Control control = validator.Parent.FindControl(validator.ControlToValidate);
                string controlToAffectID = "";

                if (control != null)
                {
                    if (enhancedFormControl.ControlLabel != null)
                    {
                        WebControl controlToAffect = (WebControl)validator.Parent.FindControl(enhancedFormControl.ControlLabel);

                        if (controlToAffect != null)
                        {
                            controlToAffectID = controlToAffect.ClientID;
                        }
                    }

                    if (!cs.IsClientScriptBlockRegistered(validator.GetType(), String.Format("HighlightValidation_{0}", validator.ClientID)))
                    {
                        /*
                         * Get the underlying original CSS settings for the controls so we can remember
                         * the original CSS state before we change to error CSS classes.
                         */

                        WebControl controlToValidate = (WebControl)validator.Parent.FindControl(validator.ControlToValidate);
                        WebControl controlLabel = (WebControl)validator.Parent.FindControl(enhancedFormControl.ControlLabel);

                        string controlToAffectIDCssClass = "";
                        string controlToAffectIDErrorCssClass = "";

                        if(controlLabel != null)
                        {
                            controlToAffectIDCssClass = controlLabel.CssClass;
                            controlToAffectIDErrorCssClass = enhancedFormControl.ControlLabelErrorCssClass;
                        }

                        cs.RegisterClientScriptBlock(validator.GetType(),
                                                     String.Format("pageEnhancedValidators{0}", validator.ClientID),
                                                     String.Format("pageEnhancedValidators.push(new Array('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}'));",
                                                                   validator.ClientID,
                                                                   control.ClientID,
                                                                   controlToValidate.CssClass,
                                                                   enhancedFormControl.ControlErrorCssClass,
                                                                   enhancedFormControl.ErrorClientCallbackFunction,
                                                                   controlToAffectID,
                                                                   controlToAffectIDCssClass,
                                                                   controlToAffectIDErrorCssClass),

                                                     true);
                    }
                }
            }
        }
Exemple #8
0
        /// <summary>
        ///   Adds html5/javascript validation by proxying calls to evaluationfunction
        ///   and calling setCustomValidity client-side.
        /// </summary>
        public static void AddHtml5Validation(BaseValidator control)
        {
            var clientId = control.ClientID;
            var scriptKey = control.GetType().Name + "-" + clientId;

            AddHtmlValidationScript(control.Page.ClientScript);
            control.Page.ClientScript.RegisterStartupScript(control.GetType(), scriptKey, "ValidatorUtil_AddHtml5Validation('" + clientId + "');", true);
        }
        protected void AddValidator(BaseValidator newValidator)
        {
            newValidator.Display = ValidatorDisplay.None;

            _validators.Add(newValidator);

            this.Controls.Add(newValidator);
        }
Exemple #10
0
        /// <summary>
        /// Registers the client-side ValidatorHookupControl method for the specified control and validator
        /// </summary>
        /// <param name="control">The control to validate. This control must have a client-side onchange event</param>
        /// <param name="validator">The validator control.</param>
        public void ValidatorHookupControl(Control control, BaseValidator validator)
        {
            if (m_startupScript == null)
            {
                m_startupScript = new StringBuilder();
            }

            m_startupScript.AppendFormat("ValidatorHookupControl(document.getElementById('{0}'), document.getElementById('{1}'));\n", control.ClientID, validator.ClientID);
        }
        /*
         * If java script is not enabbled, change CSS classes on post back.
         */
        public static void OnPreRender(BaseValidator validator)
        {
            IEnhancedFormValidator enhancedFormControl = (IEnhancedFormValidator)validator;

            StateBag pageViewState = enhancedFormControl.PageViewState;
            WebControl control = (WebControl)validator.Parent.FindControl(validator.ControlToValidate);

            if (control != null)
            {
                if (!validator.IsValid)
                {
                    control.ToolTip = validator.ToolTip;

                    if (pageViewState[control.ID + "CssClass"] == null)
                    {
                        pageViewState[control.ID + "CssClass"] = control.CssClass;
                        control.CssClass = enhancedFormControl.ControlErrorCssClass;
                    }
                }
                else
                {
                    if(pageViewState[control.ID + "CssClass"] != null)
                    {
                        control.CssClass = pageViewState[control.ID + "CssClass"].ToString();
                        pageViewState[control.ID + "CssClass"] = null;
                    }
                }
            }

            if (enhancedFormControl.ControlLabel != null && enhancedFormControl.ControlLabelErrorCssClass != null)
            {
                WebControl controltoAffect = (WebControl)validator.Parent.FindControl(enhancedFormControl.ControlLabel);

                if (controltoAffect != null)
                {
                    if (!validator.IsValid)
                    {
                        control.ToolTip = validator.ToolTip;

                        if (pageViewState[controltoAffect.ID + "CssClass"] == null)
                        {
                            pageViewState[controltoAffect.ID + "CssClass"] = controltoAffect.CssClass;
                            controltoAffect.CssClass = enhancedFormControl.ControlLabelErrorCssClass;
                        }
                    }
                    else
                    {
                        if (pageViewState[controltoAffect.ID + "CssClass"] != null)
                        {
                            controltoAffect.CssClass = pageViewState[controltoAffect.ID + "CssClass"].ToString();
                            pageViewState[controltoAffect.ID + "CssClass"] = null;
                        }
                    }
                }
            }
        }
 public ValidatorCalloutExtender GetCalloutExtender(BaseValidator validator, string controlId)
 {
     return new ValidatorCalloutExtender
     {
         ID = controlId,
         TargetControlID = validator.ID,
         HighlightCssClass = _settings.CssClass_CalloutHighlight,
         WarningIconImageUrl = _settings.ImgPath_CalloutWarning
     };
 }
Exemple #13
0
        //public static void DoBaseCompareValidatorAddAttributes(WhidbeyBaseCompareValidator validator, IBaseCompareValidatorAccessor validatorAccessor) {
        //    if (validatorAccessor.RenderUpLevel) {
        //        ValidationDataType type = validator.Type;
        //        if (type != ValidationDataType.String) {
        //            string id = validator.ClientID;

        //            ValidatorHelper.AddExpandoAttribute(validator, id, "type", PropertyConverter.EnumToString(typeof(ValidationDataType), type), false);

        //            NumberFormatInfo info = NumberFormatInfo.CurrentInfo;
        //            if (type == ValidationDataType.Double) {
        //                string decimalChar = info.NumberDecimalSeparator;
        //                ValidatorHelper.AddExpandoAttribute(validator, id, "decimalchar", decimalChar);
        //            }
        //            else if (type == ValidationDataType.Currency) {
        //                string decimalChar = info.CurrencyDecimalSeparator;
        //                ValidatorHelper.AddExpandoAttribute(validator, id, "decimalchar", decimalChar);

        //                string groupChar = info.CurrencyGroupSeparator;
        //                if (groupChar[0] == 160)
        //                    groupChar = " ";
        //                ValidatorHelper.AddExpandoAttribute(validator, id, "groupchar", groupChar);

        //                int digits = info.CurrencyDecimalDigits;
        //                ValidatorHelper.AddExpandoAttribute(validator, id, "digits", digits.ToString(NumberFormatInfo.InvariantInfo), false);

        //                int groupSize = GetCurrencyGroupSize(info);
        //                if (groupSize > 0) {
        //                    ValidatorHelper.AddExpandoAttribute(validator, id, "groupsize", groupSize.ToString(NumberFormatInfo.InvariantInfo), false);
        //                }
        //            }
        //            else if (type == ValidationDataType.Date) {
        //                ValidatorHelper.AddExpandoAttribute(validator, id, "dateorder", validatorAccessor.GetDateElementOrder(), false);
        //                ValidatorHelper.AddExpandoAttribute(validator, id, "cutoffyear", validatorAccessor.CutoffYear.ToString(NumberFormatInfo.InvariantInfo), false);

        //                int currentYear = DateTime.Today.Year;
        //                int century = currentYear - (currentYear % 100);
        //                ValidatorHelper.AddExpandoAttribute(validator, id, "century", century.ToString(NumberFormatInfo.InvariantInfo), false);
        //            }
        //        }
        //    }
        //}

        public static void DoBaseValidatorAddAttributes(WhidbeyBaseValidator validator, IBaseValidatorAccessor validatorAccessor, HtmlTextWriter writer)
        {
            bool disabled = !validator.Enabled;

            if (disabled)
            {
                validator.Enabled = true;
            }

            try {
                if (validatorAccessor.RenderUpLevel)
                {
                    validatorAccessor.EnsureID();
                    string id = validator.ClientID;

                    if (validator.ControlToValidate.Length > 0)
                    {
                        AddExpandoAttribute(validator, id, "controltovalidate", validatorAccessor.GetControlRenderID(validator.ControlToValidate));
                    }
                    if (validator.SetFocusOnError)
                    {
                        AddExpandoAttribute(validator, id, "focusOnError", "t", false);
                    }
                    if (validator.ErrorMessage.Length > 0)
                    {
                        AddExpandoAttribute(validator, id, "errormessage", validator.ErrorMessage);
                    }
                    ValidatorDisplay display = validator.Display;
                    if (display != ValidatorDisplay.Static)
                    {
                        AddExpandoAttribute(validator, id, "display", PropertyConverter.EnumToString(typeof(ValidatorDisplay), display), false);
                    }
                    if (!validator.IsValid)
                    {
                        AddExpandoAttribute(validator, id, "isvalid", "False", false);
                    }
                    if (disabled)
                    {
                        AddExpandoAttribute(validator, id, "enabled", "False", false);
                    }
                    if (validator.ValidationGroup.Length > 0)
                    {
                        AddExpandoAttribute(validator, id, "validationGroup", validator.ValidationGroup);
                    }
                }

                DoWebControlAddAttributes(validator, validatorAccessor, writer);
            }
            finally {
                if (disabled)
                {
                    validator.Enabled = false;
                }
            }
        }
Exemple #14
0
 public static void DoPreRenderRegistration(WhidbeyBaseValidator validator, IBaseValidatorAccessor validatorAccessor)
 {
     if (validatorAccessor.RenderUpLevel)
     {
         ScriptManager.RegisterClientScriptResource(validator, typeof(WhidbeyBaseValidator), ValidatorFileName);
         ScriptManager.RegisterStartupScript(validator, typeof(WhidbeyBaseValidator), ValidatorIncludeScriptKey, ValidatorStartupScript, true);
         ScriptManager.RegisterOnSubmitStatement(validator,
                                                 typeof(WhidbeyBaseValidator),
                                                 "ValidatorOnSubmit",
                                                 "if (typeof(ValidatorOnSubmit) == \"function\" && ValidatorOnSubmit() == false) return false;");
     }
 }
        /// <include file='doc\BaseValidator.uex' path='docs/doc[@for="BaseValidator.BaseValidator"]/*' />
        protected BaseValidator()
        {
            _webBaseValidator = CreateWebValidator();
            if (_webBaseValidator == null)
            {
                // Create a default web base validator, mainly for storing
                // property values.
                _webBaseValidator = new DefaultWebValidator();
            }

            Controls.Add(_webBaseValidator);

            // Currently by default we render error message in a dynamic way.
            _webBaseValidator.Display = ValidatorDisplay.Dynamic;
        }
Exemple #16
0
        /// <include file='doc\BaseValidator.uex' path='docs/doc[@for="BaseValidator.BaseValidator"]/*' />
        protected BaseValidator()
        {
            _webBaseValidator = CreateWebValidator();
            if (_webBaseValidator == null)
            {
                // Create a default web base validator, mainly for storing
                // property values.
                _webBaseValidator = new DefaultWebValidator();
            }

            Controls.Add(_webBaseValidator);

            // Currently by default we render error message in a dynamic way.
            _webBaseValidator.Display = ValidatorDisplay.Dynamic;
        }
Exemple #17
0
        public static void DoValidatorArrayDeclaration(WhidbeyBaseValidator validator, Type validatorType)
        {
            string element = "document.getElementById(\"" + validator.ClientID + "\")";

            ScriptManager.RegisterArrayDeclaration(validator, "Page_Validators", element);

            ScriptManager.RegisterStartupScript(validator, validatorType, validator.ClientID + "_DisposeScript",
                                                String.Format(
                                                    CultureInfo.InvariantCulture,
                                                    @"
document.getElementById('{0}').dispose = function() {{
    Array.remove(Page_Validators, document.getElementById('{0}'));
}}
",
                                                    validator.ClientID), true);
        }
Exemple #18
0
        protected void CheckControlValidationProperty(string name, string propertyName)
        {
            Control            control = NamingContainer.FindControl(name);
            PropertyDescriptor prop    = null;

            if (control == null)
            {
                throw new HttpException(String.Format("Unable to find control id '{0}'.", name));
            }

            prop = BaseValidator.GetValidationProperty(control);
            if (prop == null)
            {
                throw new HttpException(String.Format("Unable to find ValidationProperty attribute '{0}' on control '{1}'", propertyName, name));
            }
        }
Exemple #19
0
        /// <summary>
        ///   Retrieves the target control and sets required="required" attribute.
        /// </summary>
        public static void SetTargetControlRequired(BaseValidator control)
        {
            WithTargetControl(control, controlToValidate => {
                AttributeCollection attributes = null;

                if (controlToValidate is CheckBox) {
                    attributes = ((CheckBox)controlToValidate).InputAttributes;
                } else if (controlToValidate is WebControl) {
                    attributes = ((WebControl)controlToValidate).Attributes;
                }

                if (attributes != null) {
                    attributes["required"] = "required";
                }
            });
        }
        //public static void DoBaseCompareValidatorAddAttributes(WhidbeyBaseCompareValidator validator, IBaseCompareValidatorAccessor validatorAccessor) {
        //    if (validatorAccessor.RenderUpLevel) {
        //        ValidationDataType type = validator.Type;
        //        if (type != ValidationDataType.String) {
        //            string id = validator.ClientID;

        //            ValidatorHelper.AddExpandoAttribute(validator, id, "type", PropertyConverter.EnumToString(typeof(ValidationDataType), type), false);

        //            NumberFormatInfo info = NumberFormatInfo.CurrentInfo;
        //            if (type == ValidationDataType.Double) {
        //                string decimalChar = info.NumberDecimalSeparator;
        //                ValidatorHelper.AddExpandoAttribute(validator, id, "decimalchar", decimalChar);
        //            }
        //            else if (type == ValidationDataType.Currency) {
        //                string decimalChar = info.CurrencyDecimalSeparator;
        //                ValidatorHelper.AddExpandoAttribute(validator, id, "decimalchar", decimalChar);

        //                string groupChar = info.CurrencyGroupSeparator;
        //                if (groupChar[0] == 160)
        //                    groupChar = " ";
        //                ValidatorHelper.AddExpandoAttribute(validator, id, "groupchar", groupChar);

        //                int digits = info.CurrencyDecimalDigits;
        //                ValidatorHelper.AddExpandoAttribute(validator, id, "digits", digits.ToString(NumberFormatInfo.InvariantInfo), false);

        //                int groupSize = GetCurrencyGroupSize(info);
        //                if (groupSize > 0) {
        //                    ValidatorHelper.AddExpandoAttribute(validator, id, "groupsize", groupSize.ToString(NumberFormatInfo.InvariantInfo), false);
        //                }
        //            }
        //            else if (type == ValidationDataType.Date) {
        //                ValidatorHelper.AddExpandoAttribute(validator, id, "dateorder", validatorAccessor.GetDateElementOrder(), false);
        //                ValidatorHelper.AddExpandoAttribute(validator, id, "cutoffyear", validatorAccessor.CutoffYear.ToString(NumberFormatInfo.InvariantInfo), false);

        //                int currentYear = DateTime.Today.Year;
        //                int century = currentYear - (currentYear % 100);
        //                ValidatorHelper.AddExpandoAttribute(validator, id, "century", century.ToString(NumberFormatInfo.InvariantInfo), false);
        //            }
        //        }
        //    }
        //}

        public static void DoBaseValidatorAddAttributes(WhidbeyBaseValidator validator, IBaseValidatorAccessor validatorAccessor, HtmlTextWriter writer) {
            bool disabled = !validator.Enabled;
            if (disabled) {
                validator.Enabled = true;
            }

            try {
                if (validatorAccessor.RenderUpLevel) {
                    validatorAccessor.EnsureID();
                    string id = validator.ClientID;

                    if (validator.ControlToValidate.Length > 0) {
                        AddExpandoAttribute(validator, id, "controltovalidate", validatorAccessor.GetControlRenderID(validator.ControlToValidate));
                    }
                    if (validator.SetFocusOnError) {
                        AddExpandoAttribute(validator, id, "focusOnError", "t", false);
                    }
                    if (validator.ErrorMessage.Length > 0) {
                        AddExpandoAttribute(validator, id, "errormessage", validator.ErrorMessage);
                    }
                    ValidatorDisplay display = validator.Display;
                    if (display != ValidatorDisplay.Static) {
                        AddExpandoAttribute(validator, id, "display", PropertyConverter.EnumToString(typeof(ValidatorDisplay), display), false);
                    }
                    if (!validator.IsValid) {
                        AddExpandoAttribute(validator, id, "isvalid", "False", false);
                    }
                    if (disabled) {
                        AddExpandoAttribute(validator, id, "enabled", "False", false);
                    }
                    if (validator.ValidationGroup.Length > 0) {
                        AddExpandoAttribute(validator, id, "validationGroup", validator.ValidationGroup);
                    }
                }

                DoWebControlAddAttributes(validator, validatorAccessor, writer);
            }
            finally {
                if (disabled) {
                    validator.Enabled = false;
                }
            }

        }
        /// <internalonly/>
        /// <devdoc>
        ///    AddAttributesToRender method.
        /// </devdoc>
        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            if (renderUplevel)
            {
                // We always want validation cotnrols to have an id on the client
                EnsureID();
                string id = ClientID;

                // DevDiv 33149: A backward compat. switch for Everett rendering
                HtmlTextWriter expandoAttributeWriter = (EnableLegacyRendering || IsUnobtrusive) ? writer : null;

                if (IsUnobtrusive)
                {
                    Attributes["data-valsummary"] = "true";
                }

                if (HeaderText.Length > 0)
                {
                    BaseValidator.AddExpandoAttribute(this, expandoAttributeWriter, id, "headertext", HeaderText, true);
                }
                if (ShowMessageBox)
                {
                    BaseValidator.AddExpandoAttribute(this, expandoAttributeWriter, id, "showmessagebox", "True", false);
                }
                if (!ShowSummary)
                {
                    BaseValidator.AddExpandoAttribute(this, expandoAttributeWriter, id, "showsummary", "False", false);
                }
                if (DisplayMode != ValidationSummaryDisplayMode.BulletList)
                {
                    BaseValidator.AddExpandoAttribute(this, expandoAttributeWriter, id, "displaymode", PropertyConverter.EnumToString(typeof(ValidationSummaryDisplayMode), DisplayMode), false);
                }
                if (ValidationGroup.Length > 0)
                {
                    BaseValidator.AddExpandoAttribute(this, expandoAttributeWriter, id, "validationGroup", ValidationGroup, true);
                }
            }

            base.AddAttributesToRender(writer);
        }
        /// <summary>
        /// Register field validator.
        /// </summary>
        /// <param name="validator">Validator.</param>
        /// <returns>True if scheduled for registration on PreRender event.</returns>
        public bool RegisterFieldValidator(BaseValidator validator)
        {
            var control = FindControlRecursive(validator.Parent, validator.ControlToValidate);
            if (control == null) return false;

            return RegisterFieldValidator(validator.ClientID, control.ClientID, validator is RequiredFieldValidator);
        }
Exemple #23
0
        private System.Web.UI.WebControls.BaseValidator GetValidator(Widget control, Core.BaseValidator validator)
        {
            System.Web.UI.WebControls.BaseValidator retVal = null;
            //string validationErrorMessage = null;
            //string validationResourceKeyPrefix = String.Format("", this.ResourceKeyPrefix, validator.Name)
            //validationErrorMessage = GetGlobalResourceString("", compareConfig.ErrorMessage);

            switch (validator.GetType().Name.ToLower())
            {
            case "comparevalidator":
                Core.CompareValidator compareConfig = (Core.CompareValidator)validator;
                System.Web.UI.WebControls.CompareValidator compareActual = new System.Web.UI.WebControls.CompareValidator();

                compareActual.ID      = compareConfig.Name;
                compareActual.Display = ValidatorDisplay.None;


                compareActual.ErrorMessage      = compareConfig.ErrorMessage;
                compareActual.Text              = "*";
                compareActual.ControlToValidate = control.Name;

                //validator specific
                compareActual.Type             = compareConfig.Type;
                compareActual.ControlToCompare = compareConfig.ControlToCompare;
                compareActual.Operator         = compareConfig.Operator;
                compareActual.ValueToCompare   = compareConfig.ValueToCompare;

                retVal = (System.Web.UI.WebControls.BaseValidator)compareActual;

                break;

            case "datacommandvalidator":
                Core.DataCommandValidator  dataConfig = (Core.DataCommandValidator)validator;
                CustomDataCommandValidator dataActual = new CustomDataCommandValidator();

                dataActual.ID      = dataConfig.Name;
                dataActual.Display = ValidatorDisplay.None;

                dataActual.ErrorMessage      = dataConfig.ErrorMessage;
                dataActual.Text              = "*";
                dataActual.ControlToValidate = control.Name;

                //validator specific
                dataActual.DataCommand          = dataConfig.DataCommand;
                dataActual.ValidationField      = dataConfig.ValidationField;
                dataActual.UseValueParameter    = dataConfig.UseValueParameter;
                dataActual.ValueParameter       = dataConfig.ValueParameter;
                dataActual.UseErrorMessageField = dataConfig.UseErrorMessageField;
                dataActual.ErrorMessageField    = dataConfig.ErrorMessageField;

                dataActual.ServerValidate += new ServerValidateEventHandler(DataCommandValidator_ServerValidate);

                retVal = (System.Web.UI.WebControls.BaseValidator)dataActual;
                break;

            case "regularexpressionvalidator":
                Core.RegularExpressionValidator regexpConfig = (Core.RegularExpressionValidator)validator;
                System.Web.UI.WebControls.RegularExpressionValidator regexpActual = new System.Web.UI.WebControls.RegularExpressionValidator();

                regexpActual.ID      = regexpConfig.Name;
                regexpActual.Display = ValidatorDisplay.None;

                regexpActual.ErrorMessage      = regexpConfig.ErrorMessage;
                regexpActual.Text              = "*";
                regexpActual.ControlToValidate = control.Name;

                //validator specific
                regexpActual.ValidationExpression = regexpConfig.ValidationExpression;

                retVal = (System.Web.UI.WebControls.BaseValidator)regexpActual;
                break;

            case "rangevalidator":
                Core.RangeValidator rangeConfig = (Core.RangeValidator)validator;
                System.Web.UI.WebControls.RangeValidator rangeActual = new System.Web.UI.WebControls.RangeValidator();

                rangeActual.ID      = rangeConfig.Name;
                rangeActual.Display = ValidatorDisplay.None;

                rangeActual.ErrorMessage      = rangeConfig.ErrorMessage;
                rangeActual.Text              = "*";
                rangeActual.ControlToValidate = control.Name;

                //validator specific
                rangeActual.Type         = rangeConfig.Type;
                rangeActual.MinimumValue = rangeConfig.MinimumValue;
                rangeActual.MaximumValue = rangeConfig.MaximumValue;

                retVal = (System.Web.UI.WebControls.BaseValidator)rangeActual;
                break;
            }

            return(retVal);
        }
Exemple #24
0
        public void AddControl(Screen Screen, Section Section, Control parent, Widget control)
        {
            try
            {
                bool              IsControlVisible  = true;
                bool              IsControlEditable = true;
                ControlType       controlType       = null;
                ControlType       labelControlType  = null;
                BaseFieldTemplate ctrl         = null;
                BaseFieldTemplate readOnlyCtrl = null;
                System.Web.UI.WebControls.BaseValidator val = null;


                HtmlGenericControl group = null;

                HtmlGenericControl labelContainer     = null;
                System.Web.UI.WebControls.Label label = null;

                HtmlGenericControl controlContainer = null;
                PlaceHolder        groupContainer   = null;

                Control help = null;

                IsControlVisible  = DetermineControlVisibility(control, IsControlVisible);
                IsControlEditable = DetermineIfControlIsEditable(control, IsControlVisible, IsControlEditable);

                //setup overall container
                groupContainer         = new PlaceHolder();
                groupContainer.ID      = String.Format("{0}_GroupContainer", control.Name);
                groupContainer.Visible = IsControlVisible;

                //setup control group if needed
                if (!String.IsNullOrEmpty(control.ControlGroupElement))
                {
                    group    = new HtmlGenericControl(control.ControlGroupElement);
                    group.ID = String.Format("{0}_FormGroup", control.Name);

                    if (!String.IsNullOrEmpty(control.ControlGroupCssClass))
                    {
                        group.Attributes.Add("class", control.ControlGroupCssClass);
                    }
                }

                //setup label container if needed
                if (!String.IsNullOrEmpty(control.LabelContainerElement))
                {
                    labelContainer    = new HtmlGenericControl(control.LabelContainerElement);
                    labelContainer.ID = String.Format("{0}_LabelContainer", control.Name);

                    if (!String.IsNullOrEmpty(control.LabelContainerCssClass))
                    {
                        labelContainer.Attributes.Add("class", control.LabelContainerCssClass);
                    }
                }

                //setup control container if needed
                if (!String.IsNullOrEmpty(control.ControlContainerElement))
                {
                    controlContainer    = new HtmlGenericControl(control.ControlContainerElement);
                    controlContainer.ID = String.Format("{0}_ControlContainer", control.Name);

                    if (!String.IsNullOrEmpty(control.ControlContainerCssClass))
                    {
                        controlContainer.Attributes.Add("class", control.ControlContainerCssClass);
                    }
                }

                //setup actual control
                controlType = ControlType.GetControlType(control);
                if (controlType == null)
                {
                    throw new ApplicationException(String.Format("Control of type {0} could not be found in configuration", control.Type));
                }

                if (!IsControlEditable)
                {
                    labelControlType = ControlType.GetControlType("Label");
                }

                if (controlType != null)
                {
                    //main edit control
                    ctrl    = LoadBaseFieldTemplateFromControlType(controlType);
                    ctrl.ID = control.Name;
                    ctrl.ResourceKeyPrefix = String.Format("Screen.Sections.{0}.Control", Section.Name);
                    BaseFieldTemplate renderControl = null;

                    //alternate edit control in read only mode
                    if (!IsControlEditable)
                    {
                        readOnlyCtrl    = LoadBaseFieldTemplateFromControlType(labelControlType);
                        readOnlyCtrl.ID = String.Format("{0}_ReadOnly_Label", control.Name);
                    }

                    if (IsControlEditable)
                    {
                        renderControl = ctrl;
                    }
                    else
                    {
                        renderControl = readOnlyCtrl;
                    }

                    //label
                    label    = new System.Web.UI.WebControls.Label();
                    label.ID = String.Format("{0}_Label", control.Name);
                    if (!String.IsNullOrEmpty(control.LabelCssClass))
                    {
                        string labelCss = String.Format("{0}", control.LabelCssClass);

                        if (control.IsRequired)
                        {
                            labelCss += " required required-label";
                        }

                        label.CssClass = labelCss;
                    }
                    if (!String.IsNullOrEmpty(control.Label))
                    {
                        string labelText = GetGlobalResourceString(String.Format("Control.{0}.Label", control.Name), control.Label);
                        labelText += ":";

                        label.Controls.Add(new LiteralControl(labelText));
                    }

                    //help text
                    if (!String.IsNullOrEmpty(control.HelpText))
                    {
                        string helpText = GetGlobalResourceString(String.Format("Control.{0}.HelpText", control.Name), control.HelpText);

                        if (String.IsNullOrEmpty(control.HelpTextElement))
                        {
                            help = new LiteralControl(control.HelpText);
                        }
                        else
                        {
                            HtmlGenericControl helpControl = new HtmlGenericControl(control.HelpTextElement);
                            helpControl.InnerHtml = control.HelpText;

                            if (!String.IsNullOrEmpty(control.HelpTextCssClass))
                            {
                                helpControl.Attributes.Add("class", control.HelpTextCssClass);
                            }

                            help = helpControl;
                        }
                    }


                    //validation controls
                    List <System.Web.UI.WebControls.BaseValidator> validators = new List <System.Web.UI.WebControls.BaseValidator>();
                    if (IsControlEditable)
                    {
                        //custom validators
                        foreach (CodeTorch.Core.BaseValidator validator in control.Validators)
                        {
                            System.Web.UI.WebControls.BaseValidator validatorControl = GetValidator(control, validator);
                            validators.Add(validatorControl);
                        }
                    }

                    //assign base control, section and screen references
                    ctrl.Widget = control;
                    if (!IsControlEditable)
                    {
                        readOnlyCtrl.Widget = CreateLabelControlFromWidget(control);
                        readOnlyCtrl.Value  = ctrl.Value;
                        readOnlyCtrl.SetDisplayText(ctrl.DisplayText);
                    }
                    ctrl.Section = Section;
                    ctrl.Screen  = Screen;

                    //now that all controls have been defined we now need to render table html based on rendering mode
                    if (group != null)
                    {
                        if (control.LabelWrapsControl)
                        {
                            AssignControl(group, labelContainer, label);
                            AssignControl(label, controlContainer, renderControl, help);
                        }
                        else
                        {
                            label.AssociatedControlID = renderControl.ClientID;

                            if (control.LabelRendersBeforeControl)
                            {
                                AssignControl(group, labelContainer, label);
                                AssignControl(group, controlContainer, renderControl, help);
                            }
                            else
                            {
                                AssignControl(group, controlContainer, renderControl, help);
                                AssignControl(group, labelContainer, label);
                            }
                        }
                    }
                    else
                    {
                        Control g = groupContainer;// (parent != null) ? (Control)parent : (Control)this.ContentPlaceHolder;

                        if (control.LabelWrapsControl)
                        {
                            AssignControl(g, labelContainer, label);
                            AssignControl(label, controlContainer, renderControl, help);
                        }
                        else
                        {
                            label.AssociatedControlID = renderControl.ClientID;

                            if (control.LabelRendersBeforeControl)
                            {
                                AssignControl(g, labelContainer, label);
                                AssignControl(g, controlContainer, renderControl, help);
                            }
                            else
                            {
                                AssignControl(g, controlContainer, renderControl, help);
                                AssignControl(g, labelContainer, label);
                            }
                        }
                    }


                    if (parent != null)
                    {
                        if (group != null)
                        {
                            groupContainer.Controls.Add(group);
                        }
                        parent.Controls.Add(groupContainer);
                    }
                    else
                    {
                        if (group != null)
                        {
                            groupContainer.Controls.Add(group);
                        }
                        this.ContentPlaceHolder.Controls.Add(groupContainer);
                    }


                    string requiredErrorMessage = String.Format("{0} is required.", control.Label);
                    string requiredErrorMessageResourceValue = GetGlobalResourceString(String.Format("Control.{0}.IsRequired.ErrorMessage", control.Name), requiredErrorMessage);

                    //get container for validation
                    Control valContainer = ((Control)controlContainer ??
                                            (
                                                (Control)group ??
                                                (
                                                    ((Control)parent ?? (Control)this.ContentPlaceHolder)
                                                )
                                            )
                                            );



                    if (!String.IsNullOrEmpty(control.Name))
                    {
                        if (ctrl.SupportsValidation())
                        {
                            val = ctrl.GetRequiredValidator(control, IsControlEditable, requiredErrorMessageResourceValue);
                            valContainer.Controls.Add(val);

                            if (IsControlEditable)
                            {
                                //custom validators
                                foreach (System.Web.UI.WebControls.BaseValidator validator in validators)
                                {
                                    valContainer.Controls.Add(validator);
                                }
                            }
                        }
                    }
                }
                else
                {
                    string ErrorMessageFormat = "<span style='color:red'>ERROR - Could not load control {0} - {1} - control type returned null object</span>";
                    string ErrorMessages      = String.Format(ErrorMessageFormat, control.Name, control.Type);


                    this.ContentPlaceHolder.Controls.Add(new LiteralControl(ErrorMessages));
                }
            }
            catch (Exception ex)
            {
                this.ContentPlaceHolder.Controls.Add(new LiteralControl(ex.Message));
            }
        }
 bool FilterControl(Control control)
 {
     return(BaseValidator.GetValidationProperty(control) != null);
 }
Exemple #26
0
        protected void SetErrorMessage(BaseValidator validator, Integrity.NameOccupiedException ex)
        {
            Trace.Write(ex.ToString());

            string message = string.Format("An item named '{0}' already exists below '{1}'",
                ex.SourceItem.Name,
                ex.DestinationItem.Name);
            SetErrorMessage(validator, message);
        }
Exemple #27
0
        protected void SetErrorMessage(BaseValidator validator, Integrity.DestinationOnOrBelowItselfException ex)
        {
            Trace.Write(ex.ToString());

            string message = string.Format("Cannot move an item to a destination onto or below itself",
                ex.SourceItem.Name,
                ex.DestinationItem.Name);
            SetErrorMessage(validator, message);
        }
        protected virtual void SetUpValidator(BaseValidator validator, MetaColumn column) {

            // Set the validation group to match the dynamic control
            validator.ValidationGroup = Host.ValidationGroup;

            if (validator is DynamicValidator) {
                SetUpDynamicValidator((DynamicValidator)validator, column);
            }
            else if (validator is RequiredFieldValidator) {
                SetUpRequiredFieldValidator((RequiredFieldValidator)validator, column);
            }
            else if (validator is CompareValidator) {
                SetUpCompareValidator((CompareValidator)validator, column);
            }
            else if (validator is RangeValidator) {
                SetUpRangeValidator((RangeValidator)validator, column);
            }
            else if (validator is RegularExpressionValidator) {
                SetUpRegexValidator((RegularExpressionValidator)validator, column);
            }

            validator.ToolTip = validator.ErrorMessage;
            validator.Text = "*";
        }
 protected virtual void SetUpValidator(BaseValidator validator) {
     SetUpValidator(validator, Column);
 }
Exemple #30
0
 protected static void SetErrorMessage(BaseValidator validator, string message)
 {
     validator.IsValid = false;
     validator.ErrorMessage = message;
 }
Exemple #31
0
 /// <summary>
 ///   Retrieves the target control (from <see cref="BaseValidator.ControlToValidate" />)
 ///   and executes the provided action with the control as parameter.
 /// </summary>
 internal static void WithTargetControl(BaseValidator validator, Action<Control> action)
 {
     var targetControl = validator.NamingContainer.FindControl(validator.ControlToValidate);
     if (targetControl != null)
         action(targetControl);
 }
Exemple #32
0
		public void StopValidationTest ()
		{
			Page = null;
			Validator = null;
		}
 /// <summary>
 /// Register field validator.
 /// </summary>
 /// <param name="validator">Validator.</param>
 /// <param name="controlToValidateClientID">Control to validate client id.</param>
 /// <returns>True if scheduled for registration on PreRender event.</returns>
 public bool RegisterFieldValidator(BaseValidator validator, string controlToValidateClientID)
 {
     return RegisterFieldValidator(validator.ClientID, controlToValidateClientID, validator is RequiredFieldValidator);
 }
 public static void DoPreRenderRegistration(WhidbeyBaseValidator validator, IBaseValidatorAccessor validatorAccessor)
 {
     if(validatorAccessor.RenderUpLevel) {
         ScriptManager.RegisterClientScriptResource(validator, typeof(WhidbeyBaseValidator), ValidatorFileName);
         ScriptManager.RegisterStartupScript(validator, typeof(WhidbeyBaseValidator), ValidatorIncludeScriptKey, ValidatorStartupScript, true);
         ScriptManager.RegisterOnSubmitStatement(validator,
             typeof(WhidbeyBaseValidator),
             "ValidatorOnSubmit",
             "if (typeof(ValidatorOnSubmit) == \"function\" && ValidatorOnSubmit() == false) return false;");
     }
 }
 public bool IsRuleValid(BaseValidator placeHolderValidator, RadioButton userRadio, TextBox userName, RadioButton roleRadio, DropDownList roles)
 {
     if (userRadio.Checked && userName.Text.Trim().Length == 0) {
         placeHolderValidator.ErrorMessage = ((string)GetGlobalResourceObject("GlobalResources", "NonemptyUser"));
         placeHolderValidator.IsValid = false;
         return false;
     }
     if (roleRadio.Checked && roles.SelectedItem == null) {
         placeHolderValidator.ErrorMessage = ((string)GetGlobalResourceObject("GlobalResources", "NonemptyRole"));
         placeHolderValidator.IsValid = false;
         return false;
     }
     if (userRadio.Checked) {
         string userNameString = userName.Text.Trim();
         if (-1 != userNameString.IndexOf('*')) {
             placeHolderValidator.ErrorMessage = ((string)GetGlobalResourceObject("GlobalResources", "InvalidRuleName"));
             placeHolderValidator.IsValid = false;
             return false;
         }
     }
     return true;
 }
 public void SetSharedValues(BaseValidator validator, ValidationItem item)
 {
     validator.ControlToValidate = item.Control.ID;
     validator.ValidationGroup = _groupIdentifier;
     validator.EnableClientScript = true;
     validator.Display = ValidatorDisplay.None;
     validator.ErrorMessage = item.GetErrorMessage();
 }
		protected virtual void SetUpValidator (BaseValidator validator)
		{
		}
Exemple #38
0
        protected void SetErrorMessage(BaseValidator validator, ContentTypes.NotAllowedParentException ex)
        {
            //Trace.Write(ex.ToString());

            string message = string.Format("The item of type '{0}' isn't allowed below a destination of type '{1}'",
                ex.ContentType.Title,
                Engine.ContentTypes.GetContentType(ex.ParentType).Title);
            SetErrorMessage(validator, message);
        }
        public static void DoValidatorArrayDeclaration(WhidbeyBaseValidator validator, Type validatorType)
        {
            var element = "document.getElementById(\"" + validator.ClientID + "\")";
            ScriptManager.RegisterArrayDeclaration(validator, "Page_Validators", element);

            ScriptManager.RegisterStartupScript(validator, validatorType, validator.ClientID + "_DisposeScript",
                String.Format(
                    CultureInfo.InvariantCulture,
                    @"
            document.getElementById('{0}').dispose = function() {{
            Array.remove(Page_Validators, document.getElementById('{0}'));
            }}
            ",
                    validator.ClientID), true);
        }
		protected virtual void SetUpValidator (BaseValidator validator, MetaColumn column)
		{
			throw new NotImplementedException ();
		}
        private void RenderRow(HtmlTextWriter writer, string label, TextBox textBox, BaseValidator validator1, BaseValidator validator2)
        {
            // Row
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "Normal");
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);

            // Label
            writer.AddAttribute(HtmlTextWriterAttribute.Wrap, "false");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.RenderBeginTag(HtmlTextWriterTag.B);
            writer.Write(string.Format("{0}&nbsp;&nbsp;", label));
            writer.RenderEndTag();	// B
            writer.RenderEndTag();	// Td

            // Text box
            writer.AddAttribute(HtmlTextWriterAttribute.Wrap, "false");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            textBox.RenderControl(writer);
            writer.RenderEndTag();	// Td

            // Gap
            writer.AddAttribute(HtmlTextWriterAttribute.Wrap, "false");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("&nbsp;&nbsp;");
            writer.RenderEndTag();	// Td

            // Validator
            writer.AddAttribute(HtmlTextWriterAttribute.Wrap, "false");
            writer.AddAttribute(HtmlTextWriterAttribute.Width, "100%");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            validator1.RenderControl(writer);
            if (validator2 != null)
                validator2.RenderControl(writer);
            writer.RenderEndTag();	// Td

            // Close out row
            writer.RenderEndTag();	// Tr
        }
Exemple #42
0
 protected static void SetErrorMessage(BaseValidator validator, Exception exception)
 {
     //Engine.Resolve<IErrorHandler>().Notify(exception);
     SetErrorMessage(validator, exception.Message);
 }