我想在下表中进行一些模型级验证:
create_table :audios do |t|
t.integer :library_id, :null => false
t.string :file, :null => false, :limit => 2048
t.string :name, :limit => 512
t.timestamps
end
Run Code Online (Sandbox Code Playgroud)
这是否意味着,我的模型,(到目前为止)看起来像:
class Audio < ActiveRecord::Base
belongs_to :library
end
Run Code Online (Sandbox Code Playgroud)
具有
class Audio < ActiveRecord::Base
validates_presence_of :library
...
Run Code Online (Sandbox Code Playgroud)
要么
class Audio < ActiveRecord::Base
validates_presence_of :library_id
...
Run Code Online (Sandbox Code Playgroud)
?
我正在尝试验证一些用户联系方式,如下所示:
public class Customer
{
[Display(Name = "Your e-mail :")]
[Required(ErrorMessage = "An email address is required")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string ContactEmail { get; set; }
[Display(Name = "Your contact number :")]
[Required(ErrorMessage = "A phone number is required")]
[Phone(ErrorMessage = "Invalid Phone Number")]
public string ContactNumber { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
在我看来,电子邮件验证效果很好,并且只允许有效的电子邮件地址。但是,电话验证根本不起作用,它允许各种字母和特殊字符。
文档指出PhoneAttribute该类
使用电话号码的正则表达式指定数据字段值是格式正确的电话号码
那么为什么这没有发生呢?
我知道针对其他框架和语言多次询问这个问题,但我想知道一旦模型验证在 ASP.NET Core 2.1 中出现第一个错误,我如何才能真正停止模型验证?
[Required(ErrorMessage = Email.requiredErrorMessage)]
[DataType(DataType.EmailAddress, ErrorMessage = Email.formatErrorMessage)]
[StringLength(Email.maximumLength, MinimumLength = Email.minimumLength, ErrorMessage = Email.rangeErrorMessage)]
[EmailExists(ErrorMessage = Email.doesNotExistsMessage)]
public string email { get; set; }
[Required(ErrorMessage = ConfirmationCode.requiredErrorMessage)]
[RegularExpression(ConfirmationCode.regularExpression, ErrorMessage = ConfirmationCode.formatErrorMessage)]
public string confirmationCode { get; set; }
Run Code Online (Sandbox Code Playgroud)
上面的代码是 API 模型验证,在发出补丁请求时,我收到以下响应:
"email":[
"This email does not exist in database"
],
"confirmationCode":[
"Confirmation code format is invalid"
]
}
Run Code Online (Sandbox Code Playgroud)
我不希望模型验证在确保数据库中不存在电子邮件时继续,只需返回该错误并且不再继续验证。
我有一个DbContext像这样的基类
public abstract class DbContextBase : DbContext
{
public DbContextBase()
{
}
public DbContextBase(DbContextOptions options)
: base(options)
{
}
public override int SaveChanges()
{
this.ValidateEntities();
return base.SaveChanges();
}
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken))
{
this.ValidateEntities();
return base.SaveChangesAsync(cancellationToken);
}
public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken))
{
this.ValidateEntities();
return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
}
protected virtual void ValidateEntities()
{
var entities = this.ChangeTracker.Entries().
Where(s => s.State == EntityState.Added || s.State == EntityState.Modified);
foreach (var entity in entities) …Run Code Online (Sandbox Code Playgroud) 我正在使用 keras 实现 CNN 来执行图像分类,并且我使用 .fit_generator() 方法来训练模型,直到验证停止条件为止我使用了下一个代码:
history_3conv = cnn3.fit_generator(train_data,steps_per_epoch = train_data.n // 98, callbacks = [es,ckpt_3Conv],
validation_data = valid_data, validation_steps = valid_data.n // 98,epochs=50)
Run Code Online (Sandbox Code Playgroud)
停止前的最后两个纪元是下一个:
如图所示,最后的训练准确率为 0.91。然而,当我使用model.evaluate()方法来评估训练、测试和验证集时,我得到了下一个结果:
所以,我的问题是:为什么我有两个不同的值?
我应该使用吗evaluate_generator()?或者我应该修复seed知道flow_from_directory()要执行数据增强我使用了下一个代码:
trdata = ImageDataGenerator(rotation_range=90,horizontal_flip=True)
vldata = ImageDataGenerator()
train_data = trdata.flow(x_train,y_train,batch_size=98)
valid_data = vldata.flow(x_valid,y_valid,batch_size=98)
Run Code Online (Sandbox Code Playgroud)
此外,我知道use_multiprocessing=Falsefit_generator 中的设置会让我显着减慢训练速度。那么你认为最好的解决方案是什么
我有一个自定义验证属性,当我通过POST向服务器发出请求时,会在属性上触发两次IsValid方法.
它导致返回的错误消息被复制.
我已经使用Fiddler检查过请求只被触发一次,因此情况是1请求模型绑定触发两次.
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class MinimumAgeAttribute : ValidationAttribute
{
private readonly int _minimumAge;
public MinimumAgeAttribute(int minimumAge)
{
_minimumAge = minimumAge;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
DateTime date;
if (DateTime.TryParse(value.ToString(), out date))
{
if (date.AddYears(_minimumAge) < DateTime.Now)
{
return ValidationResult.Success;
}
}
return new ValidationResult("Invalid Age, Clients must be 18 years or over");
}
}
Run Code Online (Sandbox Code Playgroud) c# asp.net model-validation validationattribute asp.net-web-api2
我有一个.Net Core 2.0 Web Api.我有各种具有属性验证属性的模型:
[Required]
public short? Quantity { get; set; }
Run Code Online (Sandbox Code Playgroud)
我有一个ActionFilter来检查模型状态:
if (!context.ModelState.IsValid)
context.Result = new BadRequestObjectResult(context.ModelState);
Run Code Online (Sandbox Code Playgroud)
无论我做什么,当我故意省略所需的属性时,ModelState总是返回有效.我的控制器标记为:
[Produces("application/json")]
Run Code Online (Sandbox Code Playgroud)
模型正在反序列化,我的动作方法中的模型参数标有[FromBody].它似乎没有运行任何验证(标准或自定义).我已经看过这个答案以及这一个和其他几个但我无法弄清楚我错过了什么.我的API受IdenityServer 4保护,因此不确定是否会影响它,但此时我必须自己验证每个动作方法,这不是我想要做的.有人有建议吗?
如何在.NET Core中实现RequiredIf条件操作以进行基于模型的验证。
在 ASP.NET MVC 中,已与 ExpressiveAnnotation 包一起使用,但它不适用于 .NET Core。
model-validation expressiveannotations asp.net-core-2.1 .net-core-3.0
我对本文中的多态绑定示例进行了一些更改。
[Required]属性。CPUIndexScreenSizeLaptopSmartPhone到目前为止还可以。
现在添加新类:
public class DeviceWrapper
{
public Device Device { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
并修改AddDevice.cshtml.cs文件:
...
[BindProperty]
public DeviceWrapper Device { get; set; } // model type changed here
public IActionResult OnPost()
{
if (!ModelState.IsValid)
{
return Page();
}
switch (Device.Device) // added Device. prefix to respect new model structure
{
case Laptop laptop:
Message = $"You added a Laptop with …Run Code Online (Sandbox Code Playgroud) 以下代码有什么问题?
(function(){
window.App = {
Models: {},
Collections: {},
Views: {}
};
window.template = function(id) {
return _.template($('#' + id).html());
};
App.Models.Task = Backbone.Model.extend({
defaults:{
title: '',
priority: 0
},
validate: function(attrs, options){
if (attrs.priority < 0){
return 'Priority cannot be negative.';
}
}
});
var task = new App.Models.Task ({ title: 'Sample Task', priority: 5 });
task.on('invalid', function(model, error) { console.log(error); })
task.save({ priority: -9 }); // Should not pass validation
console.log(task.validationError); // Prints a validation error
console.log(task.toJSON()); // …Run Code Online (Sandbox Code Playgroud) 我在我的 api 控制器类之一中使用以下 DTO 类,在一个 asp.net 核心应用程序中。
public class InviteNewUserDto: IValidatableObject
{
private readonly IClientRepository _clientRepository;
public InviteNewUserDto(IClientRepository clientRepository)
{
_clientRepository = clientRepository;
}
//...code omitted for brevity
}
Run Code Online (Sandbox Code Playgroud)
这就是我在控制器中使用它的方式
[HttpPost]
public async Task<IActionResult> RegisterUser([FromBody] InviteNewUserDto model)
{
if (!ModelState.IsValid) return BadRequest(ModelState);
//...omitted for brevity
}
Run Code Online (Sandbox Code Playgroud)
但是我System.NullReferenceException在 DTO 类中得到了一个这是因为依赖注入在 DTO 类中不起作用。我怎样才能解决这个问题 ?
dependency-injection model-validation ivalidatableobject asp.net-core
据我了解,值类型隐式具有[Required]属性 whenMvcOptions.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes设置为false。但坦率地说,当我在两者之间切换时,我看不出有什么区别。
此外,如果我[Required]在不可空类型(例如 an )上显式使用该属性int,则需要我设置其值,而不是仅在没有给定int参数的情况下命中端点,该参数将为其类型分配默认值- 0.
所以,总结一下:
如果它隐式添加[Required]属性,为什么显式变体提供完全不同的功能?
启用/禁用有任何功能差异吗MvcOptions.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes?据我所知,它没有改变任何东西。
c# model-view-controller model-validation data-annotations asp.net-core
我想在绑定到模型值的 blazor 编辑表单中有一个 InputSelect,并且还有一个 onchange 事件,该事件根据新值更改模型中的其他属性。
绑定到 @bind-Value 和 @onchange 不起作用(我猜是因为绑定值同时使用输入的值和值更改属性。
我可以绑定到 oninput,但我想知道是否有更好的方法来做到这一点。
<InputSelect id="inputPeriod" name="inputPeriod" class="form-control" @bind-Value="model.Period" @oninput="periodChanged">
protected void periodChanged(ChangeEventArgs e)
{}
Run Code Online (Sandbox Code Playgroud)
我可以像这样绑定到 oninput
但理想情况下,我想在更新模型属性后绑定到 @onchange 事件,或者知道最佳实践是什么。如果不使用绑定值,模型验证将无法工作,所以我能想到的唯一替代方法是让更改事件在我的模型中的属性内工作,但这似乎是错误的
model-validation ×13
c# ×6
asp.net-core ×3
asp.net ×1
asp.net-mvc ×1
backbone.js ×1
blazor ×1
ef-core-2.1 ×1
keras ×1
models ×1
onchange ×1
python ×1
tensorflow ×1