예제 #1
0
    public void GetsValidationMessagesFromDataAnnotations()
    {
        // Arrange
        var model = new TestModel {
            IntFrom1To100 = 101
        };
        var editContext = new EditContext(model);

        editContext.EnableDataAnnotationsValidation();

        // Act
        var isValid = editContext.Validate();

        // Assert
        Assert.False(isValid);

        Assert.Equal(new string[]
        {
            "RequiredString:required",
            "IntFrom1To100:range"
        },
                     editContext.GetValidationMessages());

        Assert.Equal(new string[] { "RequiredString:required" },
                     editContext.GetValidationMessages(editContext.Field(nameof(TestModel.RequiredString))));

        // This shows we're including non-[Required] properties in the validation results, i.e,
        // that we're correctly passing "validateAllProperties: true" to DataAnnotations
        Assert.Equal(new string[] { "IntFrom1To100:range" },
                     editContext.GetValidationMessages(editContext.Field(nameof(TestModel.IntFrom1To100))));
    }
예제 #2
0
        private async ValueTask OnFinish(EditContext editContext)
        {
            var messageStore = new ValidationMessageStore(editContext);

            //verify credential
            try
            {
                var client  = AppRuntimeContext.Current.Resolve <ExamAssistantClient>();
                var isValid = await client.ValidateFirebaseSettingAsync(Options.To <FirebaseSettingDto>());

                if (!isValid)
                {
                    messageStore.Add(editContext.Field("JsonCredentials"), $"Failed to validate the provided credential. Please check again.");
                    editContext.NotifyValidationStateChanged();
                    return;
                }
                //var examService = new ExamService(Options.ProjectId, Options.JsonCredentials);
            }
            catch (System.Exception ex)
            {
                Logger.Error("Failed to valid the JsonCredentials provided", ex);
                messageStore.Add(editContext.Field("JsonCredentials"), $"Failed to validate the provided credential. Please check again.");
                editContext.NotifyValidationStateChanged();
                return;
            }
            await((DrawerRef <bool>)base.FeedbackRef)?.CloseAsync(true);
            // await this.OkCancelRefWithResult.OkAsync(true);
            // await this.CloseFeedbackAsync();
            // await this.CloseAsync(true);
        }
예제 #3
0
        private async Task ValidatorByAlias(EditContext editContext)
        {
            authorEntity.Alias = authorEntity.Alias.Trim();

            if (StringUtils.IsEqual(authorEntity.Alias, "."))
            {
                // authorEntity.Alias = ".";
                return;
            }

            if (StringUtils.IsEqual(authorEntity.Name, authorEntity.Alias))
            {
                messageStore.Add(editContext.Field("Alias"), "映射别名不能与名称相等");
                return;
            }

            if (StringUtils.IsNotEqual(authorEntity.Alias, "."))
            {
                BAuthorEntity other = await this.authorService.FindByNameAsync(authorEntity.Alias);

                // 如果映射的数据不存在,或不合法,或不是主数据
                if (other == null || !other.Valid || StringUtils.IsNotEqual(other.Alias, "."))
                {
                    messageStore.Add(editContext.Field("Alias"), "映射别名未找到主数据、或匹配的主数据不合法");
                }
            }
        }
    public void LookingUpModel_ThatOverridesGetHashCodeAndEquals_Works()
    {
        // Test for https://github.com/aspnet/AspNetCore/issues/18069
        // Arrange
        var model       = new EquatableModel();
        var editContext = new EditContext(model);

        editContext.NotifyFieldChanged(editContext.Field(nameof(EquatableModel.Property)));

        model.Property = "new value";

        Assert.True(editContext.IsModified(editContext.Field(nameof(EquatableModel.Property))));
    }
