Java 类org.springframework.validation.Errors 实例源码

项目:happy-news    文件:PasswordValidator.java   
@Override
public void validate(Object target, Errors errors) {
    String password = null;

    if (target instanceof PasswordChangeRequest) {
        password = ((PasswordChangeRequest) target).getPassword();
    } else if (target instanceof String) {
        password = target.toString();
    }

    if (password != null && password.length() < MINIMUM_PASSWORD_LENGTH) {
        errors.rejectValue("password", "field.min.length", new Object[]{MINIMUM_PASSWORD_LENGTH},
            "The password must be at least [" + MINIMUM_PASSWORD_LENGTH + "] characters in length.");
    }

}
项目:Restaurant    文件:CustomerInfoValidator.java   
public void validate(Object target, Errors errors) {
    CustomerInfo custInfo = (CustomerInfo) target;

       ValidationUtils.rejectIfEmptyOrWhitespace(errors, "fName", "NotEmpty.customerForm.fName");
       ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lName", "NotEmpty.customerForm.lName");
       ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "NotEmpty.customerForm.email");
       ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address", "NotEmpty.customerForm.address");
       ValidationUtils.rejectIfEmptyOrWhitespace(errors, "phone", "NotEmpty.customerForm.phone");



       if(!errors.hasErrors() && custInfo.getPhone().length()!=10){
        errors.rejectValue("phone","Length.greater.phone");
       }

       if(!errors.hasErrors() && custInfo.getPhone().contains("[0-9]+")){
        errors.rejectValue("phone","NoCharacater.cusomerForm.phone");
       }


       if (!errors.hasErrors() && !emailValidator.isValid(custInfo.getEmail())) {
           errors.rejectValue("email", "NotValid.customer.email");
       }
}
项目:EventSoft    文件:EventValidator.java   
@Override
public void validate(Object o, Errors errors) {
    Evento evento = (Evento) o;

    if(evento.getNombre().equalsIgnoreCase("")){
        errors.rejectValue("nombre" , "error.evento", "Campo vacio. Rellenalo");
    }
    else if(evento.getLugar().equalsIgnoreCase("")){
        errors.rejectValue("lugar" , "error.evento", "Campo vacio. Rellenalo");
    }
    else if (evento.getDescripcion().equalsIgnoreCase("")) {
        errors.rejectValue("descrpcion" , "error.evento", "Campo vacio. Rellenalo");
    }
    else if(evento.getFechaInicio().after(evento.getFechaFin())) {
        errors.rejectValue("fechaInicio" , "error.evento", "Fecha posterior a la de Fin. Ajustela");
    }
}
项目:SpringTutorial    文件:LogonValidator.java   
@Override
public void validate(Object target, Errors errors) {
    System.out.println("validate(Object target, Errors errors) ");

    System.out.println(target);

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userId",
        "required.userName", "Field name is required.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password",
        "required.password", "Field name is required.");

    System.out.println("validate() : - "+errors);

    Logon logon = (Logon)target;
    if(logon.getPassword()!=null && !(logon.getPassword().equals(logon.getUserId()+"111"))){
        errors.rejectValue("password", "invalid.logon");
        System.out.println("rejected");
    }
    }
