Ejemplo n.º 1
0
 public void WithNull()
 {
     RequiredValidator validator = new RequiredValidator();
     validator.Test = Expression.Parse("null");
     IValidationErrors errors = new ValidationErrors();
     Assert.IsFalse(validator.Validate(null, errors));
 }
Ejemplo n.º 2
0
 public void WithNegativeNumber()
 {
     RequiredValidator validator = new RequiredValidator();
     validator.Test = Expression.Parse("-100");
     IValidationErrors errors = new ValidationErrors();
     Assert.IsTrue(validator.Validate(null, errors));
 }
Ejemplo n.º 3
0
    public async Task FindOrCreateFromJson() {
      var em1 = await TestFns.NewEm(_serviceName);

      var vr = new RequiredValidator();
      var vrNode = ((IJsonSerializable) vr).ToJNode(null);
      var vr2 = Validator.FindOrCreate(vrNode);
      var vr3 = Validator.FindOrCreate(vrNode);
      Assert.IsTrue(vr2 == vr3);

      var mlVr = new MaxLengthValidator(17);
      var mlVrNode = ((IJsonSerializable)mlVr).ToJNode(null);
      var mlVr2 = Validator.FindOrCreate(mlVrNode);
      var mlVr3 = Validator.FindOrCreate(mlVrNode);
      Assert.IsTrue(mlVr2 == mlVr3);
      
    }
Ejemplo n.º 4
0
    public async Task FindOrCreateFromJson() {
      await _emTask;

      var vr = new RequiredValidator();
      var vrNode = ((IJsonSerializable) vr).ToJNode(null);
      var vr2 = Validator.FindOrCreate(vrNode);
      var vr3 = Validator.FindOrCreate(vrNode);
      Assert.IsTrue(vr2 == vr3);

      var mlVr = new MaxLengthValidator(17);
      var mlVrNode = ((IJsonSerializable)mlVr).ToJNode(null);
      var mlVr2 = Validator.FindOrCreate(mlVrNode);
      var mlVr3 = Validator.FindOrCreate(mlVrNode);
      Assert.IsTrue(mlVr2 == mlVr3);
      
    }
Ejemplo n.º 5
0
    public async Task InternValidators() {
      await _emTask;

      var vr2 = new RequiredValidator().Intern();
      var vr3 = new RequiredValidator().Intern();
      Assert.IsTrue(vr2 == vr3);
      Assert.IsTrue(vr2.Equals(vr3));

      var mlVr2 = new MaxLengthValidator(17).Intern();
      var mlVr3 = new MaxLengthValidator(17).Intern();
      Assert.IsTrue(mlVr2 == mlVr3);
      Assert.IsTrue(mlVr2.Equals(mlVr3));

      var slVr2 = new StringLengthValidator(3, 12).Intern();
      var slVr3 = new StringLengthValidator(3, 12).Intern();
      Assert.IsTrue(slVr2 == slVr3);
      Assert.IsTrue(slVr2.Equals(slVr3));

    }
Ejemplo n.º 6
0
        public async Task InternValidators()
        {
            var em1 = await TestFns.NewEm(_serviceName);

            var vr2 = new RequiredValidator().Intern();
            var vr3 = new RequiredValidator().Intern();

            Assert.IsTrue(vr2 == vr3);
            Assert.IsTrue(vr2.Equals(vr3));

            var mlVr2 = new MaxLengthValidator(17).Intern();
            var mlVr3 = new MaxLengthValidator(17).Intern();

            Assert.IsTrue(mlVr2 == mlVr3);
            Assert.IsTrue(mlVr2.Equals(mlVr3));

            var slVr2 = new StringLengthValidator(3, 12).Intern();
            var slVr3 = new StringLengthValidator(3, 12).Intern();

            Assert.IsTrue(slVr2 == slVr3);
            Assert.IsTrue(slVr2.Equals(slVr3));
        }
