org.springframework.validation.Errors Java Examples
The following examples show how to use
org.springframework.validation.Errors.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CatalogRESTController.java From Spring-5.0-Projects with MIT License | 6 votes |
@PostMapping(value="/addBook",consumes= MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<List<String>> addNewBook(@Valid @RequestBody BookDTO bookDto,Errors errors) { // Add BookDTO validations here if(errors.hasErrors()) { List<String> errorMsg = new ArrayList<String>(); errors.getAllErrors().forEach(a -> errorMsg.add(a.getDefaultMessage())); return new ResponseEntity<List<String>>(errorMsg, HttpStatus.BAD_REQUEST); }else { Book bookEntity = new Book(); Publisher bookPublisher = getPublisher(bookDto.getPublisherId()); bookEntity.setPublisher(bookPublisher); bookEntity.setPrice(bookDto.getPrice()); bookEntity.setCategory(getCategory(bookDto.getCategory())); bookEntity.setLongDesc(bookDto.getLongDesc()); bookEntity.setSmallDesc(bookDto.getSmallDesc()); bookEntity.setTitle(bookDto.getTitle()); bookRepository.save(bookEntity); List<String> msgLst = Arrays.asList("Book -"+bookDto.getTitle()+" has been added successfully"); return new ResponseEntity<List<String>>(msgLst, HttpStatus.OK); } }
Example #2
Source File: EntityValidatorTest.java From molgenis with GNU Lesser General Public License v3.0 | 6 votes |
@Test void testValidateNotNullConstraintString() { String attributeName = "attr"; Attribute attribute = when(mock(Attribute.class).getDataType()).thenReturn(STRING).getMock(); when(attribute.getName()).thenReturn(attributeName); EntityType entityType = when(mock(EntityType.class).getAtomicAttributes()) .thenReturn(singletonList(attribute)) .getMock(); Entity entity = when(mock(Entity.class).getEntityType()).thenReturn(entityType).getMock(); Errors errors = mock(Errors.class); entityValidator.validate(entity, errors); verify(errors).rejectValue(attributeName, "constraints.NotNull", null, null); }
Example #3
Source File: BindTagTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void bindTagWithIndexedProperties() throws JspException { PageContext pc = createPageContext(); IndexedTestBean tb = new IndexedTestBean(); Errors errors = new ServletRequestDataBinder(tb, "tb").getBindingResult(); errors.rejectValue("array[0]", "code1", "message1"); errors.rejectValue("array[0]", "code2", "message2"); pc.getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "tb", errors); BindTag tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.array[0]"); assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); assertTrue("Has status variable", status != null); assertTrue("Correct expression", "array[0]".equals(status.getExpression())); assertTrue("Value is TestBean", status.getValue() instanceof TestBean); assertTrue("Correct value", "name0".equals(((TestBean) status.getValue()).getName())); assertTrue("Correct isError", status.isError()); assertTrue("Correct errorCodes", status.getErrorCodes().length == 2); assertTrue("Correct errorMessages", status.getErrorMessages().length == 2); assertTrue("Correct errorCode", "code1".equals(status.getErrorCodes()[0])); assertTrue("Correct errorCode", "code2".equals(status.getErrorCodes()[1])); assertTrue("Correct errorMessage", "message1".equals(status.getErrorMessages()[0])); assertTrue("Correct errorMessage", "message2".equals(status.getErrorMessages()[1])); }
Example #4
Source File: CreateContractFormValidator.java From Asqatasun with GNU Affero General Public License v3.0 | 6 votes |
/** * * @param userSubscriptionCommand * @param errors * @return */ private boolean checkDates(CreateContractCommand createContractCommand, Errors errors) { Date beginDate = createContractCommand.getBeginDate(); Date endDate = createContractCommand.getEndDate(); if (beginDate == null) { errors.rejectValue(BEGIN_DATE_KEY, EMPTY_BEGIN_DATE_KEY); return false; } if (endDate == null) { errors.rejectValue(END_DATE_KEY, EMPTY_END_DATE_KEY); return false; } if (endDate.before(beginDate) || endDate.equals(beginDate)) { errors.rejectValue(BEGIN_DATE_KEY, END_DATE_ANTERIOR_TO_BEGIN_KEY); return false; } return true; }
Example #5
Source File: EntityValidatorTest.java From molgenis with GNU Lesser General Public License v3.0 | 6 votes |
@Test void testValidateRangeMinConstraint() { String attributeName = "attr"; Attribute attribute = when(mock(Attribute.class).getDataType()).thenReturn(LONG).getMock(); when(attribute.getName()).thenReturn(attributeName); long min = 1L; when(attribute.getRange()).thenReturn(new Range(min, null)); EntityType entityType = when(mock(EntityType.class).getAtomicAttributes()) .thenReturn(singletonList(attribute)) .getMock(); long value = 0L; Entity entity = when(mock(Entity.class).getEntityType()).thenReturn(entityType).getMock(); when(entity.getLong(attribute)).thenReturn(value); Errors errors = mock(Errors.class); entityValidator.validate(entity, errors); verify(errors).rejectValue(attributeName, "constraints.Min", new Object[] {min}, null); }
Example #6
Source File: ErrorsTagTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void withErrors() throws Exception { // construct an errors instance of the tag TestBean target = new TestBean(); target.setName("Rob Harrop"); Errors errors = new BeanPropertyBindingResult(target, COMMAND_NAME); errors.rejectValue("name", "some.code", "Default Message"); errors.rejectValue("name", "too.short", "Too Short"); exposeBindingResult(errors); int result = this.tag.doStartTag(); assertEquals(BodyTag.EVAL_BODY_BUFFERED, result); result = this.tag.doEndTag(); assertEquals(Tag.EVAL_PAGE, result); String output = getOutput(); assertElementTagOpened(output); assertElementTagClosed(output); assertContainsAttribute(output, "id", "name.errors"); assertBlockTagContains(output, "<br/>"); assertBlockTagContains(output, "Default Message"); assertBlockTagContains(output, "Too Short"); }
Example #7
Source File: PageValidator.java From entando-core with GNU Lesser General Public License v3.0 | 6 votes |
public void validateGroups(String pageCode, PagePositionRequest pageRequest, Errors errors) { logger.debug("ValidateGroups for page {}", pageCode); IPage parent = this.getPageManager().getDraftPage(pageRequest.getParentCode()); IPage page = this.getPageManager().getDraftPage(pageCode); logger.debug("Parent {} getGroup() {}", parent.getGroup()); logger.debug("Page {} getGroup {}", page.getGroup()); if (!parent.getGroup().equals(Group.FREE_GROUP_NAME) && !page.getGroup().equals(parent.getGroup())) { if (page.getGroup().equals(Group.FREE_GROUP_NAME)) { logger.debug("Validation error for page with pageCode {} ERRCODE_GROUP_MISMATCH 1 - {}", pageCode, ERRCODE_GROUP_MISMATCH); errors.reject(ERRCODE_GROUP_MISMATCH, new String[]{}, "page.move.freeUnderReserved.notAllowed"); } else { logger.debug("Validation error for page with pageCode {} ERRCODE_GROUP_MISMATCH 2 - {}", pageCode, ERRCODE_GROUP_MISMATCH); errors.reject(ERRCODE_GROUP_MISMATCH, new String[]{}, "page.move.group.mismatch"); } } }
Example #8
Source File: GeneralValidatorTest.java From webcurator with Apache License 2.0 | 6 votes |
@Test public void testValidateNullNameField() { try { GeneralCommand cmd = new GeneralCommand(); Errors errors = new BindException(cmd, "GeneralCommand"); cmd.setEditMode(true); cmd.setName(null); cmd.setFromDate(new Date()); cmd.setSubGroupType("Sub-Group"); cmd.setSubGroupSeparator(" > "); // pass in newly created objects, expect no errors. testInstance.validate(cmd, errors); assertEquals("Expecting 1 errors", 1, errors.getErrorCount()); assertEquals("Expecting error[0] for field Name", true, errors.getAllErrors().toArray()[0].toString().contains("Name is a required field")); } catch (Exception e) { String message = e.getClass().toString() + " - " + e.getMessage(); log.debug(message); fail(message); } }
Example #9
Source File: SitePermissionValidatorTestCase.java From webcurator with Apache License 2.0 | 6 votes |
@Test public void testValidateActionSaveCase03() { try { SitePermissionCommand cmd = new SitePermissionCommand(); SitePermissionValidator validator = new SitePermissionValidator(); Errors errors = new BindException(cmd, "SitePermissionCommand"); // don't set urls authorisingAgent = businessObjectFactory.newAuthorisingAgent(); authorisingAgent.setOid(1L); startDate = new Date(); // today cmd.setActionCmd(SitePermissionCommand.ACTION_SAVE); cmd.setAuthorisingAgent(authorisingAgent); cmd.setStartDate(startDate); validator.validate(cmd, errors); assertEquals("ACTION_SAVE Case 03: Expecting 1 errors", 1, errors.getErrorCount()); assertEquals("ACTION_SAVE Case 03: Expecting error[0] for field Urls", true, errors.getAllErrors().toArray()[0].toString().contains("[Urls]")); } catch (Exception e) { String message = e.getClass().toString() + " - " + e.getMessage(); log.debug(message); fail(message); } }
Example #10
Source File: GeneralValidatorTest.java From webcurator with Apache License 2.0 | 6 votes |
@Test public void testValidateMaxDescLength() { try { GeneralCommand cmd = new GeneralCommand(); Errors errors = new BindException(cmd, "GeneralCommand"); cmd.setEditMode(true); cmd.setName("TestName"); cmd.setFromDate(new Date()); cmd.setDescription(makeLongString(GeneralCommand.CNST_MAX_LEN_DESC+1, 'X')); cmd.setSubGroupType("Sub-Group"); cmd.setSubGroupSeparator(" > "); testInstance.validate(cmd, errors); assertEquals("Case02: Expecting 1 errors", 1, errors.getErrorCount()); assertEquals("Case02: Expecting error[0] for field Description", true, errors.getAllErrors().toArray()[0].toString().contains("Description is too long")); } catch (Exception e) { String message = e.getClass().toString() + " - " + e.getMessage(); log.debug(message); fail(message); } }
Example #11
Source File: PetValidator.java From spring-graalvm-native with Apache License 2.0 | 6 votes |
@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); } }
Example #12
Source File: EntityValidatorTest.java From molgenis with GNU Lesser General Public License v3.0 | 6 votes |
@Test void testValidateRangeMaxConstraint() { String attributeName = "attr"; Attribute attribute = when(mock(Attribute.class).getDataType()).thenReturn(LONG).getMock(); when(attribute.getName()).thenReturn(attributeName); long max = 3L; when(attribute.getRange()).thenReturn(new Range(null, max)); EntityType entityType = when(mock(EntityType.class).getAtomicAttributes()) .thenReturn(singletonList(attribute)) .getMock(); long value = 4L; Entity entity = when(mock(Entity.class).getEntityType()).thenReturn(entityType).getMock(); when(entity.getLong(attribute)).thenReturn(value); Errors errors = mock(Errors.class); entityValidator.validate(entity, errors); verify(errors).rejectValue(attributeName, "constraints.Max", new Object[] {max}, null); }
Example #13
Source File: MoveTargetsValidatorTest.java From webcurator with Apache License 2.0 | 6 votes |
@Test public final void testValidate() { try { MoveTargetsCommand cmd = new MoveTargetsCommand(); Errors errors = new BindException(cmd, "MoveTargetsCommand"); cmd.setActionCmd(MoveTargetsCommand.ACTION_MOVE_TARGETS); // pass in newly created objects, expect no errors. testInstance.validate(cmd, errors); assertEquals("Expecting 1 errors", 1, errors.getErrorCount()); assertEquals("Expecting error[0]", true, errors.getAllErrors().toArray()[0].toString().contains("target.errors.addparents.must_select")); } catch (Exception e) { String message = e.getClass().toString() + " - " + e.getMessage(); log.debug(message); fail(message); } }
Example #14
Source File: SitePermissionValidatorTestCase.java From webcurator with Apache License 2.0 | 6 votes |
@Test public void testValidateActionSaveCase02() { try { SitePermissionCommand cmd = new SitePermissionCommand(); SitePermissionValidator validator = new SitePermissionValidator(); Errors errors = new BindException(cmd, "SitePermissionCommand"); // don't set startDate or urls authorisingAgent = businessObjectFactory.newAuthorisingAgent(); authorisingAgent.setOid(1L); cmd.setActionCmd(SitePermissionCommand.ACTION_SAVE); cmd.setAuthorisingAgent(authorisingAgent); validator.validate(cmd, errors); assertEquals("ACTION_SAVE Case 02: Expecting 2 errors", 2, errors.getErrorCount()); assertEquals("ACTION_SAVE Case 02: Expecting error[0] for field startDate", true, errors.getAllErrors().toArray()[0].toString().contains("'startDate'")); assertEquals("ACTION_SAVE Case 02: Expecting error[1] for field Urls", true, errors.getAllErrors().toArray()[1].toString().contains("[Urls]")); } catch (Exception e) { String message = e.getClass().toString() + " - " + e.getMessage(); log.debug(message); fail(message); } }
Example #15
Source File: AwsSecretsManagerPropertiesTest.java From spring-cloud-aws with Apache License 2.0 | 5 votes |
@ParameterizedTest @MethodSource("invalidProperties") public void validationFails(AwsSecretsManagerProperties properties, String field, String errorCode) { Errors errors = new BeanPropertyBindingResult(properties, "properties"); properties.validate(properties, errors); assertThat(errors.getFieldError(field)).isNotNull(); assertThat(errors.getFieldError(field).getCode()).isEqualTo(errorCode); }
Example #16
Source File: BindTagTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void bindTagWithIndexedProperties() throws JspException { PageContext pc = createPageContext(); IndexedTestBean tb = new IndexedTestBean(); Errors errors = new ServletRequestDataBinder(tb, "tb").getBindingResult(); errors.rejectValue("array[0]", "code1", "message1"); errors.rejectValue("array[0]", "code2", "message2"); pc.getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "tb", errors); BindTag tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.array[0]"); assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); assertTrue("Has status variable", status != null); assertTrue("Correct expression", "array[0]".equals(status.getExpression())); assertTrue("Value is TestBean", status.getValue() instanceof TestBean); assertTrue("Correct value", "name0".equals(((TestBean) status.getValue()).getName())); assertTrue("Correct isError", status.isError()); assertTrue("Correct errorCodes", status.getErrorCodes().length == 2); assertTrue("Correct errorMessages", status.getErrorMessages().length == 2); assertTrue("Correct errorCode", "code1".equals(status.getErrorCodes()[0])); assertTrue("Correct errorCode", "code2".equals(status.getErrorCodes()[1])); assertTrue("Correct errorMessage", "message1".equals(status.getErrorMessages()[0])); assertTrue("Correct errorMessage", "message2".equals(status.getErrorMessages()[1])); }
Example #17
Source File: ValidatorUtil.java From webcurator with Apache License 2.0 | 5 votes |
/** * Helper method used to check string value 1 does not contain value 2. * @param aErrors the errors object to populate * @param val1 String value 1 * @param val2 String value 2 * @param aErrorCode the error code * @param aValues the values * @param aFailureMessage the default message */ public static void validateValueNotContained(Errors aErrors, String val1, String val2, String aErrorCode, Object[] aValues, String aFailureMessage) { if (val1 != null && val2 != null) { if (val1.contains(val2) == false) { return; } } aErrors.reject(aErrorCode, aValues, aFailureMessage); }
Example #18
Source File: ReservationApiV2Controller.java From alf.io with GNU General Public License v3.0 | 5 votes |
private void assignTickets(String eventName, String reservationId, ContactAndTicketsForm contactAndTicketsForm, BindingResult bindingResult, Locale locale, boolean preAssign, boolean skipValidation) { if(!contactAndTicketsForm.isPostponeAssignment()) { contactAndTicketsForm.getTickets().forEach((ticketId, owner) -> { if (preAssign) { Optional<Errors> bindingResultOptional = skipValidation ? Optional.empty() : Optional.of(bindingResult); ticketHelper.preAssignTicket(eventName, reservationId, ticketId, owner, bindingResultOptional, locale, Optional.empty()); } else { ticketHelper.assignTicket(eventName, ticketId, owner, Optional.of(bindingResult), locale, Optional.empty(), true); } }); } }
Example #19
Source File: SignupController.java From thymeleafexamples-layouts with Apache License 2.0 | 5 votes |
@PostMapping("signup") public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors, RedirectAttributes ra) { if (errors.hasErrors()) { return SIGNUP_VIEW_NAME; } Account account = accountService.save(signupForm.createAccount()); accountService.signin(account); // see /WEB-INF/i18n/messages.properties and /WEB-INF/views/homeSignedIn.html MessageHelper.addSuccessAttribute(ra, "signup.success"); return "redirect:/"; }
Example #20
Source File: AppGroupServiceTest.java From das with Apache License 2.0 | 5 votes |
@Test public void validatePermisionTest() throws Exception { LoginUser user = LoginUser.builder().id(1L).build(); DasGroup dasGroup = DasGroup.builder().group_name("name").build(); Errors errors = new BeanPropertyBindingResult(dasGroup, "dasGroup", true, 256); ValidatorChain chain = appGroupService.validatePermision(user, errors); Assert.assertTrue(chain.validate().isValid()); }
Example #21
Source File: NewAccountValidator.java From attic-rave with Apache License 2.0 | 5 votes |
private void validateEmail(Errors errors, String email) { if (StringUtils.isBlank(email)) { errors.rejectValue(FIELD_EMAIL, "email.required"); } else if (isInvalidEmailAddress(email)) { errors.rejectValue(FIELD_EMAIL, "email.invalid"); } else if (isExistingEmailAddress(email)) { errors.rejectValue(FIELD_EMAIL, "email.exists"); } }
Example #22
Source File: BindTagTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void bindTagWithNestedFieldErrors() throws JspException { PageContext pc = createPageContext(); TestBean tb = new TestBean(); tb.setName("name1"); TestBean spouse = new TestBean(); spouse.setName("name2"); tb.setSpouse(spouse); Errors errors = new ServletRequestDataBinder(tb, "tb").getBindingResult(); errors.rejectValue("spouse.name", "code1", "message1"); pc.getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "tb", errors); BindTag tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.spouse.name"); assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); assertTrue("Has status variable", status != null); assertTrue("Correct expression", "spouse.name".equals(status.getExpression())); assertTrue("Correct value", "name2".equals(status.getValue())); assertTrue("Correct displayValue", "name2".equals(status.getDisplayValue())); assertTrue("Correct isError", status.isError()); assertTrue("Correct errorCodes", status.getErrorCodes().length == 1); assertTrue("Correct errorMessages", status.getErrorMessages().length == 1); assertTrue("Correct errorCode", "code1".equals(status.getErrorCode())); assertTrue("Correct errorMessage", "message1".equals(status.getErrorMessage())); assertTrue("Correct errorMessagesAsString", "message1".equals(status.getErrorMessagesAsString(" - "))); }
Example #23
Source File: RequestMappingHandlerAdapterIntegrationTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void handleAndValidateRequestBody() throws Exception { Class<?>[] parameterTypes = new Class<?>[] {TestBean.class, Errors.class}; request.addHeader("Content-Type", "text/plain; charset=utf-8"); request.setContent("Hello Server".getBytes("UTF-8")); HandlerMethod handlerMethod = handlerMethod("handleAndValidateRequestBody", parameterTypes); ModelAndView mav = handlerAdapter.handle(request, response, handlerMethod); assertNull(mav); assertEquals("Error count [1]", new String(response.getContentAsByteArray(), "UTF-8")); assertEquals(HttpStatus.ACCEPTED.value(), response.getStatus()); }
Example #24
Source File: CustomRequestEntityValidationHandler.java From tutorials with MIT License | 5 votes |
@Override protected Mono<ServerResponse> onValidationErrors(Errors errors, CustomRequestEntity invalidBody, final ServerRequest request) { return ServerResponse.badRequest() .contentType(MediaType.APPLICATION_JSON) .body(Mono.just(String.format("Custom message showing the errors: %s", errors.getAllErrors() .toString())), String.class); }
Example #25
Source File: AddScenarioFormValidator.java From Asqatasun with GNU Affero General Public License v3.0 | 5 votes |
/** * The AuditSetUpFormValidator checks whether the options values are * acceptable regarding the FormField internal checker * * @param target * @param errors */ @Override public void validate(Object target, Errors errors) { AddScenarioCommand addScenarioCommand = (AddScenarioCommand)target; if (checkScenarioLabel(addScenarioCommand, errors)) { if (checkScenarioFileTypeAndSize(addScenarioCommand, errors)) { checkScenarioFileValidity(addScenarioCommand, errors); } } }
Example #26
Source File: Heritrix3ProfileValidator.java From webcurator with Apache License 2.0 | 5 votes |
public void validate(Object comm, Errors errors) { Heritrix3ProfileCommand command = (Heritrix3ProfileCommand) comm; // Contact URL is required. if(command.getContactURL() != null) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "contactURL", "required", getObjectArrayForLabel("contactURL"), "Contact URL is a required field"); ValidatorUtil.validateURL(errors, command.getContactURL(),"invalid.url",new Object[] {command.getContactURL()},"Invalid URL"); } // User agent prefix is required. if(command.getUserAgent() != null) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userAgent", "required", getObjectArrayForLabel("userAgent"), "User Agent Prefix is a required field"); } }
Example #27
Source File: GroupDatabaseController.java From das with Apache License 2.0 | 5 votes |
/** * 4、删除组对应的数据库 */ @RequestMapping(value = "/delete", method = RequestMethod.DELETE) public ServiceResult<String> delete(@Validated(DeleteGroupDB.class) @RequestBody DataBaseInfo dataBaseInfo, @CurrentUser LoginUser user, Errors errors) throws Exception { ValidateResult validateRes = groupDatabaseService.validatePermision(user, errors) .addAssert(() -> groupDatabaseService.isGroupHadDB(dataBaseInfo.getId(), dataBaseInfo.getDal_group_id()), message.message_operation_pemission) .addAssert(() -> dataBaseDao.updateDataBaseInfo(dataBaseInfo.getId(), -1L) > 0, message.db_message_delete_operation_failed).validate(); if (!validateRes.isValid()) { return ServiceResult.fail(validateRes.getSummarize()); } return ServiceResult.success(); }
Example #28
Source File: OptionsTagTests.java From spring-analysis-note with MIT License | 5 votes |
@Override protected void exposeBindingResult(Errors errors) { // wrap errors in a Model Map model = new HashMap(); model.put(BindingResult.MODEL_KEY_PREFIX + COMMAND_NAME, errors); // replace the request context with one containing the errors MockPageContext pageContext = getPageContext(); RequestContext context = new RequestContext((HttpServletRequest) pageContext.getRequest(), model); pageContext.setAttribute(RequestContextAwareTag.REQUEST_CONTEXT_PAGE_ATTRIBUTE, context); }
Example #29
Source File: StaffFormValidator.java From spring-boot-doma2-sample with Apache License 2.0 | 5 votes |
@Override protected void doValidate(StaffForm form, Errors errors) { // 確認用パスワードと突き合わせる if (isNotEquals(form.getPassword(), form.getPasswordConfirm())) { errors.rejectValue("password", "staffs.unmatchPassword"); errors.rejectValue("passwordConfirm", "staffs.unmatchPassword"); } }
Example #30
Source File: WidgetValidator.java From entando-core with GNU Lesser General Public License v3.0 | 5 votes |
protected void validateTitles(WidgetRequest widgetRequest, Errors errors) { Map<String, String> titles = widgetRequest.getTitles(); if (null == titles) { errors.rejectValue("titles", ERRCODE_NOT_BLANK, "widgettype.titles.notBlank"); } else { String[] langs = {"en", "it"}; for (String lang : langs) { if (StringUtils.isBlank(titles.get(lang))) { errors.rejectValue("titles", ERRCODE_MISSING_TITLE, new String[]{lang}, "widgettype.title.notBlank"); } } } }