Search in sources :

Example 21 with FieldError

use of org.springframework.validation.FieldError in project spring-boot by spring-projects.

the class RelaxedDataBinderTests method testRequiredFieldsValidation.

@Test
public void testRequiredFieldsValidation() throws Exception {
    TargetWithValidatedMap target = new TargetWithValidatedMap();
    BindingResult result = bind(target, "info[foo]: bar");
    assertThat(result.getErrorCount()).isEqualTo(2);
    for (FieldError error : result.getFieldErrors()) {
        System.err.println(new StaticMessageSource().getMessage(error, Locale.getDefault()));
    }
}
Also used : BindingResult(org.springframework.validation.BindingResult) StaticMessageSource(org.springframework.context.support.StaticMessageSource) FieldError(org.springframework.validation.FieldError) Test(org.junit.Test)

Example 22 with FieldError

use of org.springframework.validation.FieldError in project spring-framework by spring-projects.

the class ValidatorFactoryTests method testSpringValidationWithErrorInSetElement.

@Test
public void testSpringValidationWithErrorInSetElement() throws Exception {
    LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
    validator.afterPropertiesSet();
    ValidPerson person = new ValidPerson();
    person.getAddressSet().add(new ValidAddress());
    BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person");
    validator.validate(person, result);
    assertEquals(3, result.getErrorCount());
    FieldError fieldError = result.getFieldError("name");
    assertEquals("name", fieldError.getField());
    fieldError = result.getFieldError("address.street");
    assertEquals("address.street", fieldError.getField());
    fieldError = result.getFieldError("addressSet[].street");
    assertEquals("addressSet[].street", fieldError.getField());
}
Also used : BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) FieldError(org.springframework.validation.FieldError) Test(org.junit.Test)

Example 23 with FieldError

use of org.springframework.validation.FieldError in project spring-framework by spring-projects.

the class EscapedErrors method escapeObjectError.

@SuppressWarnings("unchecked")
private <T extends ObjectError> T escapeObjectError(T source) {
    if (source == null) {
        return null;
    }
    if (source instanceof FieldError) {
        FieldError fieldError = (FieldError) source;
        Object value = fieldError.getRejectedValue();
        if (value instanceof String) {
            value = HtmlUtils.htmlEscape((String) value);
        }
        return (T) new FieldError(fieldError.getObjectName(), fieldError.getField(), value, fieldError.isBindingFailure(), fieldError.getCodes(), fieldError.getArguments(), HtmlUtils.htmlEscape(fieldError.getDefaultMessage()));
    } else {
        return (T) new ObjectError(source.getObjectName(), source.getCodes(), source.getArguments(), HtmlUtils.htmlEscape(source.getDefaultMessage()));
    }
}
Also used : ObjectError(org.springframework.validation.ObjectError) FieldError(org.springframework.validation.FieldError)

Example 24 with FieldError

use of org.springframework.validation.FieldError in project google-app-engine-jappstart by taylorleese.

the class RegisterController method submit.

/**
     * Handle the create account form submission.
     *
     * @param register the register form bean
     * @param binding the binding result
     * @param request the HTTP servlet request
     * @return the path
     */