项目:SpringTutorial    文件:LogonValidator.java   
@Override
public void validate(Object target, Errors errors) {
    System.out.println("Entered : validate(Object target, Errors errors) ");

    System.out.println("target : " + target);

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userId",
            "required.userName", "Field name is required.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password",
            "required.password", "Field name is required.");
    Logon logon = (Logon) target;

    if("blank".equals(logon.getUserRole())){
        errors.rejectValue("userRole", "required.role");
    }

    if(logon.getDaysCount()==null){
        errors.rejectValue("daysCount", "required.dayscount");
    }

    if (logon.getPassword() != null
            && !(logon.getPassword().equals(logon.getUserId() + "111"))) {
        errors.rejectValue("password", "invalid.logon");
    }
    System.out.println("validate() : - " + errors);
}
项目:spring-filter-based-auth    文件:AuthenticationController.java   
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(@ModelAttribute @Valid RegisterForm form, Errors errors, HttpServletRequest request) {

    if (errors.hasErrors()) {
        return "register";
    }

    User existingUser = userDao.findByUsername(form.getUsername());

    if (existingUser != null) {
        errors.rejectValue("username", "username.alreadyexists", "A user with that username already exists");
        return "register";
    }

    User newUser = new User(form.getUsername(), form.getPassword());
    userDao.save(newUser);
    setUserInSession(request.getSession(), newUser);

    return "redirect:";
}
项目:spring-filter-based-auth    文件:AuthenticationController.java   
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(@ModelAttribute @Valid LoginForm form, Errors errors, HttpServletRequest request) {

    if (errors.hasErrors()) {
        return "login";
    }

    User theUser = userDao.findByUsername(form.getUsername());
    String password = form.getPassword();

    if (theUser == null) {
        errors.rejectValue("username", "user.invalid", "The given username does not exist");
        return "login";
    }

    if (!theUser.isMatchingPassword(password)) {
        errors.rejectValue("password", "password.invalid", "Invalid password");
        return "login";
    }

    setUserInSession(request.getSession(), theUser);

    return "redirect:";
}
项目:amv-access-api-poc    文件:UserValidator.java   
@Override
public void validate(Object o, Errors errors) {
    UserEntity user = (UserEntity) o;

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "NotEmpty");
    if (user.getName().length() < 3 || user.getName().length() > 32) {
        errors.rejectValue("username", "Size.userForm.username");
    }
    if (userRepository.findByName(user.getName(), firstPageSingleItemRequest).hasContent()) {
        errors.rejectValue("username", "Duplicate.userForm.username");
    }

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "NotEmpty");
    if (user.getPassword().length() < 3) {
        errors.rejectValue("password", "Size.userForm.password");
    }
}
项目:SmartSync    文件:ServiceAndHouseholdValidator.java   
/**
     * validates the data
     * @param object the household to validate
     * @param errors the errors
     */
    public void validate(Object object, Errors errors) {
        ServiceAndHouseholdDTO serviceAndHouseholdDTO = (ServiceAndHouseholdDTO) object;

        if(serviceAndHouseholdDTO.getServiceId() == null) {
            errors.rejectValue("serviceId", "field.required", "Service ID must not be empty.");
        }

        if(serviceAndHouseholdDTO.getHouseholdId() == null) {
            errors.rejectValue("householdId", "field.required", "Household ID must not be empty.");
        }


//        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userId", "field.required",
//                "User ID must not be empty.");
//
//        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "householdId", "field.required",
//                "Household ID must not be empty.");

    }
项目:SmartSync    文件:UserAndHouseholdValidator.java   
/**
     * validates the data
     * @param object the household to validate
     * @param errors the errors
     */
    public void validate(Object object, Errors errors) {
        UserAndHouseholdDTO userAndHouseholdDTO = (UserAndHouseholdDTO) object;

        if(userAndHouseholdDTO.getUserId() == null) {
            errors.rejectValue("userId", "field.required", "User ID must not be empty.");
        }

        if(userAndHouseholdDTO.getHouseholdId() == null) {
            errors.rejectValue("householdId", "field.required", "Household ID must not be empty.");
        }


//        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userId", "field.required",
//                "User ID must not be empty.");
//
//        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "householdId", "field.required",
//                "Household ID must not be empty.");

    }