Ejemplo n.º 7
0
        public void CreateColumn()
        {
            var finalMember = Member.FinalMemberInfo;

            Column = new Column()
            {
                Table        = DataType.Table,
                Name         = Member.Expression.Replace('.', '_'),
                DbType       = Sql.DbTypeMapper.Parse(MemberExpression.GetReturnType(finalMember)),
                IsNullable   = !RequiredValidator.IsRequired(finalMember),
                IsPrimaryKey = IsPrimaryKey(finalMember),
            };

            Column.IsAutoNumber = Column.IsNumeric && Column.IsPrimaryKey && DataType.BaseDataType == null;

            if (Column.IsString)
            {
                Column.Length = StringLengthValidator.GetMaxLength(finalMember);
            }

            DataType.Table.Columns.Add(Column);
        }
    public void AllowEmptyString_Ok()
    {
        var foo       = new Foo();
        var validator = new RequiredValidator()
        {
            AllowEmptyString = false,
            ErrorMessage     = "Test-ErrorMessage"
        };
        var context = new ValidationContext(foo);
        var results = new List <ValidationResult>();

        validator.Validate(null, context, results);
        Assert.Equal(validator.ErrorMessage, results[0].ErrorMessage);

        validator.Validate("", context, results);
        Assert.Equal(validator.ErrorMessage, results[0].ErrorMessage);

        validator.AllowEmptyString = true;
        results.Clear();
        validator.Validate("", context, results);
        Assert.Empty(results);
    }
Ejemplo n.º 9
0
        public Phone()
        {
            this.DataType       = DataType.Number;
            this.ControlType    = ControlType.TextBox;
            this.IsConfigurable = true;

            var requiredValidator1 = new RequiredValidator();

            this.AddValidator(requiredValidator1);

            //var requiredValidator2 = new RangeValidator();
            //this.AddValidator(requiredValidator2);

            var lengthvalidator = new LengthValidator();

            lengthvalidator.Dblength    = 10;
            lengthvalidator.MinDblength = 10;
            this.AddValidator(lengthvalidator);
            var defaultValueValidattor = new DefaultValueValidator(ControlType);

            this.AddValidator(defaultValueValidattor);
        }
    public void Localizer_Ok()
    {
        var foo       = new Foo();
        var validator = new RequiredValidator()
        {
            AllowEmptyString = false,
            ErrorMessage     = "Name",
            LocalizerFactory = Context.Services.GetRequiredService <IStringLocalizerFactory>(),
        };
        var context = new ValidationContext(foo);
        var results = new List <ValidationResult>();

        validator.Validate("v1", context, results);
        Assert.Empty(results);

        context.MemberName = "Name";
        validator.Validate("v1", context, results);
        Assert.Empty(results);

        validator.Options = Context.Services.GetRequiredService <IOptions <JsonLocalizationOptions> >().Value;
        validator.Options.ResourceManagerStringLocalizerType = typeof(Foo);
        validator.Validate("v1", context, results);
        Assert.Empty(results);
    }
Ejemplo n.º 11
0
        public Email()
        {
            this.DataType       = DataType.Email;
            this.ControlType    = ControlType.TextBox;
            this.IsConfigurable = true;

            var requiredValidator1 = new RequiredValidator();

            this.AddValidator(requiredValidator1);

            // var requiredValidator2 = new RangeValidator();
            // this.AddValidator(requiredValidator2);

            var emailformatvalidator = new EmailFormatValidator();

            emailformatvalidator.RegexFormat = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                                               @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                                               @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";

            this.AddValidator(emailformatvalidator);
            var defaultValueValidattor = new DefaultValueValidator(ControlType);

            this.AddValidator(defaultValueValidattor);
        }
Ejemplo n.º 12
0
        public static BaseValidator FactoryMethod(string type)
        {
            BaseValidator validator = null;

            switch (type)
            {
            case "required":
                validator = new RequiredValidator();
                validator.compareOption = BaseValidator.CompareOption.And;
                break;

            case "range":
                validator = new RangeValidator();
                validator.compareOption = BaseValidator.CompareOption.And;
                break;

            case "compare":
                validator = new CompareValidator();
                validator.compareOption = BaseValidator.CompareOption.And;
                break;

            case "regex":
                validator = new RegexValidator();
                validator.compareOption = BaseValidator.CompareOption.And;
                break;

            case "mailandphone":
                validator = new RegexValidator();
                validator.compareOption = BaseValidator.CompareOption.Or;
                break;

            default:
                break;
            }
            return(validator);
        }
