public void StringMinLength()
        {
            var schema = new SimpleTypeSchema("Currency", typeof(string))
                         .SetStringMinLength(3);

            schema.GetStringMinLength() !.MinLength.Should().Be(3);

            Property <string> currency = new Property <string>("Currency")
                                         .SetSchema(schema);

            var validationRules = ValidationProvider.Instance.GetValidationRules(currency).ToList();

            validationRules.Should().HaveCount(1);

            var messages = new MutablePropertyContainer()
                           .WithValue(currency, "USD")
                           .Validate(validationRules)
                           .ToList();

            messages.Should().BeEmpty();

            messages = new MutablePropertyContainer()
                       .WithValue(currency, "a")
                       .Validate(validationRules)
                       .ToList();

            messages[0].FormattedMessage.Should().Be("Value 'a' is too short (length: 1, minLength: 3)");
        }
Ejemplo n.º 2
0
        /// <summary>
        /// クライアントでのバリデーション用の操作
        /// </summary>
        /// <param name="context">クライアントのバリデーションコンテキスト</param>
        public void AddValidation(ClientModelValidationContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (MinLength > 0)
            {
                // 最小値が設定されている場合以下のタグ属性を設定する
                // minlength                            最小桁数
                // notsupported-min-length-err-msg      未サポートブラウザでのエラーメッセージ
                // min-length-err-msg                   バリデーションで設定されたエラーメッセージ
                MergeAttribute(context.Attributes, "minlength", MinLength.ToString());
                MergeAttribute(context.Attributes, "notsupported-min-length-err-msg", "最小桁数「" + MinLength.ToString() + "」より短いです。");
                if (!string.IsNullOrWhiteSpace(UnderMinErrorMessage))
                {
                    MergeAttribute(context.Attributes, "min-length-err-msg", UnderMinErrorMessage);
                }
            }

            if (MaxLength > 0)
            {
                // 最大値が設定されている場合以下のタグ属性を設定する
                // maxlength                            最大桁数
                // notsupported-max-length-err-msg      未サポートブラウザでのエラーメッセージ
                // max-length-err-msg                   バリデーションで設定されたエラーメッセージ
                MergeAttribute(context.Attributes, "maxlength", MaxLength.ToString());
                MergeAttribute(context.Attributes, "notsupported-max-length-err-msg", "最大桁数「" + MaxLength.ToString() + "」より長いです。");
                if (!string.IsNullOrWhiteSpace(ErrorMessageString))
                {
                    MergeAttribute(context.Attributes, "max-length-err-msg", ErrorMessageString);
                }
            }
        }
