public static IRuleBuilderOptions <T, string> Password <T>(this IRuleBuilderInitial <T, string> ruleBuilder) { return(ruleBuilder .Cascade(CascadeMode.Stop) .NotEmpty().WithMessage("Password is required.") .Length(6, 20).WithMessage("Incorrect email or password.")); }
public static IRuleBuilderOptions <T, string> EmailRequired <T>(this IRuleBuilderInitial <T, string> builder, string name) { return(builder .IsRequired(name) .EmailAddress() .WithMessage(string.Format(ValidationTokens.InvalidEmailFormat, name))); }
public ValidatorExtentionsTests() { var validator = new InlineValidator <Address>(); _builder = validator.RuleFor(x => x.Country); _builder.Configure(_ => { }); }
public static void MustBeHexString <T>( this IRuleBuilderInitial <T, string> ruleBuilder) { //ruleBuilder // .Must(@string => HexStringExpression.IsMatch(@string)) // .WithMessage(x => "Must be a hex string."); }
public static IRuleBuilderOptions <T, int> ValidaCodigo <T>(this IRuleBuilderInitial <T, int> ruleBuilder) where T : Cargo { return(ruleBuilder.Cascade(CascadeMode.StopOnFirstFailure) .CodigoMinimoValida().WithMessage("") .CodigoMaximoValida().WithMessage("")); }
public static void AmountMustBeValid <T>( this IRuleBuilderInitial <T, string> ruleBuilder) { ruleBuilder .Must(amount => BigInteger.TryParse(amount, out var amountParsed) && amountParsed > 0) .WithMessage(x => "Amount must be greater than zero."); }
public static void AddressMustBeValid <T>( this IRuleBuilderInitial <T, string> ruleBuilder) { ruleBuilder .Must(x => Address.ValidateFormatAndChecksum(x, true, true)) .WithMessage(x => $"Specified address is not valid."); }
/// <summary> /// Range. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="ruleBuilderInitial"></param> /// <returns></returns> public static IRuleBuilderInitial <T, int> Min <T>(this IRuleBuilderInitial <T, int> ruleBuilderInitial, int min) { ruleBuilderInitial .GreaterThanOrEqualTo(min) .WithMessage("{PropertyName}必须大于等于{Min}"); return(ruleBuilderInitial); }
/// <summary> /// Range. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="ruleBuilderInitial"></param> /// <returns></returns> public static IRuleBuilderInitial <T, int> Max <T>(this IRuleBuilderInitial <T, int> ruleBuilderInitial, int max) { ruleBuilderInitial .LessThanOrEqualTo(max) .WithMessage("{PropertyName}必须介于小于等于{Max}"); return(ruleBuilderInitial); }
/// <summary> /// Max length. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="ruleBuilderInitial"></param> /// <returns></returns> public static IRuleBuilderInitial <T, string> MaxLength <T>(this IRuleBuilderInitial <T, string> ruleBuilderInitial, int maxlength) { ruleBuilderInitial .MaximumLength(maxlength) .WithMessage("{PropertyName}长度不能超过{MaxLength}"); return(ruleBuilderInitial); }
/// <summary> /// Min length. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="ruleBuilderInitial"></param> /// <returns></returns> public static IRuleBuilderInitial <T, string> MinLength <T>(this IRuleBuilderInitial <T, string> ruleBuilderInitial, int minlength) { ruleBuilderInitial .MinimumLength(minlength) .WithMessage("{PropertyName}长度不能小于{MinLength}"); return(ruleBuilderInitial); }
public static IRuleBuilderOptions <T, string> RequiredTitle <T>(this IRuleBuilderInitial <T, string> propertyRule) { return(propertyRule .NotEmpty() .Length(0, TitleMaxLength) .Matches(NotOnlyNumbersPattern)); }
public static IRuleBuilderOptions <T, string> RequiredSlug <T>(this IRuleBuilderInitial <T, string> propertyRule) { return(propertyRule .NotEmpty() .Length(0, SlugMaxLength) .Matches(AllowedSlugCharsPattern)); }
public static IRuleBuilderOptions <T, string> Email <T>(this IRuleBuilderInitial <T, string> ruleBuilder) { return(ruleBuilder .Cascade(CascadeMode.Stop) .NotEmpty().WithMessage("Email is required.") .EmailAddress().WithMessage("Please enter a valid email address.")); }
public static void PhoneNumber <T>(this IRuleBuilderInitial <T, string> field) { field .NormalizeWhitespace() .Apply(Rules.PhoneNumber) .WithMessageFromErrorCode("VENUE_TELEPHONE_FORMAT"); }
/// <summary> /// Range. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="ruleBuilderInitial"></param> /// <returns></returns> public static IRuleBuilderInitial <T, int> Between <T>(this IRuleBuilderInitial <T, int> ruleBuilderInitial, int max, int min) { ruleBuilderInitial .InclusiveBetween(min, max) .WithMessage("{PropertyName}必须介于{Min}与{Max}之间"); return(ruleBuilderInitial); }
public static void StartDate <T>( this IRuleBuilderInitial <T, DateInput> field, Guid?tLevelId, Guid providerId, Guid tLevelDefinitionId, ISqlQueryDispatcher sqlQueryDispatcher) { field .Cascade(CascadeMode.Stop) .NotEmpty() .WithMessage("Enter a start date") .Apply(builder => Rules.Date(builder, displayName: "Start date")) .CustomAsync(async(v, ctx, _) => { var existingTLevels = await sqlQueryDispatcher.ExecuteQuery( new GetTLevelsForProvider() { ProviderId = providerId }); if (existingTLevels.Any(tl => tl.TLevelDefinition.TLevelDefinitionId == tLevelDefinitionId && tl.StartDate == v.Value && tl.TLevelId != tLevelId)) { ctx.AddFailure("Start date already exists"); } }); }
public static void Venue <T>( this IRuleBuilderInitial <T, string> field, Func <T, ApprenticeshipLocationType?> getDeliveryMode) { field .NormalizeWhitespace() .Custom((v, ctx) => { var obj = (T)ctx.InstanceToValidate; var deliveryMode = getDeliveryMode(obj); var isSpecified = !string.IsNullOrEmpty(v); // Not allowed for delivery modes other than classroom based if (isSpecified && deliveryMode != ApprenticeshipLocationType.ClassroomBased) { ctx.AddFailure(CreateFailure("APPRENTICESHIP_VENUE_NOT_ALLOWED")); return; } if (deliveryMode != ApprenticeshipLocationType.ClassroomBased) { return; } ValidationFailure CreateFailure(string errorCode) => ValidationFailureEx.CreateFromErrorCode(ctx.PropertyName, errorCode); }); }
public static void TransactionIdMustBeNonEmptyGuid <T>( this IRuleBuilderInitial <T, Guid> ruleBuilder) { ruleBuilder .Must(transactionId => transactionId != Guid.Empty) .WithMessage(x => "Specified transaction id is empty."); }
public static void DeliveryMode <T>(this IRuleBuilderInitial <T, IEnumerable <ApprenticeshipDeliveryMode> > field, Func <T, ApprenticeshipLocationType?> getDeliveryMethod) { field .Custom((v, ctx) => { var obj = (T)ctx.InstanceToValidate; var deliveryMethod = getDeliveryMethod(obj); if (deliveryMethod == ApprenticeshipLocationType.ClassroomBased || deliveryMethod == ApprenticeshipLocationType.ClassroomBasedAndEmployerBased) { if (!v.Contains(ApprenticeshipDeliveryMode.BlockRelease) && !v.Contains(ApprenticeshipDeliveryMode.DayRelease)) { ctx.AddFailure(CreateFailure("APPRENTICESHIP_DELIVERYMODE_MUSTBE_DAY_OR_BLOCK")); } } if (deliveryMethod == ApprenticeshipLocationType.EmployerBased) { // Allow Employer to be specified but nothing else if (v != null && v.Any() && !v.SequenceEqual(new[] { ApprenticeshipDeliveryMode.EmployerAddress })) { ctx.AddFailure(CreateFailure("APPRENTICESHIP_DELIVERYMODE_NOT_ALLOWED")); } } ValidationFailure CreateFailure(string errorCode) => ValidationFailureEx.CreateFromErrorCode(ctx.PropertyName, errorCode); }); }
public static void AssetMustBeSupported <T>( this IRuleBuilderInitial <T, string> ruleBuilder) { ruleBuilder .Must(assetId => assetId == Constants.AssetId) .WithMessage(x => $"Specified asset is not supported."); }
public static void ContactTelephone <T>(this IRuleBuilderInitial <T, string> field) => field .NormalizeWhitespace() .NotEmpty() .WithMessageFromErrorCode("APPRENTICESHIP_TELEPHONE_REQUIRED") .Apply(Rules.PhoneNumber) .WithMessageFromErrorCode("APPRENTICESHIP_TELEPHONE_FORMAT");
public static void VenueId <T>( this IRuleBuilderInitial <T, Guid?> field, Func <T, CourseDeliveryMode?> getDeliveryMode) { field .Custom((v, ctx) => { var obj = (T)ctx.InstanceToValidate; var deliveryMode = getDeliveryMode(obj); var isSpecified = v.HasValue; // Not allowed for delivery modes other than classroom based if (isSpecified && deliveryMode != CourseDeliveryMode.ClassroomBased) { ctx.AddFailure(CreateFailure("COURSERUN_VENUE_NAME_NOT_ALLOWED")); return; } if (deliveryMode == CourseDeliveryMode.ClassroomBased && !isSpecified) { ctx.AddFailure(CreateFailure("COURSERUN_VENUE_REQUIRED")); return; } ValidationFailure CreateFailure(string errorCode) => ValidationFailureEx.CreateFromErrorCode(ctx.PropertyName, errorCode); }); }
public static void AddressMustBeValid <T>( this IRuleBuilderInitial <T, string> ruleBuilder, IAddressService addressService) { ruleBuilder .MustAsync(async(rootObject, address, context, cancellationToken) => { if (address == null) { context.MessageFormatter.AppendArgument("Reason", "Must be specified."); return(false); } var validationResult = await addressService.ValidateAsync(address, false, true); if (validationResult is AddressValidationResult.Error error) { context.MessageFormatter.AppendArgument("Reason", error.Type.ToReason()); return(false); } else { return(true); } }) .WithMessage("{Reason}"); }
public static void VenueName <T>( this IRuleBuilderInitial <T, string> field, int providerUkprn, Guid?venueId, ICosmosDbQueryDispatcher cosmosDbQueryDispatcher) { field .NotEmpty() .WithMessage("Enter location name") .MaximumLength(Constants.NameMaxLength) .WithMessage($"Location name must be {Constants.NameMaxLength} characters or fewer") .MustAsync(async(name, _) => { // Venue name must be distinct for this provider var providerVenues = await cosmosDbQueryDispatcher.ExecuteQuery(new GetVenuesByProvider() { ProviderUkprn = providerUkprn }); var otherVenuesWithSameName = providerVenues .Where(v => v.VenueName.Equals(name, StringComparison.OrdinalIgnoreCase)) .Where(v => v.Id != venueId); return(!otherVenuesWithSameName.Any()); }) .WithMessage("Location name must not already exist"); }
public static void AssetMustBeValidAndSupported <T>( this IRuleBuilderInitial <T, string> ruleBuilder, IAssetService assetService) { ruleBuilder .Must((rootObject, assetId, context) => { if (string.IsNullOrWhiteSpace(assetId)) { context.MessageFormatter.AppendArgument("Reason", "Must be specified."); return(false); } if (assetService.Get().Id != assetId) { context.MessageFormatter.AppendArgument("Reason", "Must be supported."); return(false); } return(true); }) .WithMessage("{Reason}"); }
/// <summary> /// Triggers an action to specify validation rules to the contained value when the <see cref="Option{T}"/> contains a value. /// </summary> /// <param name="rule">The current rule</param> /// <param name="action">An action to be invoked if the rule is valid</param> /// <returns></returns> public static IRuleBuilderOptions <T, TProperty> WhenPresent <T, TProperty>( this IRuleBuilderInitial <T, Option <TProperty> > rule, Func <IRuleBuilderInitial <T, TProperty>, IRuleBuilderOptions <T, TProperty> > action) { if (rule == null) { throw new ArgumentNullException(nameof(rule)); } if (action == null) { throw new ArgumentNullException(nameof(action)); } // Cast to extract the actual rule instance from the internal api. var actualRuleBuilder = rule as RuleBuilder <T, Option <TProperty> > ?? throw new ArgumentException( $"Rule is not an instance of '{typeof(RuleBuilder<T, Option<TProperty>>)}'."); var actualRule = actualRuleBuilder.Rule; var actualRuleExpression = actualRule.Expression as Expression <Func <T, Option <TProperty> > > ?? throw new ArgumentException( $"Rule does not point to a property of type '{typeof(Option<TProperty>)}'."); // Provide a transformation function. This is fine as the internal model requires a Func<object, object> actualRule.Transformer = value => ((Option <TProperty>)value).ValueOrDefault(); // Create a new RuleBuilder that has the new type as the destination. var nestedRuleBuilder = new RuleBuilder <T, TProperty>(actualRule, actualRuleBuilder.ParentValidator); return(action(nestedRuleBuilder).WhenPresent(actualRuleExpression)); }
public static void ProviderVenueRef <T>( this IRuleBuilderInitial <T, string> field, Func <T, Task <IEnumerable <string> > > getOtherVenueProviderVenueRefs) { field .NormalizeWhitespace() .NotEmpty() .WithMessageFromErrorCode("VENUE_PROVIDER_VENUE_REF_REQUIRED") .MaximumLength(Constants.ProviderVenueRefMaxLength) .WithMessageFromErrorCode("VENUE_PROVIDER_VENUE_REF_MAXLENGTH") .MustAsync(async(obj, providerVenueRef, _) => { // Field is optional if (string.IsNullOrEmpty(providerVenueRef)) { return(true); } // Venue name must be distinct for this provider var otherVenueRefs = await getOtherVenueProviderVenueRefs(obj); var otherVenuesWithSameRef = otherVenueRefs .Where(v => (v ?? string.Empty).Equals(providerVenueRef, StringComparison.OrdinalIgnoreCase)); return(!otherVenuesWithSameRef.Any()); }) .WithMessageFromErrorCode("VENUE_PROVIDER_VENUE_REF_UNIQUE"); }
public static IRuleBuilderOptions <T, string> ValidaNome <T>(this IRuleBuilderInitial <T, string> ruleBuilder) where T : Convidado { return(ruleBuilder.Cascade(CascadeMode.StopOnFirstFailure) .NotNull().WithMessage("Nome não pode ser nulo!") .NotEmpty().WithMessage("Nome não pode ser vazio!") .Length(0, 100).WithMessage("O Tamanho do Nome não pode ser maior que 100!")); }
/// <summary> /// Defines a 'date' validator on the current rule builder, extracting the validation state /// from a corresponding entry on the validator's <c>ActionContext</c>. /// </summary> /// <typeparam name="T">Type of object being validated.</typeparam> /// <param name="ruleBuilder"> /// The rule builder on which the validator should be defined. /// The validator must inherit from <see cref="ValidatorBase{T}"/>. /// </param> /// <param name="displayName">The display name of the field being validated.</param> /// <param name="missingErrorMessage">The validation message to create if the field is missing.</param> /// <example> /// <code> /// RuleFor(m => m.DateOfBirth).Date( /// displayName: "Date of birth", /// missingErrorMessage: "Enter your date of birth"); /// </code> /// </example> public static IRuleBuilderInitial <T, Date?> Date <T>( this IRuleBuilderInitial <T, Date?> ruleBuilder, string displayName, string missingErrorMessage, bool isRequired = false) { if (!(ruleBuilder is FluentValidation.Internal.RuleBuilder <T, Date?> b) || !(b.ParentValidator is ValidatorBase <T> validatorBase)) { throw new InvalidOperationException( "Rule can only be applied on validators inheriting from ValidatorBase<T>."); } return(ruleBuilder.Custom((property, context) => { if (validatorBase.ActionContext.ModelState.TryGetValue(context.PropertyName, out var entry) && entry.Errors.SingleOrDefault()?.Exception is DateParseException dateParseException) { // Reference https://design-system.service.gov.uk/components/date-input/#error-messages var dayIsMissing = string.IsNullOrEmpty(entry.GetModelStateForProperty("Day").AttemptedValue); var monthIsMissing = string.IsNullOrEmpty(entry.GetModelStateForProperty("Month").AttemptedValue); var yearIsMissing = string.IsNullOrEmpty(entry.GetModelStateForProperty("Year").AttemptedValue); if (dayIsMissing && monthIsMissing && yearIsMissing) { // If nothing is entered // Say 'Enter [whatever it is]'. For example, 'Enter your date of birth'. context.AddFailure(missingErrorMessage); } else if (dayIsMissing || monthIsMissing || yearIsMissing) { // If the date is incomplete // Say '[whatever it is] must include a [whatever is missing]'. // For example, 'Date of birth must include a month' or 'Date of birth must include a day and month'. var missingParts = (dayIsMissing ? new[] { "day" } : Array.Empty <string>()) .Concat(monthIsMissing ? new[] { "month" } : Array.Empty <string>()) .Concat(yearIsMissing ? new[] { "year" } : Array.Empty <string>()); context.AddFailure($"{displayName} must include a {string.Join(" and ", missingParts)}"); } else { // If the date entered can’t be correct // For example, '13' in the month field can’t be correct. // Highlight the day, month or year field with the incorrect information. Or highlight the date as a whole if there’s incorrect information in more than one field, or it’s not clear which field is incorrect. // Say '[Whatever it is] must be a real date'. For example, 'Date of birth must be a real date'. context.AddFailure($"{displayName} must be a real date"); } } else if (!property.HasValue && isRequired) { context.AddFailure(missingErrorMessage); } })); }