예제 #5
0
        private void OnValidationRequested(object?sender, ValidationRequestedEventArgs e)
        {
            var validationContext = new ValidationContext(_editContext.Model, _serviceProvider, items: null);
            var validationResults = new List <ValidationResult>();

            Validator.TryValidateObject(_editContext.Model, validationContext, validationResults, true);

            // Transfer results to the ValidationMessageStore
            _messages.Clear();
            foreach (var validationResult in validationResults)
            {
                if (validationResult == null)
                {
                    continue;
                }

                var hasMemberNames = false;
                foreach (var memberName in validationResult.MemberNames)
                {
                    hasMemberNames = true;
                    _messages.Add(_editContext.Field(memberName), validationResult.ErrorMessage !);
                }

                if (!hasMemberNames)
                {
                    _messages.Add(new FieldIdentifier(_editContext.Model, fieldName: string.Empty), validationResult.ErrorMessage !);
                }
            }

            _editContext.NotifyValidationStateChanged();
        }
예제 #6
0
 private void EditContext_OnFieldChanged(object sender, FieldChangedEventArgs e)
 {
     Console.WriteLine($"EditContext_OnFieldChanged - {e.FieldIdentifier.FieldName}");
     if (e.FieldIdentifier.FieldName == nameof(Model.Date))
     {
         EditContext.NotifyFieldChanged(EditContext.Field(nameof(Model.Summary)));
     }
 }
    public void CanClearAllModifications()
    {
        // Arrange
        var editContext = new EditContext(new object());
        var field1      = editContext.Field("field1");
        var field2      = editContext.Field("field2");

        editContext.NotifyFieldChanged(field1);
        editContext.NotifyFieldChanged(field2);

        // Act
        editContext.MarkAsUnmodified();

        // Assert
        Assert.False(editContext.IsModified());
        Assert.False(editContext.IsModified(field1));
        Assert.False(editContext.IsModified(field2));
    }
    public void TracksFieldsAsModifiedWhenValueChanged()
    {
        // Arrange
        var editContext       = new EditContext(new object());
        var fieldOnThisModel1 = editContext.Field("field1");
        var fieldOnThisModel2 = editContext.Field("field2");
        var fieldOnOtherModel = new FieldIdentifier(new object(), "field on other model");

        // Act
        editContext.NotifyFieldChanged(fieldOnThisModel1);
        editContext.NotifyFieldChanged(fieldOnOtherModel);

        // Assert
        Assert.True(editContext.IsModified());
        Assert.True(editContext.IsModified(fieldOnThisModel1));
        Assert.False(editContext.IsModified(fieldOnThisModel2));
        Assert.True(editContext.IsModified(fieldOnOtherModel));
    }
예제 #9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="editContext"></param>
        /// <param name="field">The field name that was changed in the process, typically specified using "nameof(YourObject.YourProperty").</param>
        public static void NotifyFieldChanged(this EditContext editContext, string field)
        {
            if (editContext == null || string.IsNullOrWhiteSpace(field))
            {
                return;
            }

            editContext.NotifyFieldChanged(editContext.Field(field));
        }
예제 #10
0
    public void IgnoresFieldChangesThatDoNotCorrespondToAValidatableProperty(string fieldName)
    {
        // Arrange
        var editContext = new EditContext(new TestModel());

        editContext.EnableDataAnnotationsValidation();
        var onValidationStateChangedCount = 0;

        editContext.OnValidationStateChanged += (sender, eventArgs) => onValidationStateChangedCount++;

        // Act/Assert: Ignores field changes that don't correspond to a validatable property
        editContext.NotifyFieldChanged(editContext.Field(fieldName));
        Assert.Equal(0, onValidationStateChangedCount);

        // Act/Assert: For sanity, observe that we would have validated if it was a validatable property
        editContext.NotifyFieldChanged(editContext.Field(nameof(TestModel.RequiredString)));
        Assert.Equal(1, onValidationStateChangedCount);
    }
예제 #11
0
        private async Task ValidatorByName(EditContext editContext)
        {
            BAuthorEntity other = await this.authorService.FindByNameAsync(authorEntity.Name);

            if (other != null && StringUtils.IsNotEqual(authorEntity.Id, other.Id))
            {
                messageStore.Add(editContext.Field("Name"), "名字重复了");
            }
        }