项目:amazon-ecs-java-microservices    文件:PetValidator.java   
@Override
public void validate(Object obj, Errors errors) {
    Pet pet = (Pet) obj;
    String name = pet.getName();
    // name validation
    if (!StringUtils.hasLength(name)) {
        errors.rejectValue("name", REQUIRED, REQUIRED);
    }

    // type validation
    if (pet.isNew() && pet.getType() == null) {
        errors.rejectValue("type", REQUIRED, REQUIRED);
    }

    // birth date validation
    if (pet.getBirthDate() == null) {
        errors.rejectValue("birthDate", REQUIRED, REQUIRED);
    }
}
项目:amazon-ecs-java-microservices    文件:PetValidator.java   
@Override
public void validate(Object obj, Errors errors) {
    Pet pet = (Pet) obj;
    String name = pet.getName();
    // name validation
    if (!StringUtils.hasLength(name)) {
        errors.rejectValue("name", REQUIRED, REQUIRED);
    }

    // type validation
    if (pet.isNew() && pet.getType() == null) {
        errors.rejectValue("type", REQUIRED, REQUIRED);
    }

    // birth date validation
    if (pet.getBirthDate() == null) {
        errors.rejectValue("birthDate", REQUIRED, REQUIRED);
    }
}
项目:amazon-ecs-java-microservices    文件:PetValidator.java   
@Override
public void validate(Object obj, Errors errors) {
    Pet pet = (Pet) obj;
    String name = pet.getName();
    // name validation
    if (!StringUtils.hasLength(name)) {
        errors.rejectValue("name", REQUIRED, REQUIRED);
    }

    // type validation
    if (pet.isNew() && pet.getType() == null) {
        errors.rejectValue("type", REQUIRED, REQUIRED);
    }

    // birth date validation
    if (pet.getBirthDate() == null) {
        errors.rejectValue("birthDate", REQUIRED, REQUIRED);
    }
}
项目:amazon-ecs-java-microservices    文件:PetValidator.java   
@Override
public void validate(Object obj, Errors errors) {
    Pet pet = (Pet) obj;
    String name = pet.getName();
    // name validation
    if (!StringUtils.hasLength(name)) {
        errors.rejectValue("name", REQUIRED, REQUIRED);
    }

    // type validation
    if (pet.isNew() && pet.getType() == null) {
        errors.rejectValue("type", REQUIRED, REQUIRED);
    }

    // birth date validation
    if (pet.getBirthDate() == null) {
        errors.rejectValue("birthDate", REQUIRED, REQUIRED);
    }
}
项目:oauth2-shiro    文件:ClientDetailsFormDtoValidator.java   
private void validateClientId(ClientDetailsFormDto clientDetailsDto, Errors errors) {
    final String clientId = clientDetailsDto.getClientId();
    if (StringUtils.isEmpty(clientId)) {
        errors.rejectValue("clientId", null, "client_id is required");
        return;
    }

    if (clientId.length() < 5) {
        errors.rejectValue("clientId", null, "client_id 长度至少5位");
        return;
    }

    boolean existed = oauthService.isExistedClientId(clientId);
    if (existed) {
        errors.rejectValue("clientId", null, "client_id [" + clientId + "] 已存在");
    }

}
项目:SmartSync    文件:HouseholdController.java   
/**
 * Updates the househole information
 * @param updateHouseholdDTO the user information to update
 * @param errors an error container
 * @return the udpated user
 */
@RequestMapping(method = RequestMethod.PUT, value = "/", produces = "application/json")
public ResponseEntity updateHousehold(@RequestBody UpdateHouseholdDTO updateHouseholdDTO, Errors errors) {

    UpdateHouseholdValidator houseValidator = new UpdateHouseholdValidator();
    houseValidator.validate(updateHouseholdDTO, errors);

    ValidationError validationError = ValidationErrorBuilder.fromBindErrors(errors);

    if(errors.hasErrors()) {
        throw new IllegalRequestFormatException("Could not update household.", "/household", validationError);
    }

    Household updatedHousehold= this.householdService.updateHousehold(updateHouseholdDTO);

    return ResponseEntity.ok(updatedHousehold);
}
项目:OperatieBRP    文件:ValidatieUtils.java   
/**
 * Valideer dat een datum (tweedeDatum) na een andere datum (eersteDatum) ligt. Indien een van de datums niet gevuld
 * is, wordt de validatie niet uitgevoerd.
 * @param errors errors object
 * @param eersteDatum eerste datum
 * @param tweedeDatum tweede datum (die na de eerste datum moet liggen)
 * @param veldEersteDatum veld code (voor errors object)
 * @param veldTweedeDatum veld code (voor errors object)
 */
