Search in sources :

Example 1 with Validator

use of jakarta.validation.Validator in project spring-framework by spring-projects.

the class ValidatorFactoryTests method testSimpleValidationWithCustomProvider.

@Test
public void testSimpleValidationWithCustomProvider() {
    LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
    validator.setProviderClass(HibernateValidator.class);
    validator.afterPropertiesSet();
    ValidPerson person = new ValidPerson();
    Set<ConstraintViolation<ValidPerson>> result = validator.validate(person);
    assertThat(result.size()).isEqualTo(2);
    for (ConstraintViolation<ValidPerson> cv : result) {
        String path = cv.getPropertyPath().toString();
        assertThat(path).matches(actual -> "name".equals(actual) || "address.street".equals(actual));
        assertThat(cv.getConstraintDescriptor().getAnnotation()).isInstanceOf(NotNull.class);
    }
    Validator nativeValidator = validator.unwrap(Validator.class);
    assertThat(nativeValidator.getClass().getName().startsWith("org.hibernate")).isTrue();
    assertThat(validator.unwrap(ValidatorFactory.class)).isInstanceOf(HibernateValidatorFactory.class);
    assertThat(validator.unwrap(HibernateValidatorFactory.class)).isInstanceOf(HibernateValidatorFactory.class);
    validator.destroy();
}
Also used : ConstraintViolation(jakarta.validation.ConstraintViolation) Validator(jakarta.validation.Validator) ConstraintValidator(jakarta.validation.ConstraintValidator) HibernateValidator(org.hibernate.validator.HibernateValidator) Test(org.junit.jupiter.api.Test)

Example 2 with Validator

use of jakarta.validation.Validator in project wicket by apache.

the class PropertyValidator method validate.

@SuppressWarnings("unchecked")
@Override
public void validate(IValidatable<T> validatable) {
    BeanValidationContext config = BeanValidationConfiguration.get();
    Validator validator = config.getValidator();
    Property property = getProperty();
    // validate the value using the bean validator
    Set<?> violations = validator.validateValue(property.getOwner(), property.getName(), validatable.getValue(), getGroups());
    for (ConstraintViolation<?> violation : (Set<ConstraintViolation<?>>) violations) {
        validatable.error(config.getViolationTranslator().convert(violation));
    }
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) Validator(jakarta.validation.Validator) INullAcceptingValidator(org.apache.wicket.validation.INullAcceptingValidator)

Example 3 with Validator

use of jakarta.validation.Validator in project wicket by apache.

the class PropertyValidator method onComponentTag.

@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public void onComponentTag(Component component, ComponentTag tag) {
    super.onComponentTag(component, tag);
    BeanValidationContext config = BeanValidationConfiguration.get();
    Validator validator = config.getValidator();
    Property property = getProperty();
    // find any tag modifiers that apply to the constraints of the property
    // being validated
    // and allow them to modify the component tag
    Iterator<ConstraintDescriptor<?>> it = new ConstraintIterator(validator, property, getGroups());
    while (it.hasNext()) {
        ConstraintDescriptor<?> desc = it.next();
        ITagModifier modifier = config.getTagModifier(desc.getAnnotation().annotationType());
        if (modifier != null) {
            modifier.modify((FormComponent<?>) component, tag, desc.getAnnotation());
        }
    }
}
Also used : ConstraintDescriptor(jakarta.validation.metadata.ConstraintDescriptor) Validator(jakarta.validation.Validator) INullAcceptingValidator(org.apache.wicket.validation.INullAcceptingValidator)

Example 4 with Validator

use of jakarta.validation.Validator in project wicket by apache.

the class DefaultPropertyResolverTest method testBundleKeysResolution.

/**
 * Test custom bundle mechanism of jsr 303
 *
 * https://issues.apache.org/jira/browse/WICKET-5654
 *
 * @throws Exception
 */