@RequestMapping(value = "/create", method = RequestMethod.POST)
public final String submit(@ModelAttribute(REGISTER) @Valid final Register register, final BindingResult binding, final HttpServletRequest request) {
    final Locale locale = localeResolver.resolveLocale(request);
    if (binding.hasErrors()) {
        return "create";
    }
    final UserAccount user = new UserAccount(register.getUsername());
    user.setDisplayName(register.getDisplayName());
    user.setEmail(register.getEmail());
    user.setPassword(passwordEncoder.encodePassword(register.getPassword(), user.getSalt()));
    try {
        userDetailsService.addUser(user, locale);
    } catch (DuplicateUserException e) {
        binding.addError(new FieldError(REGISTER, "username", messageSource.getMessage("create.error.username", null, locale)));
        return "create";
    }
    return "redirect:/register/success";
}
Also used : Locale(java.util.Locale) FieldError(org.springframework.validation.FieldError) UserAccount(com.jappstart.model.auth.UserAccount) DuplicateUserException(com.jappstart.exception.DuplicateUserException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 25 with FieldError

use of org.springframework.validation.FieldError in project ORCID-Source by ORCID.

the class RegistrationController method regEmailValidate.

public Registration regEmailValidate(HttpServletRequest request, Registration reg, boolean isOauthRequest, boolean isKeyup) {
    reg.getEmail().setErrors(new ArrayList<String>());
    if (!isKeyup && (reg.getEmail().getValue() == null || reg.getEmail().getValue().trim().isEmpty())) {
        setError(reg.getEmail(), "Email.registrationForm.email");
    }
    String emailAddress = reg.getEmail().getValue();
    MapBindingResult mbr = new MapBindingResult(new HashMap<String, String>(), "Email");
    // Validate the email address is ok        
    if (!validateEmailAddress(emailAddress)) {
        String[] codes = { "Email.personalInfoForm.email" };
        String[] args = { emailAddress };
        mbr.addError(new FieldError("email", "email", emailAddress, false, codes, args, "Not vaild"));
    } else {
        //If email exists
        if (emailManager.emailExists(emailAddress)) {
            String orcid = emailManager.findOrcidIdByEmail(emailAddress);
            String[] args = { emailAddress };
            //If it is claimed, should return a duplicated exception
            if (profileEntityManager.isProfileClaimedByEmail(emailAddress)) {
                String[] codes = null;
                if (profileEntityManager.isDeactivated(orcid)) {
                    codes = new String[] { "orcid.frontend.verify.deactivated_email" };
                } else {
                    codes = new String[] { "orcid.frontend.verify.duplicate_email" };
                }
                mbr.addError(new FieldError("email", "email", emailAddress, false, codes, args, "Email already exists"));
            } else {
                if (profileEntityManager.isDeactivated(orcid)) {
                    String[] codes = new String[] { "orcid.frontend.verify.deactivated_email" };
                    mbr.addError(new FieldError("email", "email", emailAddress, false, codes, args, "Email already exists"));
                } else if (!emailManager.isAutoDeprecateEnableForEmail(emailAddress)) {
                    //If the email is not eligible for auto deprecate, we should show an email duplicated exception                        
                    String resendUrl = createResendClaimUrl(emailAddress, request);
                    String[] codes = { "orcid.frontend.verify.unclaimed_email" };
                    args = new String[] { emailAddress, resendUrl };
                    mbr.addError(new FieldError("email", "email", emailAddress, false, codes, args, "Unclaimed record exists"));
                } else {
                    LOGGER.info("Email " + emailAddress + " belongs to a unclaimed record and can be auto deprecated");
                }
            }
        }
    }
    for (ObjectError oe : mbr.getAllErrors()) {
        Object[] arguments = oe.getArguments();
        if (isOauthRequest && oe.getCode().equals("orcid.frontend.verify.duplicate_email")) {
            // XXX
            reg.getEmail().getErrors().add(getMessage("oauth.registration.duplicate_email", arguments));
        } else if (oe.getCode().equals("orcid.frontend.verify.duplicate_email")) {
            Object email = "";
            if (arguments != null && arguments.length > 0) {
                email = arguments[0];
            }
            String link = "/signin";
            String linkType = reg.getLinkType();
            if ("social".equals(linkType)) {
                link = "/social/access";
            } else if ("shibboleth".equals(linkType)) {
                link = "/shibboleth/signin";
            }
            reg.getEmail().getErrors().add(getMessage(oe.getCode(), email, orcidUrlManager.getBaseUrl() + link));
        } else if (oe.getCode().equals("orcid.frontend.verify.deactivated_email")) {
            // Handle this message in angular to allow AJAX action
            reg.getEmail().getErrors().add(oe.getCode());
        } else {
            reg.getEmail().getErrors().add(getMessage(oe.getCode(), oe.getArguments()));
        }
    }
    // validate confirm if already field out
    if (reg.getEmailConfirm().getValue() != null) {
        regEmailConfirmValidate(reg);
    }
    return reg;
}
Also used : ObjectError(org.springframework.validation.ObjectError) MapBindingResult(org.springframework.validation.MapBindingResult) FieldError(org.springframework.validation.FieldError)

Aggregations

FieldError (org.springframework.validation.FieldError)25 ObjectError (org.springframework.validation.ObjectError)8 Errors (org.springframework.validation.Errors)7 Test (org.junit.Test)6 BeanPropertyBindingResult (org.springframework.validation.BeanPropertyBindingResult)5 Locale (java.util.Locale)4 BindingResult (org.springframework.validation.BindingResult)4 BigDecimal (java.math.BigDecimal)2 HashMap (java.util.HashMap)2 ConverterException (org.grails.web.converters.exceptions.ConverterException)2 LocalDate (org.joda.time.LocalDate)2 MessageContext (org.springframework.binding.message.MessageContext)2 BindException (org.springframework.validation.BindException)2 DuplicateUserException (com.jappstart.exception.DuplicateUserException)1 UserAccount (com.jappstart.model.auth.UserAccount)1 GrailsApplication (grails.core.GrailsApplication)1 GrailsDomainClass (grails.core.GrailsDomainClass)1 CollectionDataBindingSource (grails.databinding.CollectionDataBindingSource)1 DataBinder (grails.databinding.DataBinder)1 DataBindingSource (grails.databinding.DataBindingSource)1