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); }
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 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(); }
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(); }
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(); }
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)}."); } var validator = Validator ?? GetValidatorForModel(CurrentEditContext.Model); if (validator == null) { throw new InvalidOperationException($"{nameof(FluentValidationValidator)} requires either a " + $"parameter of type {nameof(IValidator)}, or validator for type {nameof(CurrentEditContext.Model)} " + $"should be reachable via reflection from the calling assembly."); } var messages = new ValidationMessageStore(CurrentEditContext); var modelName = CurrentEditContext.Model.GetType().FullName; // This field collects errors that are model-related but not specific to concrete property on the model var modelErrorField = new FieldIdentifier(CurrentEditContext.Model, string.Empty); var _event = _eventAggregator?.GetEvent <ValidationEvent>(); // This subscription fires when Submit button is pressed, // acts as a guard against not validated still-focused field formValidationSub = Observable.FromEventPattern <ValidationRequestedEventArgs>( handler => CurrentEditContext.OnValidationRequested += handler, handler => CurrentEditContext.OnValidationRequested -= handler) .Subscribe(e => { messages.Clear(); var validationResults = validator.Validate(CurrentEditContext.Model); if (validationResults.IsValid) { _event?.Publish(new ValidationEventArgs(true, modelName)); if (OnValidation.HasDelegate) { OnValidation.InvokeAsync(true); } } else { _event?.Publish(new ValidationEventArgs(false, modelName)); if (OnValidation.HasDelegate) { OnValidation.InvokeAsync(false); } foreach (var validationResult in validationResults.Errors) { messages.Add(CurrentEditContext.Field(validationResult.PropertyName), validationResult.ErrorMessage); } } CurrentEditContext.NotifyValidationStateChanged(); }); // This subscription fires every time an input field loses a focus, main workhorse fieldValidationSub = Observable.FromEventPattern <FieldChangedEventArgs>( handler => CurrentEditContext.OnFieldChanged += handler, handler => CurrentEditContext.OnFieldChanged -= handler) .Subscribe(e => { var validationResults = validator.Validate(CurrentEditContext.Model); if (validationResults.IsValid) { messages.Clear(); _event?.Publish(new ValidationEventArgs(true, modelName)); if (OnValidation.HasDelegate) { OnValidation.InvokeAsync(true); } } else { _event?.Publish(new ValidationEventArgs(false, modelName)); if (OnValidation.HasDelegate) { OnValidation.InvokeAsync(false); } messages.Clear(e.EventArgs.FieldIdentifier); messages.AddRange(e.EventArgs.FieldIdentifier, validationResults.Errors .Where(failure => failure.PropertyName == e.EventArgs.FieldIdentifier.FieldName) .Select(failure => failure.ErrorMessage)); // add errors that are not specific to field, e.g. complex rules messages.Clear(modelErrorField); messages.AddRange(modelErrorField, validationResults.Errors .Where(failure => failure.PropertyName == string.Empty) .Select(failure => failure.ErrorMessage)); } CurrentEditContext.NotifyValidationStateChanged(); }); }