Ejemplo n.º 13
0
        private Validator BuildValidator(Dictionary <string, object> data)
        {
            var       name = data["name"];
            Validator v;

            if (name as string == "required")
            {
                v = new RequiredValidator();
            }
            else if (name as string == "maxLength")
            {
                v = new MaxLengthValidator();
            }
            else
            {
                v = new Validator();
            }
            v.name = name.ToString();
            if (data.Count > 1)
            {
                v.properties = data;
            }
            return(v);
        }
Ejemplo n.º 14
0
 public static bool Required <T>(T?input) where T : struct
 {
     return(RequiredValidator.IsValidImpl(input, typeof(T?)));
 }
Ejemplo n.º 15
0
 public void IsValidImpl_applies_to_common_values(Type type, object value)
 {
     Assert.False(
         RequiredValidator.IsValidImpl(value, type)
         );
 }
Ejemplo n.º 16
0
 public void boolean_should_be_true_for_required()
 {
     Assert.True(RequiredValidator.IsValidImpl(true));
     Assert.False(RequiredValidator.IsValidImpl(false));
 }
 public RequiredModelValidator(EasyModelMetaData metadata, ControllerContext context, RequiredValidator requiredvalidator)
     : base(metadata, context)
 {
     this.Attribute = new RequiredAttribute {
         ErrorMessage = requiredvalidator.ErrorMessage
     };
     //this.Attribute.ErrorMessageResourceType = Metadata.ContainerType;
     //this.Attribute.ErrorMessageResourceName = Metadata.PropertyName;
 }
Ejemplo n.º 18
0
        /// <summary>
        /// Creates a list of new DataTypes, creating as well a list of new Tables with all members of type as columns
        /// </summary>
        public static IEnumerable <DataType> DefaultMap(IEnumerable <Type> types)
        {
            //we will store here all types that are actually persistent
            List <DataType> persistentTypes = new List <DataType>();
            Random          random          = new Random();

            //map primary keys first, so we allow to foreign keys and inheritance to be correctly mapped
            foreach (Type type in types)
            {
                //skip enums and interfaces
                if (type.GetTypeInfo().IsEnum || type.GetTypeInfo().IsInterface)
                {
                    continue;
                }

                //ignore types with no primary key
                var pk = GetMappableMembers(type).Where(m => DataMember.IsPrimaryKey(m));

                if (pk.Count() == 0)
                {
                    continue;
                }

                DataType dtype = new DataType(type);
                AllDataTypes.Add(dtype);

                foreach (var memberInfo in pk)
                {
                    //create datamember
                    dtype.AddMember(memberInfo.Name);
                }

                persistentTypes.Add(dtype);
            }

            foreach (DataType dtype in persistentTypes)
            {
                //create inheritance foreign keys
                if (dtype.BaseDataType != null)
                {
                    ForeignKey foreignKey = new ForeignKey();
                    foreignKey.Table       = dtype.Table;
                    foreignKey.RemoteTable = dtype.BaseDataType.Table;
                    foreignKey.Name        = "FK_" + dtype.Name + "_" + dtype.BaseDataType.Name + "_" + random.Next();

                    //we asume that primary keys on parent and child tables have the same number and order of related columns
                    for (int i = 0; i < dtype.PrimaryKey.Count(); i++)
                    {
                        DataMember pk     = dtype.PrimaryKey.ToArray()[i];
                        DataMember basePk = dtype.BaseDataType.PrimaryKey.ToArray()[i];

                        foreignKey.Columns.Add(new Tuple <Column, Column>(pk.Column, basePk.Column));
                    }

                    dtype.Table.ForeignKeys.Add(foreignKey);
                }

                //map non primary key members now
                foreach (var memberInfo in GetMappableMembers(dtype.InnerType).Where(m => !DataMember.IsPrimaryKey(m)))
                {
                    Type returnType = MemberExpression.GetReturnType(memberInfo);

                    //is this a collection of a mapped type? if so, ignore since this must be a 1-1, 1-many or many-many relationship and must be mapped somewhere else
                    if (DataType.IsCollection(returnType) && IsMapped(returnType.GetCollectionItemType()))
                    {
                        continue;
                    }

                    //its a persistent type, with it's own table, map as a foreign key with one or more columns for the primary key
                    if (IsMapped(returnType))
                    {
                        //we asume this datatype is already mapped along with it's primery key
                        DataType returnDataType = returnType;

                        ForeignKey foreignKey = new ForeignKey();
                        foreignKey.Table       = dtype.Table;
                        foreignKey.RemoteTable = returnDataType.Table;
                        foreignKey.Name        = "FK_" + dtype.Name + "_" + memberInfo.Name + "_" + random.Next();

                        foreach (DataMember pk in returnDataType.PrimaryKey.ToList())
                        {
                            Column column = new Column();
                            column.Name         = memberInfo.Name + "_" + pk.Member.Expression.Replace('.', '_');
                            column.Table        = dtype.Table;
                            column.IsPrimaryKey = false;
                            column.IsNullable   = !RequiredValidator.IsRequired(memberInfo);
                            column.DbType       = DbTypeMapper.Parse(pk.Member.ReturnType);

                            if (column.IsString)
                            {
                                column.Length = StringLengthValidator.GetMaxLength(pk.Member.FinalMemberInfo);
                            }

                            dtype.Table.Columns.Add(column);
                            foreignKey.Columns.Add(new Tuple <Column, Column>(column, pk.Column));

                            //create datamember
                            dtype.AddMember(memberInfo.Name + "." + pk.Member, column);
                        }

                        dtype.Table.ForeignKeys.Add(foreignKey);
                    }
                    //just map as a atomic value
                    else
                    {
                        Column column = new Column();
                        column.Name         = memberInfo.Name;
                        column.Table        = dtype.Table;
                        column.IsNullable   = !RequiredValidator.IsRequired(memberInfo);
                        column.IsPrimaryKey = false;

                        //create datamember
                        DataMember dmember = dtype.AddMember(memberInfo.Name, column);

                        //is this a regular atomic value?
                        if (DbTypeMapper.DbTypeMap.ContainsValue(returnType) && returnType != typeof(object))
                        {
                            column.DbType = DbTypeMapper.Parse(returnType);
                        }
                        else if (returnType.GetTypeInfo().IsEnum)
                        {
                            column.DbType = DbType.Int32;
                        }
                        //this is an non-atomic object, but its not mapped as a DataType, so we serialize it as json
                        else
                        {
                            column.DbType     = DbType.String;
                            dmember.Converter = new Conversions.Json <object>();
                        }

                        if (column.IsString)
                        {
                            column.Length = Data.Validation.StringLengthValidator.GetMaxLength(memberInfo);
                        }

                        dtype.Table.Columns.Add(column);
                    }
                }

                yield return(dtype);
            }
        }