public static void valideerDatumLigtNaDatum(
        final Errors errors,
        final Integer eersteDatum,
        final Integer tweedeDatum,
        final String veldEersteDatum,
        final String veldTweedeDatum) {
    if (eersteDatum != null && tweedeDatum != null) {
        LOG.info(VALIDEER_DATUM_LIGT_NA_DATUM_EERSTE_DATUM_TWEEDE_DATUM, tweedeDatum, eersteDatum);
        valideer(
                errors,
                vulOnbekendeDelenEindDatumAan(tweedeDatum) > eersteDatum,
                veldTweedeDatum,
                VELD_MOETLATERZIJN,
                veldEersteDatum,
                veldTweedeDatum);
    }
}
项目:OperatieBRP    文件:ValidatieUtils.java   
/**
 * Bepaalt of de meegegeven datum geen deels onbekende datumdelen bevat.
 * @param errors errors object
 * @param veldDatum veld code (voor errors object)
 * @param datumInteger De te controleren datum
 */
public static void valideerGeenDeelsOnbekendeDelen(final Errors errors, final Integer datumInteger, final String veldDatum) {

    if (datumInteger != null) {
        // Valideer datum is niet 0
        boolean result = datumInteger != 0;
        final String datum = String.format("%08d", datumInteger);
        // Valideer jaar is niet 0000
        result &= !datum.substring(START_INDEX_JAAR, EIND_INDEX_JAAR).contains(PATROON_ONBEKEND_JAAR);
        // Valideer maand is niet 00
        result &= !datum.substring(START_INDEX_MAAND, EIND_INDEX_MAAND).contains(PATROON_ONBEKEND_MAAND_OF_DAG);
        // Valideer dag is niet 00
        result &= !datum.substring(START_INDEX_DAG).contains(PATROON_ONBEKEND_MAAND_OF_DAG);
        LOG.info(VALIDEER_DATUM_BEVAT_GEEN_ONBEKENDE_DELEN, datumInteger);
        valideer(errors, result, veldDatum, VELD_MAGNIETDEELSONBEKENDZIJN, veldDatum);
    }

}
项目:AntiSocial-Platform    文件:FileValidator.java   
public void validate(Object obj, Errors errors) {

        FileUpload fileUploadModel = (FileUpload) obj;
        MultipartFile file = fileUploadModel.getFile();
        if(file.isEmpty()){
            errors.rejectValue("file", "upload.file.required");
        }
        else if(!PNG_MIME_TYPE_PNG.equalsIgnoreCase(file.getContentType()) && !PNG_MIME_TYPE_JPEG.equalsIgnoreCase(file.getContentType())){
            errors.rejectValue("file", "upload.invalid.file.type");
        }

        else if(file.getSize() > A_MB_IN_BYTES){
            errors.rejectValue("file", "upload.exceeded.file.size");
        }

    }