예제 #12
0
        private async Task ValidatorByPassword(EditContext editContext)
        {
            if (StringUtils.IsNotEqual(userEntity.PasswordNew, userEntity.PasswordConfirm))
            {
                messageStore.Add(editContext.Field(nameof(SUserEntity.PasswordConfirm)), "确认密码不相同");
            }

            await Task.CompletedTask;
        }
예제 #13
0
    private void AddIfNoOtherErrors(string fieldName, string message)
    {
        var field = _editContext.Field(fieldName);

        if (!_editContext.GetValidationMessages(field).Any())
        {
            _validationMessages.Add(field, message);
        }
    }
예제 #14
0
        private async Task ValidatorByName(EditContext editContext)
        {
            BCryptoEntity other = await this.cryptoService.FindBySecretAsync(cryptoEntity.Secret);

            if (other != null && StringUtils.IsNotEqual(cryptoEntity.Id, other.Id))
            {
                messageStore.Add(editContext.Field(nameof(BCryptoEntity.Secret)), "密码重复了");
            }
        }
예제 #15
0
        public void DisplayErrors(EditContext context)
        {
            var messageStore = new ValidationMessageStore(context);

            foreach (var err in this.ValidationResult.Errors)
            {
                messageStore.Add(context.Field(err.PropertyName), err.ErrorMessage);
            }
            context.NotifyValidationStateChanged();
        }
예제 #16
0
        public void AddErrors(ValidationMessageStore msgStore, EditContext editContext)
        {
            var errors = JsonConvert.DeserializeObject <List <string> >(RawPayload);

            foreach (var error in errors)
            {
                msgStore.Add(editContext.Field(string.Empty), error);
            }
            editContext.NotifyValidationStateChanged();
        }
    public void CanConstructFieldIdentifiersForRootModel()
    {
        // Arrange/Act
        var model           = new object();
        var editContext     = new EditContext(model);
        var fieldIdentifier = editContext.Field("testFieldName");

        // Assert
        Assert.Same(model, fieldIdentifier.Model);
        Assert.Equal("testFieldName", fieldIdentifier.FieldName);
    }
예제 #18
0
        private async Task ValidatorByName(EditContext editContext)
        {
            BTagEntity other = await this.tagService.FindByNameAsync(tagEntity.Name);

            if (other != null && StringUtils.IsNotEqual(tagEntity.Id, other.Id))
            {
                // _times += 1; 跟踪同一个页面的验证次数
                // messageStore.Add(editContext.Field("Name"), "名字重复了 [第" + _times + "次验证]");
                messageStore.Add(editContext.Field("Name"), "名字重复了");
                // StateHasChanged();
            }
        }
예제 #19
0
        private async Task ValidatorByUsername(EditContext editContext)
        {
            // 强制设置为小写
            userEntity.Username = userEntity.Username.Trim().ToLower();

            SUserEntity other = await this.userService.FindByUsernameAsync(userEntity.Username);

            if (other != null && StringUtils.IsNotEqual(other.Id, userEntity.Id))
            {
                messageStore.Add(editContext.Field(nameof(SUserEntity.Username)), "用户名不合法");
            }
        }
예제 #20
0
    private static void ValidateModel(EditContext editContext, ValidationMessageStore messages)
    {
        var validator         = GetValidatorForModel(editContext.Model);
        var validationResults = validator.Validate(editContext.Model);

        messages.Clear();
        foreach (var validationResult in validationResults.Errors)
        {
            messages.Add(editContext.Field(validationResult.PropertyName), validationResult.ErrorMessage);
        }
        editContext.NotifyValidationStateChanged();
    }
    public void CanClearIndividualModifications()
    {
        // Arrange
        var editContext               = new EditContext(new object());
        var fieldThatWasModified      = editContext.Field("field1");
        var fieldThatRemainsModified  = editContext.Field("field2");
        var fieldThatWasNeverModified = editContext.Field("field that was never modified");

        editContext.NotifyFieldChanged(fieldThatWasModified);
        editContext.NotifyFieldChanged(fieldThatRemainsModified);

        // Act
        editContext.MarkAsUnmodified(fieldThatWasModified);
        editContext.MarkAsUnmodified(fieldThatWasNeverModified);

        // Assert
        Assert.True(editContext.IsModified());
        Assert.False(editContext.IsModified(fieldThatWasModified));
        Assert.True(editContext.IsModified(fieldThatRemainsModified));
        Assert.False(editContext.IsModified(fieldThatWasNeverModified));
    }