Ejemplo n.º 19
0
 public async Task RequiredProperty() {
   await _emTask;
   
   var emp = new Employee();
   var vr = new RequiredValidator();
   var dp = emp.EntityAspect.EntityType.GetDataProperty("LastName");
   var vc = new ValidationContext(emp, dp, null);
   var ve = vr.Validate(vc);
   Assert.IsTrue(ve != null);
   Assert.IsTrue(ve.Message.Contains("LastName") && ve.Message.Contains("required"));
   Assert.IsTrue(ve.Context.Entity == emp);
   Assert.IsTrue(ve.Validator == vr);
   Assert.IsTrue(ve.Key != null);
 }
Ejemplo n.º 20
0
    public async Task ChangeMessageBaseAndAssembly() {
      await _emTask;

      var emp = new Employee();
      var vr = new RequiredValidator().WithMessage("Model_Northwind_NetClient.CustomMessages2", typeof(Employee).Assembly);
      var dp = emp.EntityAspect.EntityType.GetDataProperty("LastName");
      var vc = new ValidationContext(emp, null, dp);
      var ve = vr.Validate(vc);
      Assert.IsTrue(ve != null);
      Assert.IsTrue(ve.Message.Contains("LastName") && ve.Message.Contains("required") && ve.Message.Contains("CUSTOM 2"));
      Assert.IsTrue(ve.Context.Instance == emp);
      Assert.IsTrue(ve.Validator == vr);
      Assert.IsTrue(ve.Key != null);
    }
Ejemplo n.º 21
0
 public void WithZeroNumber()
 {
     RequiredValidator validator = new RequiredValidator("0", null);
     IValidationErrors errors = new ValidationErrors();
     Assert.IsFalse(validator.Validate(null, errors));
 }
Ejemplo n.º 22
0
 public void WithKosherChar()
 {
     RequiredValidator validator = new RequiredValidator();
     validator.Test = Expression.Parse("'xyz'.ToCharArray()[1]");
     IValidationErrors errors = new ValidationErrors();
     Assert.IsTrue(validator.Validate(null, errors));
 }
