标签: custom-validators

如何在自定义验证方法中使用现有的Rails验证器?

我想在模型中创建自定义验证方法,并在自定义验证方法中使用一些现有的验证器(特别是validates_numericality_of)。

这可能吗?如果是这样,我该怎么办?

在某些情况下:我们使用的非ActiveRecord ORM的属性为哈希。我想对哈希内的东西执行验证。如果有办法做到这validates_numericality_of :my_attribute.:subattribute一点,那也可以。

谢谢。

validation custom-validators ruby-on-rails-4

6
推荐指数
1
解决办法
843
查看次数

在方法中使用@AssertTrue时,该方法在验证期间被调用4次(Bean Validation)

@AssertTrue当使用bean验证来验证对象的状态时,每当调用验证时,使用注释的方法就会被调用4次。每次调用只应调用一次。

Hibernate 验证器版本:5.1.3.Final

这是一个例子:

对于以下类别的摩托车:

import javax.validation.constraints.AssertTrue;
class Motorcycle{
    private int fuel;
    private int tireDurability;

    @AssertTrue(message = "motorcycle.not.available.to.use")
    public boolean isAvailable(){
        return fuel > 0 && tireDurability > 0;
    }

    public void toUse(){...}
}
Run Code Online (Sandbox Code Playgroud)

以及主要的:

import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
public class Main{
    public static void main(String []args){
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();

        Set<ConstraintViolation<Motorcycle>> violations = validator.validate(new Motorcycle());

    }
}
Run Code Online (Sandbox Code Playgroud)

validator.validate(new Motorcycle())调用时,该方法isAvailable()被调用4次。

任何人都可以帮助我解决这种情况吗?这是一个错误吗?我该如何解决这个问题?

java validation custom-validators hibernate-validator bean-validation

6
推荐指数
1
解决办法
3567
查看次数

多个自定义验证器,其反应形式为角度2

我有两个自定义validatorreactive form,我叫下面的函数来创建组件构造函数形式:

private createForm(): void {
this.passwordUpdateForm = this.formBuilder.group({
    newpassword : [null, Validators.required],
    passwordconfirm: [null, Validators.required]
},
{
    validator: [PasswordValidation.PasswordMatch, PasswordValidation.PasswordRule] // validation method

});
Run Code Online (Sandbox Code Playgroud)

}

