我想验证特定文本的文本框,它不能为空.但是正则表达式验证器不验证文本框是否为BLANK.但是,它验证我是否在文本框中键入内容.
即使文本框为空,如何使正则表达式触发?
我应该同时使用Required Validator + Regex Validator吗?谢谢.
<asp:TextBox ID="txtcard" runat="server" MaxLength="16"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server"
ControlToValidate="txtcard" ErrorMessage="Please type credit card no"
ValidationExpression="^\d{16}$"></asp:RegularExpressionValidator>
Run Code Online (Sandbox Code Playgroud) regex asp.net validation fluentvalidation fluentvalidation-2.0
我试图让Fluent验证在我的客户端验证上正常工作.我正在使用ASP.NET MVC 3.
我有一个必需的标题,它必须在1到100个字符之间.因此,当我输入标题时,会显示一条错误消息,该消息不在我的规则集中.这是我的规则集:
RuleFor(x => x.Title)
.NotEmpty()
.WithMessage("Title is required")
.Length(1, 100)
.WithMessage("Title must be less than or equal to 100 characters");
Run Code Online (Sandbox Code Playgroud)
以下是显示的错误消息:
Please enter a value less than or equal to 100
Run Code Online (Sandbox Code Playgroud)
我不确定我做错了什么.这是我的global.asax:
// FluentValidation
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
ModelValidatorProviders.Providers.Clear();
ModelValidatorProviders.Providers.Add(
new FluentValidationModelValidatorProvider(new AttributedValidatorFactory()));
ModelMetadataProviders.Current = new FluentValidationModelMetadataProvider(
new AttributedValidatorFactory());
Run Code Online (Sandbox Code Playgroud) 我有一个Action类,它包含更多Action对象的集合.像这样的东西:
public class Action
{
ICollection<Action> SubActions;
}
Run Code Online (Sandbox Code Playgroud)
这基本上形成了一个树形结构(我确保没有循环).我使用Fluent Validation为这个类编写验证器.这是我的Validator尝试:
public class ActionValidator : AbstractValidator<Action>
{
public ActionValidator()
{
RuleFor(x => x.SubActions).SetCollectionValidator(new ActionValidator());
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试解决依赖于ActionValidator的任何事情时,Unity会爆炸.更具体地说,LINQPad在尝试解析依赖于ActionValidator的服务时崩溃,可能是来自堆栈溢出.
在我的Action类中还有其他成员我正在验证,但我只是为了简洁起见重要部分.如果我注释掉我在这里列出的规则,它可以正常工作(除了它不再验证子动作).
我的方法遇到了问题.我递归地构造验证器直到某些东西死亡.但我只是不确定如何告诉Fluent Validation以这种方式验证子对象.
我使用流畅的验证和ninject设置了一个ASP.NET MVC3网站.验证码正在运行.但是,我在验证类构造函数中设置了一个断点,我注意到当我请求使用验证的视图时,构造函数会被多次命中.基于非常基本的测试,似乎命中构造函数的次数等于对象上存在的属性数.还有其他人遇到过类似的东西吗?或者有人可以更深入地了解这种类型的验证在幕后如何运作?-谢谢
这是构造函数......
public class PersonValidator : AbstractValidator<Person> {
public PersonValidator() {
RuleFor(x => x.Id).NotNull();
RuleFor(x => x.Name).Length(0, 10);
RuleFor(x => x.Email).EmailAddress();
RuleFor(x => x.Age).InclusiveBetween(18, 60);
}
}
Run Code Online (Sandbox Code Playgroud)
以下是我正在使用的库/资源(我刚刚获得了NuGet包并根据以下两个链接的信息配置了所有内容):
http://fluentvalidation.codeplex.com/wikipage?title=mvc https://github.com/ninject/ninject.web.mvc.fluentvalidation
我是Fluent Validation的新手,刚刚从nu Get 获得了5.3版本.我正在尝试将现有验证器(PhoneValidator)应用于类(Employee)的集合属性(ICollection).Fluent Validator文档说要使用:
RuleFor(x => x.Orders).SetCollectionValidator(new OrderValidator()); // example usage
Run Code Online (Sandbox Code Playgroud)
但是,我的版本上没有SetCollectionValidator()方法.相反,只有SetValidator()被标记为[已弃用].我已经看到有关同样情况的其他帖子,并了解到SetCollectionValidator()是一个扩展方法,需要确保我已导入FluentValidation.我做.
我在这里错过了什么?
using FluentValidation;
using FluentValidation.Validators;
public class EmployeeValidator : AbstractValidator<Employee>
{
public EmployeeValidator()
{
// SetCollectionValidator doesn't show in intellisense and won't compile
RuleFor(e => e.PhoneNumbers).SetCollectionValidator(new PhoneValidator());
}
}
public class PhoneValidator : AbstractValidator<Phone>
{
public PhoneValidator()
{
RuleFor(e => e.Number).Length(10).Matches("^[0-9]$");
}
}
Run Code Online (Sandbox Code Playgroud) 如何在派生类型的集合项上设置验证器?
class BaseClass
{
}
class DerivedClass : BaseClass
{
}
class SomeClass
{
public IEnumerable<BaseClass> BaseClasses { get; set; }
}
class DerivedClassValidator : AbstractValidator<DerivedClass>
{
}
class SomeClassValidator : AbstractValidator<SomeClass>
{
public SomeClassValidator()
{
RuleFor(x => x.BaseClasses).????.SetCollectionValidator(new DerivedClassValidator);
}
}
Run Code Online (Sandbox Code Playgroud)
就是想...
有没有一种方法可以将其转换为特定类型,例如
RuleFor(x => x.SomeCollection).CastTo(typeof(SomeDerivedType)).SetCollectionValidator(new SomeDerivedValidator());
Run Code Online (Sandbox Code Playgroud) 现在我已经将我的验证器连接起来并在我的应用程序中构建,但每次我们添加一个新的验证器时,我们需要手动进入我们的Unity配置并注册该类型.我想自动执行此操作,就像这篇博文描述使用StructureMap一样,仅适用于Unity.
现在我有这样的事情:
// in global.asax.cs
protected void Application_Start(Object sender, EventArgs e)
{
// some irrelevant registrations (area registrations, route config, etc)
var container = new UnityContainer();
UnityConfig.RegisterComponents(container);
FluentValidationModelValidatorProvider.Configure(c => c.ValidatorFactory = new UnityValidatorFactory(container));
}
public class UnityValidatorFactory : ValidatorFactoryBase
{
private readonly IUnityContainer container;
public UnityValidatorFactory(IUnityContainer container)
{
this.container = container;
}
public override IValidator CreateInstance(Type validatorType)
{
if (container.IsRegistered(validatorType))
{
return container.Resolve(validatorType) as IValidator;
}
return null;
}
}
public static class UnityConfig
{
public static void …Run Code Online (Sandbox Code Playgroud) 我有这两个实体:
public class Parent
{
public ICollection<Child> Children {get; set;}
}
public class Child
{
public decimal Percentage {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
我想添加验证规则,以便Percentage所有子项的总数为100.如何在以下验证器中添加此规则?
public ParentValidator()
{
RuleFor(x => x.Children).SetCollectionValidator(new ChildValidator());
}
private class ChildValidator : AbstractValidator<Child>
{
public ChildValidator()
{
RuleFor(x => x.Percentage).GreaterThan(0));
}
}
Run Code Online (Sandbox Code Playgroud) 我正在使用SimpleInjector 4和FluentValidation7。我AbstractValidator的依赖于我DbContext。
public class Validator : AbstractValidator<LocationModel>
{
public LocationModelValidator(IReadOnlyRepository repository)
{
// Check the database to see if this location is already present
RuleFor(x => x.LocationId).Must(x => !repository.Location.Any(i => i.LocationId == x)).WithMessage("A Location with this ID already exists.");
}
}
Run Code Online (Sandbox Code Playgroud)
我的合成根看起来如下:
var container = new Container();
container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
container.Register<IReadOnlyRepository, LocationDbContext>(Lifestyle.Scoped);
container.Register<IValidatorFactory>(() => new ServiceProviderValidatorFactory(GlobalConfiguration.Configuration));
container.Register(typeof(IValidator<>), assemblies, Lifestyle.Scoped);
container.RegisterWebApiControllers(GlobalConfiguration.Configuration);
container.Verify();
GlobalConfiguration.Configuration.DependencyResolver =
new SimpleInjectorWebApiDependencyResolver(container);
Run Code Online (Sandbox Code Playgroud)
ValidatorFactory的实现
public class ServiceProviderValidatorFactory : ValidatorFactoryBase
{
private readonly HttpConfiguration …Run Code Online (Sandbox Code Playgroud) 我正在尝试在需要验证并具有FluentValidation提供的验证元数据的表单字段上自动呈现一个红色的星号。
我的工作方式占50%,但是使用When(....子句会引起一些问题。
一个简化的示例是:标记助手
public class NjordInputTagHelper : TagHelper
{
public override void Process(
TagHelperContext context,
TagHelperOutput output)
{
IValidator validator = _factory.GetValidator(For.Metadata.ContainerType);
if (validator == null)
{
return;
}
IValidatorDescriptor description = validator.CreateDescriptor();
IEnumerable<IPropertyValidator> propertyValidators = description.GetValidatorsForMember(For.Metadata.PropertyName);
if ((For.Metadata.ModelType != typeof(bool) && For.Metadata.IsRequired )
//|| propertyValidators.Any(p=> p is NotNullValidator || p is NotEmptyValidator )
)
{
//insert asterisk
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的验证人
public class MyValidator: AbstractValidator<MyModel>
{
public MyValidator()
{
When(x=>x.MyPropertyA != null, () =>
{
RuleFor(x=> x.MyPropertyB).NotEmpty(); …Run Code Online (Sandbox Code Playgroud) fluentvalidation ×10
c# ×5
asp.net-mvc ×4
validation ×3
.net ×2
asp.net ×2
.net-core ×1
ninject ×1
regex ×1