Ejemplo n.º 23
0
        public void WhenValidatorIsNotEvaluatedBecauseWhenExpressionReturnsFalse()
        {
            RequiredValidator validator = new RequiredValidator("DateTime.MinValue", "false");
            IValidationErrors errors = new ValidationErrors();

            bool valid = validator.Validate(new object(), null, errors);

            Assert.IsTrue(valid, "Validation should succeed when required validator is not evaluated.");
            Assert.AreEqual(0, errors.GetErrors("errors").Count);
        }
Ejemplo n.º 24
0
 public void WithWhitespaceChar()
 {
     RequiredValidator validator = new RequiredValidator();
     validator.Test = Expression.Parse("' '.ToCharArray()[0]");
     IValidationErrors errors = new ValidationErrors();
     Assert.IsFalse(validator.Validate(null, errors));
 }
Ejemplo n.º 25
0
 public void WithKosherDouble()
 {
     RequiredValidator validator = new RequiredValidator("5.25D", null);
     IValidationErrors errors = new ValidationErrors();
     Assert.IsTrue(validator.Validate(null, errors));
 }
Ejemplo n.º 26
0
 public void WithKosherFloat()
 {
     RequiredValidator validator = new RequiredValidator(Expression.Parse("5.25F"), null);
     IValidationErrors errors = new ValidationErrors();
     Assert.IsTrue(validator.Validate(null, errors));
 }
Ejemplo n.º 27
0
 public void WithMaxDate()
 {
     RequiredValidator validator = new RequiredValidator();
     validator.Test = Expression.Parse("DateTime.MaxValue");
     IValidationErrors errors = new ValidationErrors();
     Assert.IsFalse(validator.Validate(null, errors));
 }
Ejemplo n.º 28
0
 public void WithPositiveNumber()
 {
     RequiredValidator validator = new RequiredValidator(Expression.Parse("100"), null);
     IValidationErrors errors = new ValidationErrors();
     Assert.IsTrue(validator.Validate(null, errors));
 }
Ejemplo n.º 29
0
        /// <summary>
        /// Copies all values entered by the user to a DavaValueInstance collection
        /// </summary>
        /// <param name="members">Collection where values will be copied to</param>
        public Filter GetFilter(MemberInfo member)
        {
            //validate arguments
            if (member == null)
            {
                throw new ArgumentNullException(nameof(member));
            }

            //filters
            Filter filter = null;

            DataType dtype      = member.DeclaringType;
            Type     returnType = MemberExpression.GetReturnType(member);

            //is this a single value member? (not a foreign key?)
            if (dtype.IsMapped(member.Name))
            {
                DataMember dmember = dtype[member.Name];

                #region Range filter

                //if it's a datetime or a numeric field, create range filter
                if (returnType.Equals(typeof(DateTime)) || returnType.IsNumeric())
                {
                    //realted fields
                    FormField fieldMin = null, fieldMax = null;

                    //search corresponding field for this DataValueInstance
                    foreach (FormField f in Fields)
                    {
                        if (f.Name == member.Name + "_0")
                        {
                            fieldMin = f;
                        }
                        if (f.Name == member.Name + "_1")
                        {
                            fieldMax = f;
                        }
                    }

                    //if no controls where found, return no filter
                    if (fieldMin == null && fieldMax == null)
                    {
                        return(null);
                    }

                    //if no value was set, return no filter
                    if (!RequiredValidator.HasValue(fieldMin.Value) && !RequiredValidator.HasValue(fieldMax.Value))
                    {
                        return(null);
                    }

                    //if both values are set, create range filter
                    if (RequiredValidator.HasValue(fieldMin.Value) && RequiredValidator.HasValue(fieldMax.Value))
                    {
                        filter = new RangeFilter(dmember, (IComparable)fieldMin.Value, (IComparable)fieldMax.Value);
                    }

                    //only min value is defined
                    else if (RequiredValidator.HasValue(fieldMin.Value))
                    {
                        filter = new ValueCompareFilter(dmember, (IComparable)fieldMin.Value, CompareOperator.GreaterThanEqual);
                    }

                    //only max value is defined
                    else if (RequiredValidator.HasValue(fieldMax.Value))
                    {
                        filter = new ValueCompareFilter(dmember, (IComparable)fieldMax.Value, CompareOperator.LessThanEqual);
                    }
                }

                #endregion

                #region Single value filter

                //create single value filter
                else
                {
                    //realted fields
                    FormField field = Fields.Where(f => f.Name == member.Name).SingleOrDefault();

                    //if field not found, return no filter
                    if (field == null)
                    {
                        return(null);
                    }

                    //if no value was set, return no filter
                    if (!RequiredValidator.HasValue(field.Value))
                    {
                        return(null);
                    }

                    //if its a string, make a LIKE filter
                    else if (field.ValueType.Equals(typeof(string)))
                    {
                        filter = new LikeFilter(dmember, "%" + field.Value + "%");
                    }

                    //otherwise create a compare filter
                    else
                    {
                        filter = new ValueCompareFilter(dmember, (IComparable)field.Value, CompareOperator.Equal);
                    }
                }

                #endregion
            }
            //this is a foreign key
            else if (DataType.IsMapped(returnType) && dtype.IsForeignKey(member))
            {
                //realted fields
                FormField field = Fields.Where(f => f.Name == member.Name).SingleOrDefault();

                //if field not found, return no filter
                if (field == null)
                {
                    return(null);
                }

                //if no value was set, return no filter
                if (!RequiredValidator.HasValue(field.Value))
                {
                    return(null);
                }

                filter = new ForeignKeyFilter(dtype, member, field.Value);
            }

            return(filter);
        }
