Exemple #1
0
        void IFormItem.AddControl <TValue>(AntInputComponentBase <TValue> control)
        {
            if (control.FieldIdentifier.Model == null)
            {
                throw new InvalidOperationException($"Please use @bind-Value in the control with generic type `{typeof(TValue)}`.");
            }

            this._control = control;

            CurrentEditContext.OnValidationStateChanged += (s, e) =>
            {
                control.ValidationMessages = CurrentEditContext.GetValidationMessages(control.FieldIdentifier).ToArray();
                this._isValid = !control.ValidationMessages.Any();

                StateHasChanged();
            };

            _formValidationMessages = builder =>
            {
                var i = 0;
                builder.OpenComponent <FormValidationMessage <TValue> >(i++);
                builder.AddAttribute(i++, "Control", control);
                builder.CloseComponent();
            };

            _propertyReflector = PropertyReflector.Create(control.ValueExpression);

            if (_propertyReflector.RequiredAttributes.Any())
            {
                _labelCls = $"{_prefixCls}-required";
            }
        }
        void IFormItem.AddControl <TValue>(AntInputComponentBase <TValue> control)
        {
            this._control = control;

            CurrentEditContext.OnValidationStateChanged += (s, e) =>
            {
                control.ValidationMessages = CurrentEditContext.GetValidationMessages(control.FieldIdentifier).ToArray();
                this._isValid = !control.ValidationMessages.Any();

                StateHasChanged();
            };

            _formValidationMessages = builder =>
            {
                var i = 0;
                builder.OpenComponent <FormValidationMessage <TValue> >(i++);
                builder.AddAttribute(i++, "Control", control);
                builder.CloseComponent();
            };

            if (control.FieldIdentifier.TryGetValidateProperty(out var propertyInfo))
            {
                var requiredAttribute = propertyInfo.GetCustomAttributes(typeof(RequiredAttribute), true);
                if (requiredAttribute.Length > 0)
                {
                    _labelCls = $"{_prefixCls}-required";
                }
            }
        }
 public void OnModelChanged()
 {
     if (validationRequested || !ValidateAfterTheFirstSubmit)
     {
         CurrentEditContext.Validate();
     }
 }
        protected async Task AddAsync()
        {
            _messageStore.Clear();
            var userId = await UserApiService.GetUserIdAsync(Username);

            var loggedInUserId = (await AuthenticationStateTask).LoggedInUserId();

            if (userId == loggedInUserId)
            {
                _messageStore.Add(CurrentEditContext.Field("Username"), "Adding yourself is not allowed.");
                CurrentEditContext.NotifyValidationStateChanged();
                return;
            }

            if (string.IsNullOrEmpty(userId))
            {
                _messageStore.Add(CurrentEditContext.Field("Username"), $"{Username} not found");
                CurrentEditContext.NotifyValidationStateChanged();
                return;
            }

            if (Members.Any(m => m[0] == userId))
            {
                _messageStore.Add(CurrentEditContext.Field("Username"), $"{Username} already added.");
                CurrentEditContext.NotifyValidationStateChanged();
                return;
            }

            Members.Add(new string[] { userId, Username });
            await OnUpdateUsers.InvokeAsync(Members);
        }
