private static void ValidateModel(EditContext?editContext, ValidationMessageStore messages, ValidateForm editForm) { if (editContext != null) { var validationContext = new ValidationContext(editContext.Model); var validationResults = new List <ValidationResult>(); editForm.ValidateObject(validationContext, validationResults); messages.Clear(); foreach (var validationResult in validationResults.Where(v => !string.IsNullOrEmpty(v.ErrorMessage))) { if (!validationResult.MemberNames.Any()) { messages.Add(new FieldIdentifier(editContext.Model, fieldName: string.Empty), validationResult.ErrorMessage !); continue; } foreach (var memberName in validationResult.MemberNames) { messages.Add(editContext.Field(memberName), validationResult.ErrorMessage !); } } editContext.NotifyValidationStateChanged(); } }
/// <summary> /// 添加数据合规检查 /// </summary> /// <param name="editContext">The <see cref="EditContext"/>.</param> /// <param name="editForm"></param> public static EditContext AddEditContextDataAnnotationsValidation(this EditContext editContext, ValidateForm editForm) { if (editContext == null) { throw new ArgumentNullException(nameof(editContext)); } var messages = new ValidationMessageStore(editContext); editContext.OnValidationRequested += (sender, eventArgs) => ValidateModel(sender as EditContext, messages, editForm); editContext.OnFieldChanged += (sender, eventArgs) => ValidateField(editContext, messages, eventArgs.FieldIdentifier, editForm); return(editContext); }