项目:yum    文件:UsersApiController.java   
@Override
@PreAuthorize("hasAuthority('admin')")
public ResponseEntity<Object> usersIdPut(@ApiParam(value = "", required = true) @PathVariable("id") Long id,
        @ApiParam(value = "The user data to be updated", required = true) @Valid @RequestBody UserSettings user, Errors errors) throws ApiException, Exception {
    if (errors.hasErrors()) {//Check for validation error from UserSettings class(package:model)
        Error error = new Error();
        error.setError("400");
        error.setMessage("Validation Failed");
        System.out.println("" + errors.getAllErrors());
        return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
    }
    try {
        //Call method for update user from class UsersService.
        userService.usersIdPut(user, id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    } catch (OptimisticLockException ex) {
        try {
            User newUserVersion = userService.userIdGet(id);
            throw new ConcurrentModificationException(409, "Concurrent modification error", newUserVersion);    
        } catch (ApiException ex1){
            Logger.getLogger(UsersApiController.class.getName()).log(Level.SEVERE, null, ex1);
            throw new ApiException(500, "Concurrent modification exception: internal error");
        }
    }
}
项目:yum    文件:UsersApiController.java   
@Override
@PreAuthorize("hasAuthority('admin')")
public ResponseEntity<Object> usersPost(@ApiParam(value = "The user to save") @Valid @RequestBody UserReg user, Errors errors) throws ApiException, Exception {
    if (errors.hasErrors()) { //Check for validation error from UserReg class(package:model) 
        Error error = new Error();
        error.setError("400");
        error.setMessage("Validation Failed");
        System.out.println("" + errors.getAllErrors());
        return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
    }
    //Call method for save user in database from class UsersService.
    com.jrtechnologies.yum.data.entity.User userEntity = userService.usersPost(user);
    //After created return id of new user.
    return new ResponseEntity<>(userEntity.getId(), HttpStatus.CREATED);
}
项目:yum    文件:AuthApiController.java   
@Transactional
@Override
public ResponseEntity<Error> authRegisterPost(@ApiParam(value = "The email/password", required = true) @Valid @RequestBody UserReg body, Errors errors) throws ApiException {


    if(applicationProperties.getLdap().isEnabled()){ 
        throw new ApiException(404, "Disabled");
    }         


    if (errors.hasErrors()) {
        Error error = new Error();
        error.setError("400");
        error.setMessage("Validation Failed");
        System.out.println("" + errors.getAllErrors());
        return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
    }
    authService.authRegisterPost(body);
    return new ResponseEntity<>(HttpStatus.OK);

}
项目:yum    文件:OrdersApi.java   
@ApiOperation(value = "Modifies order for the specified day", notes = "Modify the order", response = OrderUpdate.class, authorizations = {
    @Authorization(value = "Bearer")
}, tags={ "hungry", })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "Order succesfully modified", response = OrderUpdate.class),
    @ApiResponse(code = 304, message = "Unmodified data", response = Void.class),
    @ApiResponse(code = 400, message = "Order couldn't be modified.", response = Void.class),
    @ApiResponse(code = 402, message = "Not enough balance.", response = Void.class),
    @ApiResponse(code = 404, message = "Order not found (id)", response = Void.class),
    @ApiResponse(code = 409, message = "Concurrent modification error", response = DailyOrder.class),
    @ApiResponse(code = 410, message = "Concurrent Order Deletion", response = ConcurrentOrderDeletion.class),
    @ApiResponse(code = 412, message = "Deadline for orders passed", response = Void.class),
    @ApiResponse(code = 500, message = "An unexpected error occured.", response = Error.class) })
@RequestMapping(value = "/orders/{id}",
    produces = { "application/json" }, 
    method = RequestMethod.PUT)
@CrossOrigin
ResponseEntity<Object> ordersIdPut(@ApiParam(value = "",required=true ) @PathVariable("id") Long id,@ApiParam(value = "") @RequestParam(value = "userid", required = false) Long userid,
    @ApiParam(value = "The order items to modify"  ) @RequestBody UpdateOrderItems updateOrderItems, Errors errors) throws ApiException;