Ejemplo n.º 30
0
    public async Task InternValidators() {
      var em1 = await TestFns.NewEm(_serviceName);

      var vr2 = new RequiredValidator().Intern();
      var vr3 = new RequiredValidator().Intern();
      Assert.IsTrue(vr2 == vr3);
      Assert.IsTrue(vr2.Equals(vr3));

      var mlVr2 = new MaxLengthValidator(17).Intern();
      var mlVr3 = new MaxLengthValidator(17).Intern();
      Assert.IsTrue(mlVr2 == mlVr3);
      Assert.IsTrue(mlVr2.Equals(mlVr3));

      var slVr2 = new StringLengthValidator(3, 12).Intern();
      var slVr3 = new StringLengthValidator(3, 12).Intern();
      Assert.IsTrue(slVr2 == slVr3);
      Assert.IsTrue(slVr2.Equals(slVr3));

    }
Ejemplo n.º 31
0
    public async Task LocalizedValidationMessage() {
      await _emTask;

      var vr = new RequiredValidator();
      var mt = vr.LocalizedMessage.Message;
      Assert.IsTrue(!String.IsNullOrEmpty(mt));
      Assert.IsTrue(vr.LocalizedMessage.IsLocalized);
    }
Ejemplo n.º 32
0
    public async Task ChangeMessageString() {
      var em1 = await TestFns.NewEm(_serviceName);

      var emp = new Employee();
      var vr = new RequiredValidator().WithMessage("{0} is bad");
      var dp = emp.EntityAspect.EntityType.GetDataProperty("LastName");
      var vc = new ValidationContext(emp, dp, null);
      var ve = vr.Validate(vc);
      Assert.IsTrue(ve != null);
      Assert.IsTrue(ve.Message.Contains("LastName") && ve.Message.Contains("bad"));
      Assert.IsTrue(ve.Context.Entity == emp);
      Assert.IsTrue(ve.Validator == vr);
      Assert.IsTrue(ve.Key != null);
    }