PasswordValidation是一个具有以下两个功能的类

    export class PasswordValidation {

     public  static PasswordMatch(control: AbstractControl) {
        let password = control.get('newpassword'); // to get value in input tag
        if(password){
            let confirmPassword = control.get('passwordconfirm').value; // to get value in input tag
            if (password.value !== confirmPassword) {
                control.get('passwordconfirm').setErrors({ ['passwordmatch'] : true});
            }else {
                return null;
            }
        }
    } …
Run Code Online (Sandbox Code Playgroud)

custom-validators angular-validation angular angular-reactive-forms angular-forms

6
推荐指数
1
解决办法
6199
查看次数

Angular4:尽管字段中没有错误,表单无效(使用自定义验证)

我正在尝试使用自定义验证来验证表单.出于某种原因,我必须构建一个可以更改电子邮件或设置新密码的表单.出于这个原因,我不能使用Validators.required,因为密码字段只有在被触摸时才需要.

我的问题是,当解决输入验证时,表单仍然无效.

我做了一个plnkr来证明我的问题:http://plnkr.co/edit/obF4gC5RHkXOOlCEsIuH?p = preview

ngOnInit(): void {
    this.emailField = new FormControl('mail@mail.com', Validators.email);
    this.pw1 = new FormControl('', [this.passwordAreEqualValidator, Validators.minLength(2)]);
    this.pw2 = new FormControl('', this.passwordAreEqualValidator);
    this.pwOld = new FormControl('', this.notEmptyIfNewIsTouchedValidator);

    this.form = this.formBuilder.group({
      pw1: this.pw1,
      pw2: this.pw2,
      emailField: this.emailField,
      pwOld: this.pwOld
    });
  }

notEmptyIfNewIsTouchedValidator(control: FormControl) : ValidationErrors | null {
    if (control.dirty) {
      if (control.value === '') {
        return {
          oldPasswordEmpty: true
        }
      }

      const parent = control.parent,
            pw1 = parent.get('pw1'),
            pw2 = parent.get('pw2');

      // this will trigger nothing …
Run Code Online (Sandbox Code Playgroud)

custom-validators angular

6
推荐指数
1
解决办法
1155
查看次数

在错误文本中禁止"base"以自定义Rails嵌套属性的验证

我有以下型号:

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)

custom-validators nested-attributes ruby-on-rails-3

5
推荐指数
1
解决办法
1761
查看次数

为什么 JSR303 自定义注解的约束组必须默认为空数组?

我正在为特定约束组(不是默认值)编写自定义验证器,但运行时给了我以下错误。

我只是好奇为什么他们需要默认值为空。感谢您能分享您的意见。谢谢 :)

xxx.model.validation.CustomValidation包含Constraint注解,但是groups参数默认值不是空数组。

StackTrace: org.hibernate.validator.metadata.ConstraintHelper.assertGroupsParameterExists(ConstraintHelper.java:335) org.hibernate.validator.metadata.ConstraintHelper.isConstraintAnnotation(ConstraintHelper.java:282)

custom-validators bean-validation

5
推荐指数
1
解决办法
4184
查看次数

如何在自定义 jsr 303 验证中设置 FieldError 字段

我正在春天创建一个网络服务。我有一个 Params DTO,它嵌套在我的 OtherParentDTO 中。每个请求可能只包含 params Dto 中的某些字段。如果字段存在,那么我需要进行验证(基本上是空检查)。在自定义验证器中,我将指定需要针对特定​​请求验证哪些字段。我的问题是在控制器中,错误字段作为参数返回。有没有办法将其更改为 params.customerId 或 parmas.userId。

更新客户需求:

{"params":{"customerId" : "b2cab997-df13-4cb0-8f67-4357b019bb96"}, "客户":{}}

更新用户要求:

{"params":{"userId" : "b2cab997-df13-4cb0-8f67-4357b019bb96"}, "用户":{}}

@JsonSerialize(include = Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class Params {

    private String customerId;
    private String userId;

    //setter and getter are there
}

public class UpdateCustomerRequestDTO {

    @NotNull
    @IsValid(params = {"customerId"}) 
    protected Params params;
    @NotNull @Valid
    private Customer customer;
}

public class UpdateUserRequestDTO {

    @NotNull
    @IsValid(params = {"userId"}) 
    protected Params params;
    @NotNull @Valid
    private User user;
}
Run Code Online (Sandbox Code Playgroud)

自定义约束验证器

@Constraint(validatedBy = …
Run Code Online (Sandbox Code Playgroud)

spring-mvc custom-validators jsr bean-validation

5
推荐指数
0
解决办法
1749
查看次数

使用 Minitest 测试自定义验证器

我有多个带有电子邮件验证的模型。因此,我已将验证提取到自定义验证器中。我按照Rails Guides的教程进行了修改。

class EmailValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
      record.errors[attribute] << (options[:message] || "is not an email")
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

到现在为止还挺好。但是由于我已经将电子邮件验证的功能提取到了它自己的范围内,所以我也想单独测试它。我不想为每个模型添加相同的电子邮件格式测试。

我发现了另一个问题,它也问了同样的问题,但对于 RSpec。但是由于我还没有使用过存根和模拟,我不知道如何将测试移植到 Minitest 测试中。我还没有找到任何使用 Minitest 测试自定义验证器的资源。

有谁知道如何在 Minitest 中为自定义验证器编写此类测试(不使用规范!)?

validation unit-testing ruby-on-rails custom-validators minitest

5
推荐指数
1
解决办法
1734
查看次数

vee-validate自定义验证规则不起作用

版本:

  • VueJs:2.2.6
  • Vee-Validate:^ 2.0.0-beta.25

描述:

我正在开发一个项目,我使用laravel-vue-starter 作为基本模板.

我想使用自定义验证密码.所以我用代码创建了一个resources\assets\_js\validators\passwordValidators.js文件:

import { Validator } from 'vee-validate';

Validator.extend('password', {
    getMessage: field => 'Insert a strong password, it should contain Uppercase letter, lowercase letter, number and special character',
    validate: value => /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.[\W]).{8,}$/.test(value)
});
Run Code Online (Sandbox Code Playgroud)

但是当我添加v-validate="'password'" 它时会产生错误[vee-validate] No such validator 'password' exists

任何帮助将不胜感激.

custom-validators vuejs2

5
推荐指数
1
解决办法
4569
查看次数

Angular 表单自定义验证器 null 返回不会从表单中删除错误

所以我创建了一个自定义验证器来验证确认密码输入是否与原始条目匹配。工作正常。但是,我允许这两个字段都为空,因为这是在某人可以在其设置中更改密码的页面上,当然他们可能不想这样做。如果两者都为空白,则表单应该有效,以便可以提交,并且可以为他们的个人资料更新其他设置,但发生了一些奇怪的事情。

表格道具:

passControl = new FormControl('', [
  FormValidation.checkPasswordStrength()
]);

passConfirmControl = new FormControl('', [
]);

profileForm = new FormGroup(
  {
    password: this.passControl,
    passwordConfirm: this.passConfirmControl
  },
  {
    validators: FormValidation.checkPasswordsMatch()
  }
);
Run Code Online (Sandbox Code Playgroud)

这是我的验证功能:

static checkPasswordsMatch(): ValidatorFn {
  return (control: AbstractControl): {[key: string]: any} => {
    let passwordCtrl = control.get('password');
    let passwordConfirmCtrl = control.get('passwordConfirm');

    // allow blank for when they don't want to change password
    if (passwordCtrl.value === '' && passwordConfirmCtrl.value === '') {
      console.log('both are blank');
      return null;
    }

    if (passwordCtrl.value !== …
Run Code Online (Sandbox Code Playgroud)

javascript custom-validators typescript angular angular-reactive-forms

5
推荐指数
1
解决办法
9705
查看次数