项目:JuniperBotJ    文件:CommandsContainerValidator.java   
@Override
public void validate(Object target, Errors errors) {
    validatorAdapter.validate(target, errors);
    CommandsContainer container = (CommandsContainer) target;

    Set<String> existingKey = new HashSet<>();
    for (int i = 0; i < container.getCommands().size(); i++) {
        String path = "commands[" + i + "].";
        CustomCommandDto command = container.getCommands().get(i);
        String key = command.getKey();
        if (StringUtils.isNotEmpty(key)) {
            if (!existingKey.add(key)) {
                errors.rejectValue(path + "key", "validation.commands.key.unique.message");
            } else if (holderService.getByLocale(key, true) != null) {
                errors.rejectValue(path + "key", "validation.commands.key.service.message");
            }
        }
    }
}
项目:SmartSync    文件:WeatherValidator.java   
@Override
public void validate(Object object, Errors errors) {

    WeatherLocationDTO weatherLocationDTO = (WeatherLocationDTO) object;

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userId", "field.required",
            "User Id must not be empty");

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "city", "field.required",
            "City must not be empty");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "state", "field.required",
            "State must not be empty");

    if(!errors.hasErrors()) {
        if(weatherLocationDTO.getState().length() != 2) {
            errors.rejectValue("state", "filed.invalid",
                    "State must be length 2. Did you forget to use state code?");
        }

    }


}
项目:SmartSync    文件:UpdateUserValidator.java   
@Override
public void validate(Object o, Errors errors) {
    UpdateUserDTO user = (UpdateUserDTO) o;

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userId", "field.required",
            "User Id must not be empty.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "googleId", "field.required",
            "googleId must not be empty.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "fullName", "field.required",
            "User Full Name must not be empty.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "givenName", "field.required",
            "User Given Name must not be empty.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "familyName", "field.required",
            "User Family Name must not be empty.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "imageURL", "field.required",
            "User Image URL must not be empty.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "field.required",
            "User Email must not be empty");
    ValidationUtils.rejectIfEmpty(errors, "role", "field.required",
            "User Role must not be empty.");

    // doing specific input validaiton, so we need to make sure all of the fields are there
    if(!errors.hasErrors()) {
        if(user.getRole() < 0 || user.getRole() > 1) {
            errors.rejectValue("role", "field.invalid", "User Role must be 0 or 1");
        }

        if(!EmailValidator.getInstance().isValid(user.getEmail())) {
            errors.rejectValue("email", "field.invalid", "User Email must be a valid email address.");
        }

        if(!UrlValidator.getInstance().isValid(user.getImageURL())) {
            errors.rejectValue("imageURL", "field.invalid", "User Image URl must be a valid web address.");
        }
    }
}
项目:SmartSync    文件:UserValidator.java   
/**
 * Validates the input
 * @param object the user to validate
 * @param errors the errors
 */
public void validate(Object object, Errors errors) {

    UserDTO user = (UserDTO) object;

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "googleId", "field.required",
            "googleId must not be empty.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "fullName", "field.required",
            "User Full Name must not be empty.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "givenName", "field.required",
            "User Given Name must not be empty.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "familyName", "field.required",
            "User Family Name must not be empty.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "imageURL", "field.required",
            "User Image URL must not be empty.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "field.required",
            "User Email must not be empty");
    ValidationUtils.rejectIfEmpty(errors, "role", "field.required",
            "User Role must not be empty.");

    // doing specific input validaiton, so we need to make sure all of the fields are there
    if(!errors.hasErrors()) {
        if(user.getRole() < 0 || user.getRole() > 1) {
            errors.rejectValue("role", "field.invalid", "User Role must be 0 or 1");
        }

        if(!EmailValidator.getInstance().isValid(user.getEmail())) {
            errors.rejectValue("email", "field.invalid", "User Email must be a valid email address.");
        }

        if(!UrlValidator.getInstance().isValid(user.getImageURL())) {
            errors.rejectValue("imageURL", "field.invalid", "User Image URl must be a valid web address.");
        }
    }



}
项目:OperatieBRP    文件:WebConfiguratie.java   
@Override
public void validate(final Object target, final Errors errors) {
    for (final Validator validator : validators) {
        if (validator.supports(target.getClass())) {
            validator.validate(target, errors);
        }
    }
}
项目:Spring-5.0-Cookbook    文件:EmployeeValidator.java   
@Override
public void validate(Object model, Errors errors) {
    EmployeeForm empForm = (EmployeeForm) model;

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "empty.firstName");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "empty.lastName");

    if(empForm.getAge() < 0) errors.rejectValue("age", "negative.age");
    if(empForm.getAge() > 65) errors.rejectValue("age", "retirable.age");

    if(empForm.getBirthday().before(new Date(50,0,1))) errors.rejectValue("birthday", "old.birthday");
    Date now = new Date();
    if(empForm.getBirthday().getYear() == now.getYear() || empForm.getBirthday().before(new Date(99,0,1))) errors.rejectValue("birthday", "underage.birthday");
}
项目:Spring-5.0-Cookbook    文件:EmployeeValidator.java   
@Override
public void validate(Object model, Errors errors) {
    EmployeeForm empForm = (EmployeeForm) model;

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "empty.firstName");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "empty.lastName");

    if(empForm.getAge() < 0) errors.rejectValue("age", "negative.age");
    if(empForm.getAge() > 65) errors.rejectValue("age", "retirable.age");

    if(empForm.getBirthday().before(new Date(50,0,1))) errors.rejectValue("birthday", "old.birthday");
    Date now = new Date();
    if(empForm.getBirthday().getYear() == now.getYear() || empForm.getBirthday().before(new Date(99,0,1))) errors.rejectValue("birthday", "underage.birthday");
}
项目:Spring-5.0-Cookbook    文件:EmployeeValidator.java   
@Override
public void validate(Object model, Errors errors) {
    EmployeeForm empForm = (EmployeeForm) model;

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "empty.firstName");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "empty.lastName");

    if(empForm.getAge() < 0) errors.rejectValue("age", "negative.age");
    if(empForm.getAge() > 65) errors.rejectValue("age", "retirable.age");

    if(empForm.getBirthday().before(new Date(50,0,1))) errors.rejectValue("birthday", "old.birthday");
    Date now = new Date();
    if(empForm.getBirthday().getYear() == now.getYear() || empForm.getBirthday().before(new Date(99,0,1))) errors.rejectValue("birthday", "underage.birthday");
}
项目:SmartSync    文件:ServiceController.java   
/**
 * Adds a new service to the database
 *
 * @param serviceDTO the user dto to add
 * @param errors the errors list
 *
 * @return the service that was added
 */