Ejemplo n.º 3
0
        public void TestRuleMinLength()
        {
            SingleRule       rule   = new MinLength(3);
            ValidationResult result = rule.Validate("abcd");

            Assert.IsTrue(result.IsValid);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// クライアントでのバリデーション用の操作
        /// </summary>
        /// <param name="context">クライアントのバリデーションコンテキスト</param>
        public void AddValidation(ClientModelValidationContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (MinLength > 0)
            {
                // 最小値が設定されている場合以下のタグ属性を設定する
                // minlength                            最小桁数
                // min-length-err-msg                   バリデーションで設定されたエラーメッセージ
                context.Attributes["minlength"] = MinLength.ToString();
                if (!string.IsNullOrWhiteSpace(UnderMinErrorMessage))
                {
                    context.Attributes["minlength-err-msg"] = UnderMinErrorMessage;
                }
            }

            if (MaxLength > 0)
            {
                // 最大値が設定されている場合以下のタグ属性を設定する
                // maxlength                            最大桁数
                // max-length-err-msg                   バリデーションで設定されたエラーメッセージ
                context.Attributes["maxlength"] = MaxLength.ToString();
                if (!string.IsNullOrWhiteSpace(OverMaxErrorMessage))
                {
                    context.Attributes["maxlength-err-msg"] = OverMaxErrorMessage;
                }
            }
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Returns a hash code for this instance.
 /// </summary>
 /// <returns>
 /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
 /// </returns>
 public override int GetHashCode()
 {
     unchecked
     {
         int hashCode = 17 + MinLength.GetHashCode() ^ MaxLength.GetHashCode() ^ AllowNull.GetHashCode() ^
                        ReadOnly.GetHashCode() + 31 * GetHashCode(PossibleValues);
         return((DefaultValue == null) ? hashCode : hashCode *32 + DefaultValue.GetHashCode());
     }
 }
Ejemplo n.º 6
0
        protected override void Execute(CodeActivityContext executionContext)
        {
            var text   = Text.Get <string>(executionContext);
            var min    = MinLength.Get <int>(executionContext);
            var max    = MaxLength.Get <int>(executionContext);
            var result = Codify(text, min, max);

            Result.Set(executionContext, result);
        }
Ejemplo n.º 7
0
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            base.Process(context, output);
            RenderFieldHeader(context, output);

            var id = GetDomId();

            output.Content.AppendHtml("<textarea data-target=\"aiplugs-textarea.textarea\" data-action=\"keydown->aiplugs-textarea#updateHeight\" data-val=\"true\"");

            if (id != null)
            {
                output.Content.AppendHtml($"id=\"{id}\"");
            }

            if (Name != null)
            {
                output.Content.AppendHtml($"name=\"{Name}\"");
            }

            if (Placeholder != null)
            {
                output.Content.AppendHtml($"placeholder=\"{Placeholder}\"");
            }

            if (Required)
            {
                output.Content.AppendHtml($"required data-val-required=\"{Localizer[SharedResource.VAL_MSG_REQUIRED, Label]}\"");
            }

            if (!string.IsNullOrEmpty(Pattern))
            {
                var message = !string.IsNullOrEmpty(PatternErrorMessage) ? PatternErrorMessage : Localizer.MsgValPattern(Label, Pattern);
                output.Attr("data-val-regex", message);
                output.Attr("data-val-regex-pattern", Pattern);
            }

            if (MaxLength.HasValue)
            {
                output.Attr("data-val-maxlength", Localizer.MsgValMaxLengthForString(Label, MaxLength.Value));
                output.Attr("data-val-maxlength-max", MaxLength.ToString());
            }

            if (MinLength.HasValue)
            {
                output.Attr("data-val-minlength", Localizer.MsgValMinLengthForString(Label, MinLength.Value));
                output.Attr("data-val-minlength-min", MinLength.ToString());
            }

            output.Content.AppendHtml(">");
            output.Content.Append(Value ?? "");
            output.Content.AppendHtml("</textarea>");

            RenderFieldFooter(context, output, Name);
        }
Ejemplo n.º 8
0
        public bool MinLength_IsValid(string propertyValue, int minLength)
        {
            //Create Validator
            var validator = new MinLength <Contact>(minLength);
            RuleValidatorContext <Contact, string> context = BuildContextForLength(propertyValue);

            var notification = new ValidationNotification();

            //Validate the validator only, return true of no error returned
            return(validator.Validate(context, null, notification));
        }
Ejemplo n.º 9
0
 /// <summary>
 /// 最小桁数のサーバーバリデーション時のエラーメッセージ取得
 /// </summary>
 /// <param name="displayName">表示名称(DisplayNameアトリビュートで変更できる)</param>
 /// <returns>必須エラーメッセージ</returns>
 string GetUnderMinErrorMessage(string displayName)
 {
     if (string.IsNullOrEmpty(UnderMinErrorMessage))
     {
         return(displayName + "の値が最小値「" + MinLength.ToString() + "」より小さいです。");
     }
     else
     {
         return(UnderMinErrorMessage);
     }
 }
Ejemplo n.º 10
0
        public bool MinLength_Expression_IsValid(string firstName, string lastName)
        {
            //Create Validator
            //FirstName Length must be at least the same length as the LastName
            var validator = new MinLength <Contact>(c => (int)(c.LastName.Length));
            RuleValidatorContext <Contact, string> context = BuildContextForLength(firstName, lastName);

            var notification = new ValidationNotification();

            //Validate the validator only, return true of no error returned
            return(validator.Validate(context, null, notification));
        }
Ejemplo n.º 11
0
        public void RenderInput(TagHelperContext context, TagHelperOutput output, string name, string value = null, bool target = true)
        {
            output.Tag("input", () => {
                output.Attr("type", "checkbox");
                output.Attr("data-val", "true");

                if (value != null)
                {
                    output.Attr("value", value);
                }

                if (Pattern != null)
                {
                    var message = !string.IsNullOrEmpty(PatternErrorMessage) ? PatternErrorMessage : Localizer.MsgValPattern(Label, Pattern);
                    output.Attr("data-val-regex", message);
                    output.Attr("data-val-regex-pattern", Pattern);
                }

                if (MaxLength.HasValue)
                {
                    output.Attr("data-val-maxcount", Localizer.MsgValMaxLengthForArray(Label, MaxLength.Value));
                    output.Attr("data-val-maxcount-max", MaxLength.ToString());
                }

                if (MinLength.HasValue)
                {
                    output.Attr("data-val-mincount", Localizer.MsgValMinLengthForArray(Label, MinLength.Value));
                    output.Attr("data-val-mincount-min", MinLength.ToString());
                }

                if (!MinLength.HasValue && Required)
                {
                    output.Attr("data-val-mincount", Localizer.MsgValRequired(Label));
                    output.Attr("data-val-mincount-min", "1");
                }

                if (target)
                {
                    if (name != null)
                    {
                        output.Attr("name", name);
                    }
                    output.Attr("data-target", "aiplugs-tag-item.input");
                    output.Html(" checked ");
                }
                else
                {
                    output.Attr("class", "aiplugs-tag__dummy val-ignore");
                }
            });
        }
Ejemplo n.º 12
0
        protected override void RegisterClientSideValidationExtensionScripts()
        {
            var template =
                new ScriptTemplate(this, "Macro.ImageServer.Web.Common.WebControls.Validators.LengthValidator.js");

            template.Replace("@@MIN_LENGTH@@", MinLength.ToString());
            template.Replace("@@MAX_LENGTH@@", MaxLength.ToString());
            template.Replace("@@CONDITION_CHECKBOX_CLIENTID@@",
                             ConditionalCheckBox != null ? ConditionalCheckBox.ClientID : "null");
            template.Replace("@@VALIDATE_WHEN_UNCHECKED@@", ValidateWhenUnchecked ? "true" : "false");
            template.Replace("@@IGNORE_EMPTY_VALUE@@", IgnoreEmptyValue ? "true" : "false");

            Page.ClientScript.RegisterClientScriptBlock(GetType(), ClientID + "_ValidatorClass", template.Script, true);
        }
Ejemplo n.º 13
0
 public FileInspectionRequest GetInspectionRequest(string fileName)
 {
     return(new FileInspectionRequest(fileName)
     {
         DataTypes = Types.Select(t => t.Type).ToList(),
         DefaultLength = MinLength == 0 ? "1024" : MinLength.ToString(CultureInfo.InvariantCulture),
         DefaultType = "string",
         MinLength = MinLength,
         LineLimit = LineLimit,
         MaxLength = MaxLength,
         Delimiters = Delimiters.ToDictionary(d => d.Character, d => d),
         Sample = Sample,
         IgnoreEmpty = IgnoreEmpty
     });
 }
Ejemplo n.º 14
0
 /// <summary>
 /// Serves as a hash function for a particular type.
 /// </summary>
 /// <returns>
 /// A hash code for the current <see cref="T:System.Object"/>.
 /// </returns>
 public override int GetHashCode()
 {
     unchecked
     {
         var hashCode = Type.GetHashCode();
         hashCode = (hashCode * 397) ^ (Id?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (Schema?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (Comment?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (Title?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (Description?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (Default?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ MultipleOf.GetHashCode();
         hashCode = (hashCode * 397) ^ Maximum.GetHashCode();
         hashCode = (hashCode * 397) ^ ExclusiveMaximum.GetHashCode();
         hashCode = (hashCode * 397) ^ Minimum.GetHashCode();
         hashCode = (hashCode * 397) ^ ExclusiveMinimum.GetHashCode();
         hashCode = (hashCode * 397) ^ (MaxLength?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (MinLength?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (Pattern?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (AdditionalItems?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (Items?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (MaxItems?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (MinItems?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (UniqueItems?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (Contains?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (AdditionalProperties?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (Definitions?.GetCollectionHashCode().GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (Properties?.GetCollectionHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (PatternProperties?.GetCollectionHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (Dependencies?.GetCollectionHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (Const?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (Enum?.GetCollectionHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (Format?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (ContentMediaType?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (ContentEncoding?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (If?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (Then?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (Else?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (AllOf?.GetCollectionHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (AnyOf?.GetCollectionHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (OneOf?.GetCollectionHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (Not?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (Required?.GetCollectionHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (Examples?.GetCollectionHashCode() ?? 0);
         return(hashCode);
     }
 }
Ejemplo n.º 15
0
        public void WriteXmlSubtree(XmlWriter writer)
        {
            writer.WriteStartElement(XmlStrings.RndSymbolsGen);
            writer.WriteAttributeString(XmlStrings.NameAttr, Name);
            writer.WriteStartElement(XmlStrings.ParamsNode);
            writer.WriteAttributeString("min", MinLength.ToString());
            writer.WriteAttributeString("max", MaxLength.ToString());

            foreach (var s in Lines)
            {
                writer.WriteStartElement("lines");
                writer.WriteString(s);
                writer.WriteEndElement();                 // lines
            }

            writer.WriteEndElement();
            writer.WriteEndElement();
        }
Ejemplo n.º 16
0
        protected override void Render(HtmlTextWriter writer)
        {
            CssClass = CssClass + " validator";
            if (MinLength > 0)
            {
                Attributes["minlength"] = MinLength.ToString();
            }

            if (MaxLength > 0 && MaxLength > MinLength)
            {
                Attributes["maxlength"] = MaxLength.ToString();
            }

            if (!string.IsNullOrEmpty(Group))
            {
                Attributes["group"] = Group;
            }

            if (!string.IsNullOrEmpty(GroupMessage))
            {
                Attributes["groupmessage"] = GroupMessage;
            }

            if (Required)
            {
                Attributes["required"] = Required.ToString();
            }

            if (CustomFunction == null)
            {
                CustomFunction = Function.ToString();
            }

            Attributes["function"] = CustomFunction;
            if (!string.IsNullOrEmpty(ControlToValidate))
            {
                Attributes["validates"] = ControlToValidate;
            }

            base.Render(writer);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Gets the restriction value in string in CultureInfo.CurrentUICulture.
        /// </summary>
        /// <param name="restrictionField">The facet to be retrieved.</param>
        /// <returns>The value in string.</returns>
        public virtual string GetRestrictionValue(RestrictionField restrictionField)
        {
            switch (restrictionField)
            {
            case RestrictionField.Pattern:
                return(Pattern);

            case RestrictionField.Length:
                return(Length.ToString(CultureInfo.CurrentUICulture));

            case RestrictionField.MinLength:
                return(MinLength.ToString(CultureInfo.CurrentUICulture));

            case RestrictionField.MaxLength:
                return(MaxLength.ToString(CultureInfo.CurrentUICulture));

            default:
                Debug.Assert(false);
                return(string.Empty);
            }
        }
Ejemplo n.º 18
0
        public void AddValidation(ClientModelValidationContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var propertyDisplayName = context.ModelMetadata.GetDisplayName();

            AddAttribute(context.Attributes, "data-val", "true");
            AddAttribute(context.Attributes, "data-val-tinymce-required", GetRequiredErrorMessage(propertyDisplayName));

            if (MinLength > 0)
            {
                AddAttribute(context.Attributes, "data-val-tinymce-minlength", GetMinLengthErrorMessage(propertyDisplayName));
                AddAttribute(context.Attributes, "data-val-tinymce-minlength-value", MinLength.ToString(CultureInfo.InvariantCulture));
            }

            if (MaxLength > 0)
            {
                AddAttribute(context.Attributes, "data-val-tinymce-maxlength", GetMaxLengthErrorMessage(propertyDisplayName));
                AddAttribute(context.Attributes, "data-val-tinymce-maxlength-value", MaxLength.ToString(CultureInfo.InvariantCulture));
            }
        }
        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
        {
            string str = (string)value;

            if (string.IsNullOrEmpty(str))
            {
                if (MinLength > 0 && !CanEmpty)
                {
                    return(new ValidationResult(false, string.Format("不能为空")));
                }
                else
                {
                    return(new ValidationResult(true, null));
                }
            }
            #region 构建验证规则
            rule = string.Empty;
            if (IsNumberOnly)
            {
                rule += @"^[0-9";
            }
            else
            {
                rule += @"^[a-zA-Z0-9";
                if (HasUnderline)
                {
                    rule += "_";
                }
                if (HasChinese)
                {
                    rule += "\u4e00-\u9fa5";
                }
            }
            rule += "(),!@#$&*]{" + MinLength.ToString() + "," + MaxLength.ToString() + "}$";
            //string rule = string.Empty;
            //rule += @"^[a-zA-Z0-9_\u4e00";
            //if (HasUnderline)
            //{
            //    rule += "_";
            //}
            //if (HasChinese)
            //{
            //    rule += "\u4e00-\u9fa5";
            //}


            //rule += "]{" + MinLength.ToString() + "," + MaxLength.ToString() + "}$";

            #endregion


            if (Regex.IsMatch(str, rule))
            {
                return(new ValidationResult(true, null));
            }
            else
            {
                if (IsNumberOnly)
                {
                    return(new ValidationResult(false, string.Format("只能是数字组成的{0}-{1}位字符串", MinLength, MaxLength)));
                }
                if (HasChinese && HasUnderline)
                {
                    return(new ValidationResult(false, string.Format("只能是数字,英文字母,汉字,下划线组成的{0}-{1}位字符串", MinLength, MaxLength)));
                }
                else if (HasChinese && !HasUnderline)
                {
                    return(new ValidationResult(false, string.Format("只能是数字,英文字母,汉字组成的{0}-{1}位字符串", MinLength, MaxLength)));
                }
                else
                {
                    return(new ValidationResult(false, string.Format("只能是数字,英文字母,(),!@#$&*,下划线组成的{0}-{1}位字符串", MinLength, MaxLength)));
                }
            }
        }
Ejemplo n.º 20
0
 private void InputCompleted(object sender, EventArgs e)
 {
     try
     {
         Entry input = (Entry)sender;
         var   text  = input.Text;
         if (!string.IsNullOrEmpty(text) && RemoveSpace)
         {
             text = text.Replace(" ", "");
         }
         var length = string.IsNullOrEmpty(text) ? 0 : text.Length;
         IsValid = length >= MinLength;
         if (!IsValid)
         {
             if (MinLength > 1)
             {
                 Reason = MinLength > 0 ? string.Format(AppResources.MinLength, FieldName, MinLength.ToString()) : string.Format(AppResources.RequiredMessage, FieldName);
             }
             else
             {
                 Reason = string.Format(AppResources.RequiredMessage, FieldName);
             }
         }
         else
         {
             Reason = " ";
         }
     }
     catch (Exception e1)
     {
         ExceptionHandler.Catch(e1);
     }
 }
Ejemplo n.º 21
0
        private void Update(EvaluationContext context)
        {
            var stringBuilder = InputBuffer.GetValue(context);

            Builder.Value = stringBuilder;
            if (stringBuilder == null)
            {
                return;
            }

            var bufferLength = stringBuilder.Length;

            if (TriggerChop.GetValue(context))
            {
                //if (stringBuilder.Length < MaxLength.GetValue(context))
                //    stringBuilder.Append(String.GetValue(context));
                var minRandomLength = MinLength.GetValue(context);
                if (minRandomLength < 0)
                {
                    minRandomLength = 0;
                }

                var maxRandomLength = MaxLength.GetValue(context);
                if (maxRandomLength < minRandomLength)
                {
                    maxRandomLength = minRandomLength;
                }

                var lenRemove = (int)_random.NextLong(minRandomLength, maxRandomLength);

                var maxRandPos = bufferLength - lenRemove;
                if (maxRandPos < 0)
                {
                    maxRandPos = 0;
                }

                var randPos = (int)_random.NextLong(0, maxRandPos);
                if (lenRemove > 0 && lenRemove < bufferLength)
                {
                    stringBuilder.Remove(randPos, lenRemove);
                }
            }

            var fillString = FillString.GetValue(context);

            bufferLength = stringBuilder.Length;
            if (TriggerFill.GetValue(context) && fillString.Length > 0 && bufferLength > 0)
            {
                if (TriggerFillJump.GetValue(context))
                {
                    _fillIndex = (int)_random.NextLong(0, bufferLength);
                }
                _fillIndex += FillDirection.GetValue(context);
                _fillIndex %= bufferLength;
                if (_fillIndex < 0)
                {
                    _fillIndex += bufferLength;
                }

                stringBuilder[_fillIndex] = fillString[_fillIndex % fillString.Length];
            }
        }
Ejemplo n.º 22
0
        public bool MinLength_IsValid(string propertyValue, int minLength)
        {
            //Create Validator
            var validator = new MinLength<Contact>(minLength);
            RuleValidatorContext<Contact, string> context = BuildContextForLength(propertyValue);

            var notification = new ValidationNotification();

            //Validate the validator only, return true of no error returned
            return validator.Validate(context, null, notification);
        }
Ejemplo n.º 23
0
        public bool MinLength_Expression_IsValid(string firstName, string lastName)
        {
            //Create Validator
            //FirstName Length must be at least the same length as the LastName
            var validator = new MinLength<Contact>(c => (int)(c.LastName.Length));
            RuleValidatorContext<Contact, string> context = BuildContextForLength(firstName, lastName);

            var notification = new ValidationNotification();

            //Validate the validator only, return true of no error returned
            return validator.Validate(context, null, notification);
        }
Ejemplo n.º 24
0
        protected override void OnLoad(EventArgs e)
        {
            // startup init script
            WetControls.Extensions.ClientScript.InitScript(Page);

            // datepicker script
            if (IsDate)
            {
                WetControls.Extensions.ClientScript.InitDatePicker(this.Page);
            }
            // gouvernment email script
            if (IsGovernmentEmail)
            {
                WetControls.Extensions.ClientScript.InitFrmvldGovemail(this.Page, this.ErrorGovEmail);
            }
            // price script
            if (IsPrice)
            {
                WetControls.Extensions.ClientScript.InitFrmvldPrice(this.Page, this.ErrorPrice);
            }

            if (EnableClientValidation)
            {
                // attributes validation conflicts
                VerifyValidationConflicts();

                if (IsRequired)
                {
                    base.Attributes.Add("required", "required");
                }
                if (IsPhoneNumber)
                {
                    base.Attributes.Add("data-rule-phoneUS", "true");
                }
                if (IsPostalCode)
                {
                    base.Attributes.Add("size", "7");
                    base.Attributes.Add("data-rule-postalCodeCA", "true");
                }
                if (IsEmail)
                {
                    base.Attributes.Add("type", "email");
                }
                if (IsGovernmentEmail)
                {
                    base.Attributes.Add("data-rule-govemail", "true");
                }
                if (IsUrl)
                {
                    base.Attributes.Add("type", "url");
                }
                if (IsDate)
                {
                    base.Attributes.Add("type", "date");
                    base.Attributes.Add("data-rule-dateISO", "true");
                }
                if (IsTime)
                {
                    base.Attributes.Add("type", "time");
                }
                if (IsAlphanumeric)
                {
                    base.Attributes.Add("pattern", "[A-Za-z0-9_\\s]");
                    base.Attributes.Add("data-rule-alphanumeric", "true");
                }
                if (IsDigitsOnly)
                {
                    base.Attributes.Add("type", "number");
                    base.Attributes.Add("data-rule-digits", "true");
                }
                if (IsPrice)
                {
                    base.Attributes.Add("data-rule-price", "true");
                }
                if (IsLettersOnly)
                {
                    base.Attributes.Add("pattern", "[A-Za-z\\s]");
                    base.Attributes.Add("data-rule-lettersonly", "true");
                }
                if (IsLettersWithBasicPunc)
                {
                    base.Attributes.Add("pattern", "[A-Za-z-.,()'\"\\s]");
                    base.Attributes.Add("data-rule-letterswithbasicpunc", "true");
                }
                if (IsNoWhiteSpace)
                {
                    base.Attributes.Add("pattern", "[A-Za-z-.,()'\"\\s]");
                    base.Attributes.Add("data-rule-nowhitespace", "true");
                }
                if (IsNumber)
                {
                    base.Attributes.Add("type", "number");
                }
                if (MinNumber != 0 && MaxNumber != 0)
                {
                    base.Attributes.Add("data-rule-range", string.Format("[{0},{1}]", MinNumber, MaxNumber));
                }
                else if (MinNumber != 0)
                {
                    base.Attributes.Add("min", MinNumber.ToString());
                }
                else if (MaxNumber != 0)
                {
                    base.Attributes.Add("max", MaxNumber.ToString());
                }
                if (StepNumber != 0)
                {
                    base.Attributes.Add("step", StepNumber.ToString());
                }
                if (MinLength > 0 && MaxLength > 0)
                {
                    base.Attributes.Add("data-rule-rangelength", string.Format("[{0},{1}]", MinLength, MaxLength));
                }
                else if (MinLength > 0)
                {
                    base.Attributes.Add("data-rule-minlength", MinLength.ToString());
                }
                else if (MaxLength > 0)
                {
                    base.Attributes.Add("maxlength", MaxLength.ToString());
                }
                if (MinWords > 0 && MaxWords > 0)
                {
                    base.Attributes.Add("data-rule-rangeWords", string.Format("[{0},{1}]", MinWords, MaxWords));
                }
                else if (MinWords > 0)
                {
                    base.Attributes.Add("data-rule-minWords", MinWords.ToString());
                }
                else if (MaxWords > 0)
                {
                    base.Attributes.Add("data-rule-maxWords", MaxWords.ToString());
                }
                if (!string.IsNullOrEmpty(EqualTo))
                {
                    Control ctrl = Page.FindControlRecursive(EqualTo.TrimStart('#')); // prevent tag at beginning
                    base.Attributes.Add("data-rule-equalTo", (ctrl == null ? "#" + EqualTo : "#" + ctrl.ClientID));
                }
                if (!string.IsNullOrEmpty(ValidationErrorMsg))
                {
                    base.Attributes.Add("data-msg", ValidationErrorMsg);
                }
            }
            if (!string.IsNullOrEmpty(Placeholder))
            {
                base.Attributes.Add("placeholder", Placeholder);
            }

            base.OnLoad(e);
        }
Ejemplo n.º 25
0
Archivo: Code.cs Proyecto: aiplugs/tags
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            base.Process(context, output);
            RenderFieldHeader(context, output);

            var id = GetDomId();

            output.Html("<div class=\"aiplugs-code__cover\">");

            output.Tag("textarea", () => {
                if (id != null)
                {
                    output.Attr("id", id);
                }

                if (Name != null)
                {
                    output.Attr("name", Name);
                }

                if (Required)
                {
                    output.Attr("required");
                    output.Attr("data-val-required", Localizer.MsgValRequired(Label));
                }

                if (!string.IsNullOrEmpty(Pattern))
                {
                    var message = !string.IsNullOrEmpty(PatternErrorMessage) ? PatternErrorMessage : Localizer.MsgValPattern(Label, Pattern);
                    output.Attr("data-val-regex", message);
                    output.Attr("data-val-regex-pattern", Pattern);
                }

                if (MaxLength.HasValue)
                {
                    output.Attr("data-val-maxlength", Localizer.MsgValMaxLengthForString(Label, MaxLength.Value));
                    output.Attr("data-val-maxlength-max", MaxLength.ToString());
                }

                if (MinLength.HasValue)
                {
                    output.Attr("data-val-minlength", Localizer.MsgValMinLengthForString(Label, MinLength.Value));
                    output.Attr("data-val-minlength-min", MinLength.ToString());
                }

                output.Attr("data-target", "aiplugs-code.input");
                output.Attr("data-val", "true");
            }, Value);

            output.Tag("pre", null, () => {
                output.Tag("code", () => {
                    var @class = "aiplugs-code__view";
                    if (Lang != null)
                    {
                        @class = $"{@class} {Lang}";
                    }

                    output.Attr("class", @class);
                    output.Attr("data-target", "aiplugs-code.view");
                }, Value);
            });

            output.Html("<div class=\"aiplugs-code__screen\" data-action=\"click->aiplugs-code#edit\">");
            output.Html("<div><i class=\"fa fa-edit\"></i></div>");
            output.Html("</div>");

            output.Html("</div>");

            output.Html("<button type=\"button\" class=\"fas aiplugs-code__toggle\" data-action=\"aiplugs-code#toggleView\"></button>");

            output.Tag("template", () => {
                output.Attr("data-controller", "aiplugs-dialog-template");
            }, () => {
                output.HtmlLine($"<div class=\"aiplugs-dialog\" data-controller=\"aiplugs-dialog\">");
                output.HtmlLine($"<div class=\"aiplugs-dialog__content\">");
                output.HtmlLine($"<p class=\"aiplugs-dialog__message\">{Localizer.MsgConfirmDiscard(Label)}</p>");
                output.HtmlLine("<div class=\"aiplugs-dialog__actions\">");
                output.HtmlLine($"<button class=\"aiplugs-button --warning aiplugs-code__close-realy\">{Localizer.LabelConfirmDiscardYes()}</button>");
                output.HtmlLine($"<button class=\"aiplugs-button --block --primary\" data-action=\"aiplugs-dialog#close\">{Localizer.LabelConfirmDiscardNo()}</button>");
                output.HtmlLine("</div>");
                output.HtmlLine("</div>");
                output.HtmlLine("</div>");
            });

            RenderFieldFooter(context, output, Name);
        }
        /// <summary>
        /// In HTML konvertieren
        /// </summary>
        /// <param name="context">Der Kontext, indem das Steuerelement dargestellt wird</param>
        /// <returns>Das Control als HTML</returns>
        public override IHtmlNode Render(RenderContextFormular context)
        {
            Classes.Add("form-control");

            if (Disabled)
            {
                Classes.Add("disabled");
            }

            switch (ValidationResult)
            {
            case TypesInputValidity.Success:
                Classes.Add("input-success");
                break;

            case TypesInputValidity.Warning:
                Classes.Add("input-warning");
                break;

            case TypesInputValidity.Error:
                Classes.Add("input-error");
                break;
            }

            if (AutoInitialize && Format == TypesEditTextFormat.Wysiwyg && !string.IsNullOrWhiteSpace(ID))
            {
                context.Page.AddScript(ID, InitializeCode);
                AutoInitialize = false;
            }

            return(Format switch
            {
                TypesEditTextFormat.Multiline => new HtmlElementFormTextarea()
                {
                    ID = ID,
                    Value = Value,
                    Name = Name,
                    Class = string.Join(" ", Classes.Where(x => !string.IsNullOrWhiteSpace(x))),
                    Style = string.Join("; ", Styles.Where(x => !string.IsNullOrWhiteSpace(x))),
                    Role = Role,
                    Placeholder = Placeholder,
                    Rows = Rows.ToString()
                },
                TypesEditTextFormat.Wysiwyg => new HtmlElementFormTextarea()
                {
                    ID = ID,
                    Value = Value,
                    Name = Name,
                    Class = string.Join(" ", Classes.Where(x => !string.IsNullOrWhiteSpace(x))),
                    Style = string.Join("; ", Styles.Where(x => !string.IsNullOrWhiteSpace(x))),
                    Role = Role,
                    Placeholder = Placeholder,
                    Rows = Rows.ToString()
                },
                _ => new HtmlElementFieldInput()
                {
                    ID = ID,
                    Value = Value,
                    Name = Name,
                    MinLength = MinLength?.ToString(),
                    MaxLength = MaxLength?.ToString(),
                    Required = Required,
                    Pattern = Pattern,
                    Type = "text",
                    Disabled = Disabled,
                    Class = string.Join(" ", Classes.Where(x => !string.IsNullOrWhiteSpace(x))),
                    Style = string.Join("; ", Styles.Where(x => !string.IsNullOrWhiteSpace(x))),
                    Role = Role,
                    Placeholder = Placeholder
                },
            });
Ejemplo n.º 27
0
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value is string str && (string.IsNullOrWhiteSpace(str) || str.Length < MinLength || str.Length > MaxLength))
            {
                return(new ValidationResult(SharedResources.StringLengthValidationErrorMask.With(MinLength.ToString(), MaxLength.ToString())));
            }

            return(ValidationResult.Success);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Converts the edge to the table-valued function
        /// </summary>
        /// <param name="nodeAlias">Source node alias</param>
        /// <param name="dumbNode"></param>
        /// <param name="metaData">Meta data</param>
        /// <returns>A syntax tree node representing the table-valued function</returns>
        public override WSchemaObjectFunctionTableReference ToSchemaObjectFunction(string nodeAlias, string dumbNode, GraphMetaData metaData)
        {
            var edgeIdentifiers   = EdgeColumn.MultiPartIdentifier.Identifiers;
            var edgeColIdentifier = edgeIdentifiers.Last();
            HashSet <string> nodeSet;

            if (!metaData.NodeViewMapping.TryGetValue(
                    WNamedTableReference.SchemaNameToTuple(SourceNode.NodeTableObjectName), out nodeSet))
            {
                nodeSet = null;
            }
            var sourceNodeColumns =
                metaData.ColumnsOfNodeTables[WNamedTableReference.SchemaNameToTuple(BindNodeTableObjName)];
            var edgeInfo = sourceNodeColumns[edgeColIdentifier.Value].EdgeInfo;
            List <Tuple <string, string> > edgeTuples = edgeInfo.EdgeColumns;
            var parameters = ConstructEdgeTvfParameters(nodeAlias, null, nodeSet, edgeTuples);

            Identifier decoderFunction;

            if (ReferencePathInfo)
            {
                decoderFunction = new Identifier
                {
                    Value = BindNodeTableObjName.SchemaIdentifier.Value + '_' +
                            BindNodeTableObjName.BaseIdentifier.Value + '_' +
                            EdgeColumn.MultiPartIdentifier.Identifiers.Last().Value + '_' +
                            "bfsPathWithMessage"
                };
                // Node view
                if (nodeSet != null)
                {
                    parameters.Insert(0, new WColumnReferenceExpression
                    {
                        MultiPartIdentifier =
                            new WMultiPartIdentifier(new Identifier()
                        {
                            Value = SourceNode.RefAlias
                        },
                                                     new Identifier()
                        {
                            Value = "_NodeId"
                        })
                    });
                    parameters.Insert(0, new WColumnReferenceExpression
                    {
                        MultiPartIdentifier =
                            new WMultiPartIdentifier(new Identifier()
                        {
                            Value = SourceNode.RefAlias
                        },
                                                     new Identifier()
                        {
                            Value = "_NodeType"
                        })
                    });
                }
                else
                {
                    string nodeIdName =
                        sourceNodeColumns.FirstOrDefault(e => e.Value.Role == WNodeTableColumnRole.NodeId).Key;
                    if (string.IsNullOrEmpty(nodeIdName))
                    {
                        parameters.Insert(0, new WValueExpression {
                            Value = "null"
                        });
                    }
                    else
                    {
                        parameters.Insert(0, new WColumnReferenceExpression
                        {
                            MultiPartIdentifier =
                                new WMultiPartIdentifier(new Identifier()
                            {
                                Value = SourceNode.RefAlias
                            },
                                                         new Identifier()
                            {
                                Value = nodeIdName
                            })
                        });
                    }
                    parameters.Insert(0,
                                      new WValueExpression {
                        Value = BindNodeTableObjName.BaseIdentifier.Value, SingleQuoted = true
                    });
                }
            }
            else
            {
                decoderFunction = new Identifier
                {
                    Value = BindNodeTableObjName.SchemaIdentifier.Value + '_' +
                            BindNodeTableObjName.BaseIdentifier.Value + '_' +
                            EdgeColumn.MultiPartIdentifier.Identifiers.Last().Value + '_' +
                            "bfsPath"
                };
            }
            parameters.Insert(0, new WValueExpression {
                Value = MaxLength.ToString()
            });
            parameters.Insert(0, new WValueExpression {
                Value = MinLength.ToString()
            });
            parameters.Insert(0,
                              new WColumnReferenceExpression
            {
                MultiPartIdentifier =
                    new WMultiPartIdentifier(new[] { new Identifier {
                                                         Value = nodeAlias
                                                     }, new Identifier {
                                                         Value = "GlobalNodeId"
                                                     }, })
            });
            var attributes = edgeInfo.ColumnAttributes;

            if (AttributeValueDict == null)
            {
                WValueExpression nullExpression = new WValueExpression {
                    Value = "null"
                };
                for (int i = 0; i < attributes.Count; i++)
                {
                    parameters.Add(nullExpression);
                }
            }
            else
            {
                foreach (var attribute in attributes)
                {
                    string value;
                    var    valueExpression = new WValueExpression
                    {
                        Value = AttributeValueDict.TryGetValue(attribute, out value) ? value : "null"
                    };

                    parameters.Add(valueExpression);
                }
            }
            return(new WSchemaObjectFunctionTableReference
            {
                SchemaObject = new WSchemaObjectName(
                    new Identifier {
                    Value = "dbo"
                },
                    decoderFunction),
                Parameters = parameters,
                Alias = new Identifier
                {
                    Value = EdgeAlias,
                }
            });
        }
Ejemplo n.º 29
0
        public void RenderCheckbox(TagHelperContext context, TagHelperOutput output)
        {
            var id        = GetDomId();
            var selection = Selection ?? new SelectListItem[0];

            RenderFieldFooter(context, output, Name?.WithArraySuffix());

            foreach (var item in selection)
            {
                output.Html("<label class=\"aiplugs-select__checkbox\">");

                output.Tag("input", () => {
                    output.Attr("type", "checkbox");
                    output.Attr("data-target", "aiplugs-select.checkbox");
                    output.Attr("data-action", "change->aiplugs-select#update");
                    output.Attr("data-val", "true");

                    if (Name != null)
                    {
                        output.Attr("name", Name?.WithArraySuffix());
                    }

                    if (item.Selected)
                    {
                        output.Html(" checked ");
                    }

                    if (item.Disabled)
                    {
                        output.Html(" disabled ");
                    }

                    if (MaxLength.HasValue)
                    {
                        output.Attr("data-val-maxcount", Localizer.MsgValMaxLengthForArray(Label, MaxLength.Value));
                        output.Attr("data-val-maxcount-max", MaxLength.ToString());
                    }

                    if (MinLength.HasValue)
                    {
                        output.Attr("data-val-mincount", Localizer.MsgValMinLengthForArray(Label, MinLength.Value));
                        output.Attr("data-val-mincount-min", MinLength.ToString());
                    }

                    if (!MinLength.HasValue && Required)
                    {
                        output.Attr("data-val-mincount", Localizer.MsgValRequired(Label));
                        output.Attr("data-val-mincount-min", "1");
                    }

                    if (item.Value != null)
                    {
                        output.Attr("value", item.Value);
                    }
                });


                output.Text(item.Text);
                output.Html("</label>");
            }
        }
Ejemplo n.º 30
0
        public void RenderSelect(TagHelperContext context, TagHelperOutput output)
        {
            var id        = GetDomId();
            var name      = Multiple ? Name.WithArraySuffix() : Name;
            var selection = Selection ?? new SelectListItem[0];

            output.Tag("select", () => {
                output.Attr("data-val", "true");

                if (id != null)
                {
                    output.Attr("id", id);
                }

                if (name != null)
                {
                    output.Attr("name", name);
                }

                if (Multiple)
                {
                    output.Html(" multiple ");
                    if (MaxLength.HasValue)
                    {
                        output.Attr("data-val-maxcount", Localizer.MsgValMaxLengthForArray(Label, MaxLength.Value));
                        output.Attr("data-val-maxcount-max", MaxLength.ToString());
                    }

                    if (MinLength.HasValue)
                    {
                        output.Attr("data-val-mincount", Localizer.MsgValMinLengthForArray(Label, MinLength.Value));
                        output.Attr("data-val-mincount-min", MinLength.ToString());
                    }
                }

                if (Required)
                {
                    output.Html(" required ");
                    output.Attr("data-val-required", Localizer.MsgValRequired(Label));
                }
            }, () => {
                foreach (var item in selection)
                {
                    output.Tag("option", () => {
                        output.Attr("value", item.Value);

                        if (item.Selected)
                        {
                            output.Html(" selected");
                        }

                        if (item.Disabled)
                        {
                            output.Html(" disabled");
                        }
                    }, item.Text);
                }
            });

            RenderFieldFooter(context, output, name);
        }
Ejemplo n.º 31
0
 public static StringValidator ExactLength(int length) =>
 v => MinLength(length)(v) | MaxLength(length)(v);
Ejemplo n.º 32
0
        /// <summary>
        /// 改写OnPreRender
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPreRender(EventArgs e)
        {
            //添加默认样式表
            if (string.IsNullOrWhiteSpace(this.CssClass))
            {
                this.CssClass = "myTextBox";
            }
            else if (this.CssClass.IndexOf("myTextBox") == -1)
            {
                this.CssClass += " myTextBox";
            }

            if (IsRequired)
            {
                if (this.Attributes["IsRequired"] == null)
                {
                    this.Attributes.Add("IsRequired", "True");
                }
                else
                {
                    this.Attributes["IsRequired"] = "true";
                }
            }
            if (MinLength > 0)
            {
                if (this.Attributes["MinLength"] == null)
                {
                    this.Attributes.Add("MinLength", MinLength.ToString());
                }
                else
                {
                    this.Attributes["MinLength"] = MinLength.ToString();
                }
            }
            if (!string.IsNullOrWhiteSpace(WatermarkText))
            {
                if (this.Attributes["placeholder"] == null)
                {
                    this.Attributes.Add("placeholder", WatermarkText);
                }
                else
                {
                    this.Attributes["placeholder"] = WatermarkText;
                }
            }
            if (!string.IsNullOrWhiteSpace(ValidationExpression))
            {
                if (this.Attributes["ValidationExpression"] == null)
                {
                    this.Attributes.Add("ValidationExpression", ValidationExpression);
                }
                else
                {
                    this.Attributes["ValidationExpression"] = ValidationExpression;
                }
            }
            if (IsFilterSqlChars)
            {
                if (this.Attributes["IsFilterSqlChars"] == null)
                {
                    this.Attributes.Add("IsFilterSqlChars", "True");
                }
                else
                {
                    this.Attributes["IsFilterSqlChars"] = "True";
                }
            }
            if (IsFilterSpecialChars)
            {
                if (this.Attributes["IsFilterSpecialChars"] == null)
                {
                    this.Attributes.Add("IsFilterSpecialChars", "True");
                }
                else
                {
                    this.Attributes["IsFilterSpecialChars"] = "True";
                }
            }

            if (this.Attributes["MyInputType"] == null)
            {
                this.Attributes.Add("MyInputType", this.GetType().Name);
            }
            else
            {
                this.Attributes["MyInputType"] = this.GetType().Name;
            }

            if (this.Attributes["ShowErrorType"] == null)
            {
                this.Attributes.Add("ShowErrorType", ShowErrorType.ToString());
            }
            else
            {
                this.Attributes["ShowErrorType"] = ShowErrorType.ToString();
            }

            if (this.TextMode == System.Web.UI.WebControls.TextBoxMode.MultiLine)
            {
                this.Attributes.Add("TextAreaMaxLength", MaxLength.ToString());
            }

            base.OnPreRender(e);
        }