Exemple #5
0
        private void EventHandler(object sender, ValidationRequestedEventArgs eventArgs)
        {
            string name;

            if (ControlToValidate.Current.ValueExpression.Body is MemberExpression memberExpression)
            {
                name = memberExpression.Member.Name;
            }
            else
            {
                throw new InvalidOperationException("You should not have seen this message, but now that you do" +
                                                    "I want you to open an issue here https://github.com/fritzAndFriends/BlazorWebFormsComponents/issues " +
                                                    "with a title 'ValueExpression.Body is not MemberExpression' and a sample code to reproduce this. Thanks!");
            }

            var fieldIdentifier = CurrentEditContext.Field(name);

            _messageStore.Clear(fieldIdentifier);
            var value = GetCurrentValueAsString();

            if (!Enabled || Validate(value))
            {
                IsValid = true;
            }
            else
            {
                IsValid = false;
                // Text is for validator, ErrorMessage is for validation summary
                _messageStore.Add(fieldIdentifier, Text + "," + ErrorMessage);
            }

            CurrentEditContext.NotifyValidationStateChanged();
        }
        public void EventHandler(EditContext editContext, ValidationMessageStore messages)
        {
            string name;

            if (ControlToValidate.Current.ValueExpression.Body is MemberExpression memberExpression)
            {
                name = memberExpression.Member.Name;
            }
            else
            {
                throw new InvalidOperationException("You shoud not have seen this message, but now that you do" +
                                                    "I want you to open an issue here https://github.com/fritzAndFriends/BlazorWebFormsComponents/issues " +
                                                    "with a title 'ValueExpression.Body is not MemberExpression' and a sample code to reproduce this. Thanks!");
            }

            var fieldIdentifier = CurrentEditContext.Field(name);

            messages.Clear(fieldIdentifier);

            var value = typeof(InputBase <Type>).GetProperty("CurrentValueAsString", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(ControlToValidate.Current) as string;

            if (!Enabled || Validate(value))
            {
                IsValid = true;
            }
            else
            {
                IsValid = false;
                // Text is for validator,ErrorMessage is for validation summary
                messages.Add(fieldIdentifier, Text + "," + ErrorMessage);
            }

            editContext.NotifyValidationStateChanged();
        }
 private string[] GetValidationErrors()
 {
     if (CurrentEditContext != null)
     {
         return(CurrentEditContext.GetValidationMessages().ToArray());
     }
     return(Array.Empty <string>());
 }
 protected override void OnInitialized()
 {
     if (CurrentEditContext == null)
     {
         throw new InvalidOperationException($"Invalid Edit Context");
     }
     CurrentEditContext.AddFluentValidation(ServiceProvider, validator);
 }
Exemple #9
0
        void IFormItem.AddControl <TValue>(AntInputComponentBase <TValue> control)
        {
            if (_control != null)
            {
                return;
            }

            if (control.FieldIdentifier.Model == null)
            {
                throw new InvalidOperationException($"Please use @bind-Value (or @bind-Values for selected components) in the control with generic type `{typeof(TValue)}`.");
            }

            _fieldIdentifier = control.FieldIdentifier;
            this._control    = control;


            if (Form.ValidateMode.IsIn(FormValidateMode.Rules, FormValidateMode.Complex))
            {
                _fieldPropertyInfo = _fieldIdentifier.Model.GetType().GetProperty(_fieldIdentifier.FieldName);
            }

            _validationStateChangedHandler = (s, e) =>
            {
                control.ValidationMessages = CurrentEditContext.GetValidationMessages(control.FieldIdentifier).Distinct().ToArray();
                this._isValid = !control.ValidationMessages.Any();

                StateHasChanged();
            };

            CurrentEditContext.OnValidationStateChanged += _validationStateChangedHandler;

            _formValidationMessages = builder =>
            {
                var i = 0;
                builder.OpenComponent <FormValidationMessage <TValue> >(i++);
                builder.AddAttribute(i++, "Control", control);
                builder.CloseComponent();
            };

            if (control.ValueExpression is not null)
            {
                _propertyReflector = PropertyReflector.Create(control.ValueExpression);
            }
            else
            {
                _propertyReflector = PropertyReflector.Create(control.ValuesExpression);
            }

            if (_propertyReflector.RequiredAttribute != null)
            {
                _labelCls = $"{_prefixCls}-required";
            }
            if (_propertyReflector.DisplayName != null)
            {
                Label ??= _propertyReflector.DisplayName;
            }
        }
 protected override void OnInitialized()
 {
     if (CurrentEditContext == null)
     {
         throw new InvalidOperationException($"{nameof(DataAnnotationsValidator)} requires a cascading " +
                                             $"parameter of type {nameof(EditContext)}. For example, you can use {nameof(DataAnnotationsValidator)} " +
                                             $"inside an EditForm.");
     }
     CurrentEditContext.SetFieldCssClassProvider(provider);
 }
 protected override void OnInitialized()
 {
     if (CurrentEditContext == null)
     {
         throw new InvalidOperationException($"{nameof(FluentValidationValidator)} requires a cascading " +
                                             $"parameter of type {nameof(EditContext)}. For example, you can use {nameof(FluentValidationValidator)} " +
                                             $"inside an {nameof(EditForm)}.");
     }
     CurrentEditContext.AddFluentValidation(ShouldValidate);
 }
        /// <summary>`
        /// Constructs an instance of <see cref="ValidationMessage{TValue}"/>.
        /// </summary>
        public FormValidationMessage()
        {
            _validationStateChangedHandler = (sender, eventArgs) =>
            {
                bool valid = !CurrentEditContext.GetValidationMessages(_fieldIdentifier).Any();
                OnStateChange.InvokeAsync(valid);

                StateHasChanged();
            };
        }
Exemple #13
0
 /// <inheritdoc />
 protected override void BuildRenderTree(RenderTreeBuilder builder)
 {
     foreach (string message in CurrentEditContext.GetValidationMessages(FieldIdentifier))
     {
         builder.OpenElement(0, "div");
         builder.AddMultipleAttributes(1, AdditionalAttributes);
         builder.AddContent(2, message);
         builder.CloseElement();
     }
 }
 /// <inheritdoc />
 protected override void BuildRenderTree(RenderTreeBuilder builder)
 {
     foreach (var message in CurrentEditContext.GetValidationMessages(_fieldIdentifier))
     {
         builder.OpenElement(0, "div");
         builder.AddAttribute(1, "class", "validation-message");
         builder.AddContent(2, message);
         builder.CloseElement();
     }
 }
Exemple #15
0
 /// <inheritdoc />
 protected override void BuildRenderTree(RenderTreeBuilder builder)
 {
     foreach (var message in CurrentEditContext.GetValidationMessages(_fieldIdentifier))
     {
         builder.OpenElement(0, "div");
         builder.AddMultipleAttributes(1, AdditionalAttributes);
         builder.AddAttribute(2, "class", "invalid-feedback");
         builder.AddContent(3, message);
         builder.CloseElement();
     }
 }
Exemple #16
0
        protected override void OnInitialized()
        {
            if (CurrentEditContext == null)
            {
                throw new InvalidOperationException($"{nameof(FluentValidationValidator)} requires a cascading " +
                                                    $"parameter of type {nameof(EditContext)}. For example, you can use {nameof(FluentValidationValidator)} " +
                                                    $"inside an {nameof(EditForm)}.");
            }

            CurrentEditContext.AddFluentValidation(ServiceProvider, DisableAssemblyScanning, Validator, this);
        }
    /// <summary>
    /// 初始化方法
    /// </summary>
    protected override void OnInitialized()
    {
        if (ValidateForm == null)
        {
            throw new InvalidOperationException($"{nameof(Components.BootstrapBlazorDataAnnotationsValidator)} requires a cascading " +
                                                $"parameter of type {nameof(Components.ValidateForm)}. For example, you can use {nameof(Components.BootstrapBlazorDataAnnotationsValidator)} " +
                                                $"inside an {nameof(Components.ValidateForm)}.");
        }

        CurrentEditContext.AddEditContextDataAnnotationsValidation(ValidateForm);
    }
    /// <inheritdoc />
    protected override void OnInitialized()
    {
        if (CurrentEditContext == null)
        {
            throw new InvalidOperationException($"{nameof(DataAnnotationsValidator)} requires a cascading " +
                                                $"parameter of type {nameof(EditContext)}. For example, you can use {nameof(DataAnnotationsValidator)} " +
                                                $"inside an EditForm.");
        }

        _subscriptions       = CurrentEditContext.EnableDataAnnotationsValidation(ServiceProvider);
        _originalEditContext = CurrentEditContext;
    }
        protected override void OnInit()
        {
            if (CurrentEditContext == null)
            {
                throw new InvalidOperationException($"{nameof(FluentValidationValidator)} requires a cascading " +
                                                    $"parameter of type {nameof(EditContext)}. For example, you can use {nameof(FluentValidationValidator)} " +
                                                    $"inside an {nameof(EditForm)}.");
            }

            Console.WriteLine(Validator == null);
            CurrentEditContext.AddFluentValidation(ServiceProvider, Validator);
        }
Exemple #20
0
 private void Validate(Person model, ValidationMessageStore store)
 {
     if (model.DepartmentId == DepartmentId && (!LocationStates.ContainsKey(model.LocationId) || LocationStates[model.LocationId] != State))
     {
         store.Add(CurrentEditContext.Field("LocationId"), $"{DeptName} staff must be in: {State}");
     }
     else
     {
         store.Clear();
     }
     CurrentEditContext.NotifyValidationStateChanged();
 }
Exemple #21
0
        public void ClearMessages(bool clearValidationMessages)
        {
            if (clearValidationMessages)
            {
                ValidationMessageStore.Clear();

                CurrentEditContext.NotifyValidationStateChanged();
            }

            Message = string.Empty;

            StateHasChanged();
        }
Exemple #22
0
        public bool Validate(Action <ValidationStrategy <object> > options)
        {
            this.options = options;

            try
            {
                return(CurrentEditContext.Validate());
            }
            finally
            {
                this.options = null;
            }
        }
 /// <inheritdoc />
 protected override void BuildRenderTree(RenderTreeBuilder builder)
 {
     foreach (var message in CurrentEditContext.GetValidationMessages(_fieldIdentifier))
     {
         builder.OpenElement(0, "div");
         builder.AddMultipleAttributes(1, AdditionalAttributes);
         builder.AddAttribute(2, "id", Id);
         builder.AddAttribute(2, "class", "mdc-text-field-helper-text mdc-text-field-helper-text--persistent mdc-text-field-helper-text--validation-msg");
         builder.AddAttribute(2, "data-valmsg-for", ForId);
         builder.AddContent(3, message);
         builder.CloseElement();
     }
 }
        public void DisplayErrors(Dictionary <string, List <string> > errors)
        {
            if (errors == null || errors.Count == 0)
            {
                return;
            }

            foreach (var err in errors)
            {
                _messageStore.Add(CurrentEditContext.Field(err.Key), err.Value);
            }

            CurrentEditContext.NotifyValidationStateChanged();
        }
Exemple #25
0
        /// <summary>
        /// 初始化方法
        /// </summary>
        protected override void OnInitialized()
        {
            if (CurrentEditContext == null)
            {
                throw new InvalidOperationException($"{nameof(DataAnnotationsValidator)} requires a cascading parameter of type {nameof(EditContext)}. For example, you can use {nameof(DataAnnotationsValidator)} inside an EditForm.");
            }

            if (EditForm == null)
            {
                throw new InvalidOperationException($"{nameof(DataAnnotationsValidator)} requires a cascading parameter of type {nameof(LgbEditFormBase)}. For example, you can use {nameof(BootstrapAdminDataAnnotationsValidator)} inside an EditForm.");
            }

            CurrentEditContext.AddBootstrapAdminDataAnnotationsValidation(EditForm);
        }
Exemple #26
0
 protected override void OnParametersSet()
 {
     this.IsValid = true;
     {
         if (this.IsRequired)
         {
             this.IsValid = false;
             var messages = CurrentEditContext.GetValidationMessages(_fieldIdentifier).ToList();
             if (messages is null || messages.Count == 0)
             {
                 this.IsValid = true;
             }
         }
     }
 }
Exemple #27
0
        protected override void BuildRenderTree(RenderTreeBuilder builder)
        {
            var classes = ((Dictionary <string, object>)AdditionalAttributes).VorN("class")?.ToString().Split(" ").ToList() ?? new List <string>();

            classes.Insert(0, "validation-message");
            var strClasses = string.Join(" ", classes);

            foreach (var message in CurrentEditContext.GetValidationMessages(_fieldIdentifier))
            {
                builder.OpenElement(0, "div");
                builder.AddMultipleAttributes(1, AdditionalAttributes);
                builder.AddAttribute(2, "class", strClasses);
                builder.AddContent(3, message);
                builder.CloseElement();
            }
        }
        private void ValidateRequested(object?editContext, ValidationRequestedEventArgs validationEventArgs)
        {
            messageStore.Clear();

            var tmp = (TRow)Context.Data;

            var validationResult = Validator.Validate(tmp);

            if (!validationResult.IsValid)
            {
                foreach (var item in validationResult.Errors)
                {
                    messageStore.Add(new FieldIdentifier(tmp, item.PropertyName), item.ErrorMessage);
                }
            }

            CurrentEditContext.NotifyValidationStateChanged();
        }
Exemple #29
0
        public void ShowError(Result result, object model)
        {
            ClearMessages(false);

            if (result.Success == false)
            {
                ShowMessage("Błąd w formularzu", MessageType.Error);

                ValidationMessageStore.Clear();

                foreach (var error in result.Errors.Where(e => string.IsNullOrEmpty(e.PropertyName) == false))
                {
                    var fieldIdentifier = new FieldIdentifier(model, error.PropertyName);
                    ValidationMessageStore.Add(fieldIdentifier, error.Message);
                }
            }

            CurrentEditContext.NotifyValidationStateChanged();
        }
        private async void CurrentEditContextOnValidationStateChanged(object sender, ValidationStateChangedEventArgs e)
        {
            Log.LogInformation("-> CurrentEditContextOnValidationStateChanged");

            if (CurrentEditContext.GetValidationMessages().Count() == 0)
            {
                Log.LogTrace("Saving");

                if (!await Host.SaveSession())
                {
                    return;
                }

                await Host.UpdateRemoteHosts(
                    UpdateAction.UpdateClock,
                    null,
                    CurrentClockMessage,
                    null);
            }
        }