@RequestMapping(method = RequestMethod.POST, value = "/", produces = "application/json")
public ResponseEntity addService(@RequestBody ServiceDTO serviceDTO, Errors errors) {
    logger.info("Adding new service: " + serviceDTO);

    ServiceValidator serviceValidator = new ServiceValidator();
    serviceValidator.validate(serviceDTO, errors);

    ValidationError validationError = ValidationErrorBuilder.fromBindErrors(errors);


    if(errors.hasErrors()) {

        logger.error("Service could not be created: " + validationError.getErrors());
        throw new IllegalRequestFormatException("Could not add service.", "/users/", validationError);
    }

    logger.info("Getting service type information for id: " + serviceDTO.getServiceTypeId());

    ServiceType serviceType = this.serviceTypeService.getServiceTypeById(serviceDTO.getServiceTypeId());

    if(serviceType == null) {

        String message = "Could not find service type with id " + serviceDTO.getServiceTypeId() + ".";
        String url = "/service/types/" + serviceDTO.getServiceTypeId();
        logger.error(message);
        throw new ServiceTypeNotFoundException(message, url);
    }

    Service service = new Service(serviceDTO);
    Service savedService = this.serviceService.addService(service);
    logger.info("Successfully created new service: " + savedService);

    return ResponseEntity.ok(savedService);
}
项目:amv-access-api-poc    文件:UpdateAccessCertificateSignatureRequestValidator.java   
@Override
public void validate(Object target, Errors errors) {
    if (target == null) {
        errors.reject("null", "request must not be null");
    }

}
项目:hike    文件:TagsController.java   
@RequestMapping(value = "{hike.id}", method = RequestMethod.POST)
public String ProcessAddTags(@ModelAttribute @Valid tags newTag, Errors errors, Model model) {

    if (errors.hasErrors()) {
        model.addAttribute("title", "Share A Hike");
        model.addAttribute(new tags());
        return "tags/{hike.id}";
    }
    tagsDao.save(newTag);
    return "redirect:tags/" + newTag.getId();
}
项目:hike    文件:HikeController.java   
@RequestMapping(value = "add-tags/{hikeId}", method = RequestMethod.POST)
public String addTags (Model model, @ModelAttribute @Valid AddTagForm form, Errors errors) {

    if (errors.hasErrors()) {
        model.addAttribute("form", form);
        return "home/add-tags/";
    }
    tags newTag = tagsDao.findOne(form.getTagsId());
    hike newHike = hikeDao.findOne(form.getHikeId());
    newHike.addTag(newTag);
    hikeDao.save(newHike);

    return "home/add-tags/" + newHike.getId();
}
项目:fat-lining    文件:ValidationUtils.java   
/**
 * Validate passwords input
 * <ul>
 *  <li>password is not empty</li>
 *  <li>password has appropriate length</li>
 *  <li>password and repeated password match</li>
 * </ul>
 * @param password to validate
 * @param repeatedPassword to validate
 * @param errors resulting to validation
 */