@Test
void testBundleKeysResolution() throws Exception {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    DefaultViolationTranslator translator = new DefaultViolationTranslator();
    // test with a too short password
    BeanWithPassword bean = new BeanWithPassword("short");
    Set<ConstraintViolation<BeanWithPassword>> constraintViolations = validator.validate(bean);
    assertEquals(1, constraintViolations.size());
    @SuppressWarnings("unchecked") ConstraintViolation<BeanWithPassword> shortViolation = (ConstraintViolation<BeanWithPassword>) constraintViolations.toArray()[0];
    ValidationError error = translator.convert(shortViolation);
    checkErrorBundleKeys(error, DEFAULT_BUNDLE_KEY + ".String", DEFAULT_BUNDLE_KEY);
    // test with a password containing non-word chars
    bean.setPassword("notWord&%$£");
    constraintViolations = validator.validate(bean);
    assertEquals(1, constraintViolations.size());
    @SuppressWarnings("unchecked") ConstraintViolation<BeanWithPassword> nonWordviolation = (ConstraintViolation<BeanWithPassword>) constraintViolations.toArray()[0];
    error = translator.convert(nonWordviolation);
    checkErrorBundleKeys(error, CUSTOM_BUNDLE_KEY + ".String", CUSTOM_BUNDLE_KEY, DEFAULT_BUNDLE_KEY + ".String", DEFAULT_BUNDLE_KEY);
    // test with a valid password
    bean.setPassword("aValidPassword1234");
    constraintViolations = validator.validate(bean);
    assertEquals(0, constraintViolations.size());
}
Also used : ValidatorFactory(jakarta.validation.ValidatorFactory) ConstraintViolation(jakarta.validation.ConstraintViolation) ValidationError(org.apache.wicket.validation.ValidationError) Validator(jakarta.validation.Validator) Test(org.junit.jupiter.api.Test)

Example 5 with Validator

use of jakarta.validation.Validator in project hibernate-orm by hibernate.

the class BeanValidationEventListener method validate.

private <T> void validate(T object, RepresentationMode mode, EntityPersister persister, SessionFactoryImplementor sessionFactory, GroupsPerOperation.Operation operation) {
    if (object == null || mode != RepresentationMode.POJO) {
        return;
    }
    TraversableResolver tr = new HibernateTraversableResolver(persister, associationsPerEntityPersister, sessionFactory);
    Validator validator = factory.usingContext().traversableResolver(tr).getValidator();
    final Class<?>[] groups = groupsPerOperation.get(operation);
    if (groups.length > 0) {
        final Set<ConstraintViolation<T>> constraintViolations = validator.validate(object, groups);
        if (constraintViolations.size() > 0) {
            Set<ConstraintViolation<?>> propagatedViolations = CollectionHelper.setOfSize(constraintViolations.size());
            Set<String> classNames = new HashSet<>();
            for (ConstraintViolation<?> violation : constraintViolations) {
                LOG.trace(violation);
                propagatedViolations.add(violation);
                classNames.add(violation.getLeafBean().getClass().getName());
            }
            StringBuilder builder = new StringBuilder();
            builder.append("Validation failed for classes ");
            builder.append(classNames);
            builder.append(" during ");
            builder.append(operation.getName());
            builder.append(" time for groups ");
            builder.append(toString(groups));
            builder.append("\nList of constraint violations:[\n");
            for (ConstraintViolation<?> violation : constraintViolations) {
                builder.append("\t").append(violation.toString()).append("\n");
            }
            builder.append("]");
            throw new ConstraintViolationException(builder.toString(), propagatedViolations);
        }
    }
}
Also used : TraversableResolver(jakarta.validation.TraversableResolver) ConstraintViolation(jakarta.validation.ConstraintViolation) ConstraintViolationException(jakarta.validation.ConstraintViolationException) Validator(jakarta.validation.Validator) HashSet(java.util.HashSet)

Aggregations

Validator (jakarta.validation.Validator)413 Test (org.testng.annotations.Test)340 ConstraintViolation (jakarta.validation.ConstraintViolation)258 HibernateValidator (org.hibernate.validator.HibernateValidator)215 TestForIssue (org.hibernate.validator.testutil.TestForIssue)181 ConstraintValidator (jakarta.validation.ConstraintValidator)114 ValidatorUtil.getValidator (org.hibernate.validator.testutils.ValidatorUtil.getValidator)88 ValidatorFactory (jakarta.validation.ValidatorFactory)79 ConstraintMapping (org.hibernate.validator.cfg.ConstraintMapping)71 HibernateValidatorConfiguration (org.hibernate.validator.HibernateValidatorConfiguration)43 Test (org.junit.Test)38 ExecutableValidator (jakarta.validation.executable.ExecutableValidator)33 ConstraintViolationException (jakarta.validation.ConstraintViolationException)32 NotNullDef (org.hibernate.validator.cfg.defs.NotNullDef)28 SizeDef (org.hibernate.validator.cfg.defs.SizeDef)27 NotNull (jakarta.validation.constraints.NotNull)26 Path (jakarta.validation.Path)19 Size (jakarta.validation.constraints.Size)18 CountValidationCallsValidator (org.hibernate.validator.testutil.CountValidationCallsValidator)17 List (java.util.List)13