Ejemplo n.º 33
0
        public void CreateValidationMetadata(ValidationMetadataProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (context.Key.ContainerType != null && !context.Key.ContainerType.IsValueType)
            {
                var viewConfig = ServiceLocator.GetViewConfigure(context.Key.ContainerType);

                if (viewConfig != null && context.Key.Name.IsNotNullAndWhiteSpace())
                {
                    var descriptor = viewConfig.GetViewPortDescriptor(context.Key.Name);
                    if (descriptor != null)
                    {
                        descriptor.Validator.Each(v =>
                        {
                            if (v.DisplayName == null)
                            {
                                v.DisplayName = () => descriptor.DisplayName;
                            }
                            string encodeError = Convert.ToBase64String(JsonConvert.SerializeObject(new Mapping(v.Name, v.Property)).ToByte());
                            if (v is RangeValidator)
                            {
                                RangeValidator valid = (RangeValidator)v;
                                RangeAttribute range = new RangeAttribute(valid.Min, valid.Max);
                                range.ErrorMessage   = encodeError;

                                context.ValidationMetadata.ValidatorMetadata.Add(range);
                            }
                            else if (v is RegularValidator)
                            {
                                RegularValidator valid             = (RegularValidator)v;
                                RegularExpressionAttribute regular = new RegularExpressionAttribute(valid.Expression);
                                regular.ErrorMessage = encodeError;
                                context.ValidationMetadata.ValidatorMetadata.Add(regular);
                            }
                            else if (v is RemoteValidator)
                            {
                                RemoteValidator valid  = (RemoteValidator)v;
                                RemoteAttribute remote = new RemoteAttribute(valid.Action, valid.Controller, valid.Area);
                                remote.ErrorMessage    = encodeError;
                                context.ValidationMetadata.ValidatorMetadata.Add(remote);
                            }
                            else if (v is RequiredValidator)
                            {
                                RequiredValidator valid    = (RequiredValidator)v;
                                RequiredAttribute required = new RequiredAttribute();
                                required.ErrorMessage      = encodeError;
                                context.ValidationMetadata.ValidatorMetadata.Add(required);
                            }
                            else if (v is StringLengthValidator)
                            {
                                StringLengthValidator valid        = (StringLengthValidator)v;
                                StringLengthAttribute stringLength = new StringLengthAttribute(valid.Max);
                                stringLength.ErrorMessage          = encodeError;
                                context.ValidationMetadata.ValidatorMetadata.Add(stringLength);
                            }
                        });
                    }
                }
            }
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Creates a field for a DataMember
        /// </summary>
        public FormField AddField(MemberInfo member)
        {
            //if there's no values defined, exit
            if (member == null)
            {
                throw new ArgumentNullException(nameof(member));
            }

            //field
            FormField field;
            Type      returnType = MemberExpression.GetReturnType(member);

            //String
            if (returnType.Equals(typeof(string)))
            {
                field = new StringField();

                //set max lenght, if defined
                int maxLenght = (int)StringLengthValidator.GetMaxLength(member);

                if (maxLenght == 0)
                {
                    field.TableWide = true;
                }
                else
                {
                    ((StringField)field).MaxLenght = maxLenght;
                }

                //set regular expression validation, if defined
                var regex = member.CustomAttributes.Where(att => att.AttributeType.Equals(typeof(RegexValidator))).SingleOrDefault();

                if (regex != null)
                {
                    ((StringField)field).RegularExpression = (string)regex.ConstructorArguments[0].Value;
                }
            }

            //DataType
            else if (returnType.Equals(typeof(DataType)))
            {
                field = new DataTypeField();
            }

            //otherwise delegate to the static method to create the field from the return type
            else
            {
                field = CreateField(returnType);
            }

            field.Name                = member.Name;
            field.Container           = this;
            field.Required            = RequiredValidator.IsRequired(member);
            field.CaptionControl.Text = Translator.Translate(member);
            //if (member.Column.IsPrimaryKey) field.SortOrder = 0;

            //add to fields collection
            Fields.Add(field);

            return(field);
        }
Ejemplo n.º 35
0
        public static IRuleBuilder <T> Required <T>(this IRuleBuilder <T> ruleBuilder) where T : class
        {
            ruleBuilder.AddRule(RequiredValidator <T> .New(ruleBuilder));

            return(ruleBuilder);
        }
Ejemplo n.º 36
0
 public void WithKosherString()
 {
     RequiredValidator validator = new RequiredValidator();
     validator.Test = Expression.Parse("'some non-empty string'");
     IValidationErrors errors = new ValidationErrors();
     Assert.IsTrue(validator.Validate(null, errors));
 }
Ejemplo n.º 37
0
        public async Task CustomizeMessageString()
        {
            var manager = new EntityManager(_serviceName); // new empty EntityManager
            await manager.FetchMetadata(); // required before creating a new entity

            var customer = new Customer();
            var vr = new RequiredValidator().WithMessage("Dude! The {0} is really required ... seriously ... as in mandatory");

            var companyNameProp = customer.EntityAspect.EntityType.GetDataProperty("CompanyName");
            var context = new ValidationContext(customer, companyNameProp, null);
            var error = vr.Validate(context);
            Assert.IsTrue(error.Message.Contains("CompanyName") && error.Message.Contains("Dude"), "should be an error containing 'Dude'");
        }
Ejemplo n.º 38
0
 public void WithKosherDate()
 {
     RequiredValidator validator = new RequiredValidator("DateTime.Today", null);
     IValidationErrors errors = new ValidationErrors();
     Assert.IsTrue(validator.Validate(null, errors));
 }
Ejemplo n.º 39
0
 public void int32_should_be_nonzero_for_required()
 {
     Assert.True(RequiredValidator.IsValidImpl(420));
     Assert.False(RequiredValidator.IsValidImpl(0));
 }
        public void Validate_ReturnValue_AreEqual(string value, bool isValid)
        {
            RequiredValidator validator = new RequiredValidator("", value);

            Assert.AreEqual(validator.Validate(), isValid);
        }
 private Validator BuildValidator(Dictionary<string, string> data) {
   var name = data["name"];
   Validator v;
   if (name == "required") v = new RequiredValidator();
   else if (name == "maxLength") v = new MaxLengthValidator();
   else v = new Validator();
   v.name = name;
   if (data.Count > 1) {
     v.properties = data;
   }
   return v;
 }
Ejemplo n.º 42
0
    public async Task ChangeMessageResourceType() {
      await _emTask;

      var emp = new Employee();
      var vr = new RequiredValidator().WithMessage(typeof(Model_Northwind_NetClient.CustomMessages1));
      var dp = emp.EntityAspect.EntityType.GetDataProperty("LastName");
      var vc = new ValidationContext(emp, dp, null);
      var ve = vr.Validate(vc);
      Assert.IsTrue(ve != null);
      Assert.IsTrue(ve.Message.Contains("LastName") && ve.Message.Contains("required") && ve.Message.Contains("CUSTOM 1"));
      Assert.IsTrue(ve.Context.Entity == emp);
      Assert.IsTrue(ve.Validator == vr);
      Assert.IsTrue(ve.Key != null);
    }
Ejemplo n.º 43
0
 public static bool Required(object input)
 {
     return(RequiredValidator.IsValidImpl(input));
 }
Ejemplo n.º 44
0
 public void WithMinDate()
 {
     RequiredValidator validator = new RequiredValidator(Expression.Parse("DateTime.MinValue"), null);
     IValidationErrors errors = new ValidationErrors();
     Assert.IsFalse(validator.Validate(null, errors));
 }
Ejemplo n.º 45
0
    public async Task LocalizedValidationMessage() {
      var em1 = await TestFns.NewEm(_serviceName);

      var vr = new RequiredValidator();
      var mt = vr.LocalizedMessage.Message;
      Assert.IsTrue(!String.IsNullOrEmpty(mt));
      Assert.IsTrue(vr.LocalizedMessage.IsLocalized);
    }
Ejemplo n.º 46
0
 public void WithEmptyString()
 {
     RequiredValidator validator = new RequiredValidator("''", null);
     IValidationErrors errors = new ValidationErrors();
     Assert.IsFalse(validator.Validate(null, errors));
 }
Ejemplo n.º 47
0
    public async Task ChangeMessageBaseAndAssembly() {
      var em1 = await TestFns.NewEm(_serviceName);

      var emp = new Employee();
      var vr = new RequiredValidator().WithMessage("Model.NorthwindIB.CustomMessages2", typeof (Employee).Assembly);
      var dp = emp.EntityAspect.EntityType.GetDataProperty("LastName");
      var vc = new ValidationContext(emp, dp, null);
      var ve = vr.Validate(vc);
      Assert.IsTrue(ve != null);
      Assert.IsTrue(ve.Message.Contains("LastName") && ve.Message.Contains("required") &&
                    ve.Message.Contains("CUSTOM 2"));
      Assert.IsTrue(ve.Context.Entity == emp);
      Assert.IsTrue(ve.Validator == vr);
      Assert.IsTrue(ve.Key != null);
    }
Ejemplo n.º 48
0
 public void WithWhitespaceOnlyString()
 {
     RequiredValidator validator = new RequiredValidator(Expression.Parse("'    '"), null);
     IValidationErrors errors = new ValidationErrors();
     Assert.IsFalse(validator.Validate(null, errors));
 }