public void validatePasswords(String password, String repeatedPassword, Errors errors) {
    String cleanPassword = StringUtils.trimToEmpty(password);
    if (StringUtils.isBlank(cleanPassword)) {
        errors.rejectValue("password", "validation.error.password.blank");
    } else if (StringUtils.length(cleanPassword) < config.getPasswordLength()) {
        errors.rejectValue("password", "validation.error.password.tooShort", new Object[]{config.getPasswordLength()}, StringUtils.EMPTY);
    } else {
        String cleanRepeatedPassword = StringUtils.trimToEmpty(repeatedPassword);
        if (!StringUtils.equals(cleanPassword, cleanRepeatedPassword)) {
            errors.rejectValue("repeatedPassword", "validation.error.password.noMatch");
        }
    }

}
项目:SmartSync    文件:ValidationErrorBuilder.java   
/**
 * Takes in the list of errors from the Validator and turns them into readable strings for the response to the
 * front end
 *
 * @param errors the errors
 *
 * @return the Validation Error container
 */
public static ValidationError fromBindErrors(Errors errors) {
    ValidationError error = new ValidationError("Illegal Request Format");

    for(ObjectError objectError : errors.getAllErrors()) {
        error.addValidationError(objectError.getDefaultMessage());
    }

    return error;

}
项目:OperatieBRP    文件:ValidatieUtils.java   
/**
 * Valideer of te valideren datum op of na de huidige datum ligt.
 * @param errors validatie error map
 * @param teValiderenDatum datum welke gevalideerd moet worden
 * @param teValiderenDatumVeld naam van het veld
 */
public static void valideerDatumLigtOpOfNaHuidigeDatum(final Errors errors, final Integer teValiderenDatum, final String teValiderenDatumVeld) {
    final Integer huidigeDatum = DatumUtil.vanDatumNaarInteger(LocalDate.now());
    LOG.info(VALIDEER_DATUM_LIGT_OP_OF_NA_DATUM_EERSTE_DATUM_TWEEDE_DATUM, teValiderenDatum, huidigeDatum);
    if (teValiderenDatum != null) {
        valideer(
                errors,
                vulOnbekendeDelenEindDatumAan(teValiderenDatum) >= huidigeDatum,
                teValiderenDatumVeld,
                VELD_MOETGELIJKOFLATERZIJN,
                "Vandaag",
                teValiderenDatumVeld);
    }
}
项目:fat-lining    文件:NewUserDTOValidator.java   
@Override
public void validate(Object target, Errors errors) {
    log.debug("Validating {}", target);
    NewUserDTO dto = (NewUserDTO) target;
    utils.validateName(dto.getName(), errors);
    utils.validateEmail(dto.getEmail(), null, errors);
    utils.validatePasswords(dto.getPassword(), dto.getRepeatedPassword(), errors);
    utils.validateGoalInKg(dto.getGoalInKg(), errors);
}
项目:onboarding-service    文件:ComparisonController.java   
@ResponseBody
@RequestMapping(path = "comparisons", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public ComparisonResponse comparison(@Valid @ModelAttribute @ApiParam ComparisonCommand comparisonCommand,
                        @ApiIgnore @AuthenticationPrincipal AuthenticatedPerson authenticatedPerson,
                        @ApiIgnore Errors errors) throws Exception {
    if (errors != null && errors.hasErrors()) {
        throw new ValidationErrorsException(errors);
    }

    return comparisonService.compare(comparisonCommand, authenticatedPerson.getUserId());
}