我有以下型号:
class Evaluation < ActiveRecord::Base
attr_accessible :product_id, :description, :evaluation_institutions_attributes
has_many :evaluation_institutions, :dependent => :destroy
accepts_nested_attributes_for :evaluation_institutions, :reject_if => lambda { |a| a[:token].blank? }, :allow_destroy => true
validate :requires_at_least_one_institution
private
def requires_at_least_one_institution
if evaluation_institution_ids.nil? || evaluation_institution_ids.length == 0
errors.add_to_base("Please select at least one institution")
end
end
end
class EvaluationInstitution < ActiveRecord::Base
attr_accessible :evaluation_institution_departments_attributes, :institution_id
belongs_to :evaluation
has_many :evaluation_institution_departments, :dependent => :destroy
accepts_nested_attributes_for :evaluation_institution_departments, :reject_if => lambda { |a| a[:department_id].blank? }, :allow_destroy => true
validate :requires_at_least_one_department
private
def requires_at_least_one_department
if evaluation_institution_departments.nil? || …Run Code Online (Sandbox Code Playgroud) 我为我所包含的代码量道歉.我试图将它保持在最低限度.
我正在尝试在我的模型上使用自定义验证器属性以及自定义模型绑定器.属性和Binder分开工作很好,但如果我同时使用,则验证属性不再有效.
这是我的代码剪切的可读性.如果我省略了global.asax中的代码,则会启动自定义验证,但如果我启用了自定义绑定,则不会触发.
验证属性;
public class IsPhoneNumberAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
//do some checking on 'value' here
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
在我的模型中使用属性;
[Required(ErrorMessage = "Please provide a contact number")]
[IsPhoneNumberAttribute(ErrorMessage = "Not a valid phone number")]
public string Phone { get; set; }
Run Code Online (Sandbox Code Playgroud)
定制模型粘合剂;
public class CustomContactUsBinder : DefaultModelBinder
{
protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
ContactFormViewModel contactFormViewModel = bindingContext.Model as ContactFormViewModel;
if (!String.IsNullOrEmpty(contactFormViewModel.Phone))
if (contactFormViewModel.Phone.Length > 10)
bindingContext.ModelState.AddModelError("Phone", "Phone is too long."); …Run Code Online (Sandbox Code Playgroud) 我正在尝试实现自定义属性验证,类似于ScottGu的博客中所示:http: //weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation. ASPX
我有这个电子邮件的自定义验证器属性:
public class EmailAttribute : RegularExpressionAttribute
{
public EmailAttribute() :
base("^[A-Za-z0-9](([_\\.\\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\\.\\-]?[a-zA-Z0-9]+)*)\\.([A-Za-z]{2,})$") { }
}
Run Code Online (Sandbox Code Playgroud)
我的班级使用它像这样:
[Required(ErrorMessage = ValidationCiM.MsgObaveznoPolje)]
[Email(ErrorMessage = ValidationCiM.MsgMailNeispravan)]
[StringLength(ValidationCiM.LenSrednjePolje, ErrorMessage = ValidationCiM.MsgSrednjePolje)]
public string Mail { get; set; }
Run Code Online (Sandbox Code Playgroud)
它在服务器端运行良好,模型验证正常,以及一切.但客户端验证不会为此激活第二个属性,它适用于Required,它也适用于StringLength但不适用于电子邮件.我试过包括jquery和Microsoft ajax脚本,但似乎没有区别.
在ScottGu的博客中,他声明如果像这样实现的自定义验证应该可以在不需要添加自定义脚本的情况下工作.
有什么想法吗?
asp.net-mvc custom-validators asp.net-mvc-2-validation asp.net-mvc-3
我是Web2py的新手,我正在尝试使用自定义验证器.
class IS_NOT_EMPTY_IF_OTHER(Validator):
def __init__(self, other,
error_message='must be filled because other value '
'is present'):
self.other = other
self.error_message = error_message
def __call__(self, value):
if isinstance(self.other, (list, tuple)):
others = self.other
else:
others = [self.other]
has_other = False
for other in others:
other, empty = is_empty(other)
if not empty:
has_other = True
break
value, empty = is_empty(value)
if empty and has_other:
return (value, T(self.error_message))
else:
return (value, None)
Run Code Online (Sandbox Code Playgroud)
我不明白如何在我的桌子上使用它:
db.define_table('numbers',
Field('a', 'integer'),
Field('b', 'boolean'),
Field('c', 'integer')
Run Code Online (Sandbox Code Playgroud)
我想以这样一种方式使用它,当'b'被勾选时'c'不能留黑.
我正在为 Angular 5 中的反应形式开发一个验证器,并且在设置基于另一个输入的值的验证器时遇到困难。
表格看起来像这样:
let myRules = new FormArray([]);
myRules.push(this.newRuleFormGroup(1, 'period', 1));
this.myForm = new FormGroup({
'name': new FormControl(name, [Validators.required, this.validate_usedName.bind(this)]), // V: must not exist already
'icon': new FormControl(icon, [Validators.required]), // has default
'rules': myRules
})
Run Code Online (Sandbox Code Playgroud)
'rules' 是 a FormArray,我FormGroup使用以下命令从模板中推送 new :
newRuleFormGroup = (amount: number, period: string, repAmount: number = 1) => {
return new FormGroup({
'amount': new FormControl(amount, [Validators.required]),
'type': new FormControl(period, [Validators.required]),
'repAmount': new FormControl(repAmount, [this.validate_repAmount.bind(this)])
})
}
Run Code Online (Sandbox Code Playgroud)
repAmount仅当 时才需要type …
我有两个TextBox控制开始日期和结束日期输入.我必须验证结束日期不大于开始日期,开始日期和结束日期之间的差异不超过12个月.
我们可以在这里阅读如何写:
http://framework.zend.com/manual/en/zend.validate.writing_validators.html
class MyValid_Float extends Zend_Validate_Abstract
{
Run Code Online (Sandbox Code Playgroud)
1) 我们应该把它放在哪里?
应用/默认/验证器?application/view/helpers/...?
2) 我们是否必须在我们的申请表上注册?
更新: 这是我的bootstrap的一个例子:
include_once 'config_root.php';
set_include_path ( $PATH );
require_once 'Initializer.php';
require_once "Zend/Loader.php";
require_once 'Zend/Loader/Autoloader.php';
// Set up autoload.
$loader = Zend_Loader_Autoloader::getInstance ();
$loader->setFallbackAutoloader ( true );
$loader->suppressNotFoundWarnings ( false );
// Prepare the front controller.
$frontController = Zend_Controller_Front::getInstance ();
$frontController->throwExceptions(true);
$frontController->registerPlugin ( new Initializer ( PROJECT_ENV ) );
// Dispatch the request using the front controller.
try {
$frontController->dispatch ();
} catch ( Exception $exp ) {
$contentType …Run Code Online (Sandbox Code Playgroud) 我按照以下Symfony2食谱教程,但我一直收到错误
constraint myContraintClass cannot be put on properties or getters
在validation.yml我有
Core\Entity\Activity:
properties:
maxTotalParticipant:
- Application\ActivityBundle\Validator\ActivityMaxTotalParticipant: ~
Run Code Online (Sandbox Code Playgroud)
这是我的约束
<?php
namespace Application\ActivityBundle\Validator;
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
*/
class ActivityMaxTotalParticipant extends Constraint
{
public $message = 'trigger error';
public function validatedBy() {
return 'activity_max_total_participant_validator';
}
public function getTargets() {
return self::CLASS_CONSTRAINT;
}
public function getMessage() {
return $this->message;
}
}
Run Code Online (Sandbox Code Playgroud)
和我的约束验证器
<?php
namespace Application\ActivityBundle\Validator;
use Symfony\Component\Validator\ExecutionContext;
use Symfony\Bundle\DoctrineBundle\Registry;
use myApp\Core\Entity\Activity;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Translation\Translator;
use Symfony\Component\Translation;
class …Run Code Online (Sandbox Code Playgroud) 我使用了自定义验证.但它不起作用.这是我的模特
class Manufacture extends \yii\db\ActiveRecord
{
public function rules()
{
return [
[['model_no'], 'safe'],
['model_no', 'customValidation', 'skipOnEmpty' => false, 'skipOnError' => false],
];
}
public function customValidation($attribute, $params)
{
if($this->model_no=='test')
{
$this->addError($attribute,'add proper data.');
}
}
}
Run Code Online (Sandbox Code Playgroud)
在控制器中
public function actionCreate()
{
if ($model->load(Yii::$app->request->post())) {
if ($model->validate()) {
//some code
}
}
}
Run Code Online (Sandbox Code Playgroud)
这里我在安全中添加了属性,但我的错误仍然没有在视图中显示.
我将Rails 4与Rails-i18n Gem一起使用,我想用我的语言翻译文件中的占位符替换我的硬编码字符串"300px",如config/locales/de.yml中的%{minimum_resolution}
activerecord:
errors:
models:
organisation:
attributes:
image:
resolution_too_small:"Image Resolution should be at least %{minimum_resolution}"
Run Code Online (Sandbox Code Playgroud)
%{minimum_resolution}中的值应来自app/models/organisation.rb中的自定义验证
def validate_minimum_image_dimensions
if image.present?
logo = MiniMagick::Image.open(image.path)
minimum_resolution = 300
unless logo[:width] > minimum_resolution || logo[:height] > minimum_resolution
errors.add :image, :minimum_image_size
end
else
return false
end
end
Run Code Online (Sandbox Code Playgroud)
如何从minimum_resolution获取值到我的yaml文件中?
asp.net-mvc ×2
activerecord ×1
angular ×1
asp.net ×1
constraints ×1
python ×1
rails-i18n ×1
symfony ×1
validation ×1
web2py ×1