예제 #22
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="editContext"></param>
        /// <param name="fields">An inline list of fields that were changed in the process, typically specified using "nameof(YourObject.YourProperty").</param>
        public static void NotifyFieldsChanged(this EditContext editContext, params string[] fields)
        {
            if (editContext == null || fields == null)
            {
                return;
            }

            foreach (var field in fields)
            {
                editContext.NotifyFieldChanged(editContext.Field(field));
            }
        }
예제 #23
0
        private async ValueTask OnFinish(EditContext editContext)
        {
            var messageStore = new ValidationMessageStore(editContext);

            if (!IsValidEmail(Options.Email))
            {
                messageStore.Add(editContext.Field("Email"), "The email address is not valid.");
                editContext.NotifyValidationStateChanged();
                return;
            }

            var hasNumber        = new Regex(@"[0-9]+");
            var hasUpperChar     = new Regex(@"[A-Z]+");
            var hasMinimum8Chars = new Regex(@".{8,}");

            if (!hasNumber.IsMatch(Options.Password))
            {
                messageStore.Add(editContext.Field("Password"), "The password must contain at least one number.");
                editContext.NotifyValidationStateChanged();
                return;
            }
            if (!hasUpperChar.IsMatch(Options.Password))
            {
                messageStore.Add(editContext.Field("Password"), "The password must contain at least one upper-case letter.");
                editContext.NotifyValidationStateChanged();
                return;
            }
            if (!hasMinimum8Chars.IsMatch(Options.Password))
            {
                messageStore.Add(editContext.Field("Password"), "The password must contain at least 8 characters.");
                editContext.NotifyValidationStateChanged();
                return;
            }


            await((DrawerRef <bool>)base.FeedbackRef)?.CloseAsync(true);
            // await this.OkCancelRefWithResult.OkAsync(true);
            //  await this.CloseFeedbackAsync();
            // await this.CloseAsync(true);
        }
예제 #24
0
        //проверка модели вызывается OnValidationRequested
        private static void ValidateModel(EditContext editContext, ValidationMessageStore messages)
        {
            var validator = GetValidatorForModel(editContext.Model);
            var validationResults = validator.Validate(editContext.Model);

            messages.Clear();//очищай хранилища
            foreach (var validationResult in validationResults.Errors)
            {
                messages.Add(editContext.Field(validationResult.PropertyName), validationResult.ErrorMessage);
            }

            editContext.NotifyValidationStateChanged();// сообщает editContext-у что произовли изменения
        }
예제 #25
0
        private void ValidateField(IMPropertyField pField)
        {
            var propInfo = GetPropertyInfo(pField);

            PropertyInfo oriPropInfo = null;

            var isExpando = typeof(IDictionary <string, object>).IsAssignableFrom(ModelType);

            if (!isExpando)
            {
                oriPropInfo = ModelType.GetProperty(propInfo.Name);
            }

            var fieldIdentifier = mEditContext.Field(propInfo.Name);

            bool messagesCleared = false;

            //if attribute is passed via field and not handled by DataAnnotationsValidator
            foreach (ValidationAttribute attribute in propInfo.GetAttributes().Where(a => a is ValidationAttribute))
            {
                if ((oriPropInfo != null && oriPropInfo.GetCustomAttribute(attribute.GetType()) == null) || isExpando)
                {
                    if (!messagesCleared)
                    {
                        mValidationMessageStore.Clear(fieldIdentifier);
                        messagesCleared = true;
                    }

                    var value = propInfo.GetValue(Model);

                    if (!attribute.IsValid(value))
                    {
                        string displayname = propInfo.GetDisplayName(L, false);
                        var    msg         = attribute.FormatErrorMessage(displayname);
                        mValidationMessageStore.Add(fieldIdentifier, msg);
                    }
                }
            }
        }
        private async Task ValidateModel(
            EditContext editContext,
            ValidationMessageStore messages,
            IServiceProvider serviceProvider)
        {
            if (editContext == null)
            {
                throw new ArgumentNullException(nameof(editContext));
            }
            if (messages == null)
            {
                throw new ArgumentNullException(nameof(messages));
            }
            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }
            if (editContext.Model == null)
            {
                throw new NullReferenceException($"{nameof(editContext)}.{nameof(editContext.Model)}");
            }

            messages.Clear();
            editContext.NotifyValidationStateChanged();

            IEnumerable <IValidator> validators = GetValidatorsForObject(editContext.Model, serviceProvider);

            var validationContext = new ValidationContext <object>(editContext.Model);

            var validationResults = new List <ValidationResult>();

            foreach (IValidator validator in validators)
            {
                var validationResult = await validator.ValidateAsync(validationContext);

                validationResults.Add(validationResult);
            }

            IEnumerable <ValidationFailure> validationFailures = validationResults.SelectMany(x => x.Errors);

            foreach (var validationError in validationFailures)
            {
                messages.Add(editContext.Field(validationError.PropertyName), validationError.ErrorMessage);
            }

            editContext.NotifyValidationStateChanged();
        }
예제 #27
0
        private static async void ValidateModel(EditContext editContext, ValidationMessageStore messages, IServiceProvider serviceProvider, IValidator validator = null)
        {
            if (validator == null)
            {
                validator = GetValidatorForModel(serviceProvider, editContext.Model);
            }

            var validationResults = await validator.ValidateAsync(editContext.Model);

            messages.Clear();
            foreach (var validationResult in validationResults.Errors)
            {
                messages.Add(editContext.Field(validationResult.PropertyName), validationResult.ErrorMessage);
            }

            editContext.NotifyValidationStateChanged();
        }
예제 #28
0
        private void ValidateProperty(EditContext ectx, DataProperty p)
        {
            var vstore = validationStores[ectx];
            var row    = ectx.Model as DataRow;

            p.Validate(row);
            var errors = p.GetValidationErrors(row);

            if (errors?.Errors != null)
            {
                var fld = ectx.Field(p.Name);
                foreach (var error in errors.Errors)
                {
                    vstore.Add(fld, error.Message);
                }
            }
        }
예제 #29
0
        /// <summary>
        /// Validate the whole form and trigger client UI update.
        /// </summary>
        /// <param name="editContext"></param>
        /// <param name="messages"></param>
        private void ValidateModel(EditContext editContext, ValidationMessageStore messages)
        {
            // ATTENTION: DO NOT USE Async Void + ValidateAsync
            // Explanation: Blazor UI will get VERY BUGGY for some reason if you do that. (Field CSS lagged behind validation)
            var vctx = new ValidationContext <object>(editContext.Model);
            var validationResults = Validator.Validate(vctx);

            messages.Clear();

            foreach (var error in validationResults.Errors)
            {
                var fieldID = editContext.Field(error.PropertyName);
                messages.Add(fieldID, error.ErrorMessage);
            }

            editContext.NotifyValidationStateChanged();
        }
예제 #30
0
        private async Task ValidatorByParent(EditContext editContext)
        {
            if (StringUtils.IsBlank(functionEntity.Parent))
            {
                functionEntity.Parent = "0";
            }
            else if (StringUtils.IsEqual("0", functionEntity.Parent))
            {
                return;
            }

            SFunctionEntity other = await this.functionService.FindAsync(functionEntity.Parent);

            if (other == null)
            {
                messageStore.Add(editContext.Field("Parent"), "上级代码必须为[0]或未找到上级数据");
            }
        }