Java Code Examples for org.springframework.validation.Errors#rejectValue()
The following examples show how to use
org.springframework.validation.Errors#rejectValue() .
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: BindTagTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void bindTagWithMappedProperties() throws JspException { PageContext pc = createPageContext(); IndexedTestBean tb = new IndexedTestBean(); Errors errors = new ServletRequestDataBinder(tb, "tb").getBindingResult(); errors.rejectValue("map[key1]", "code1", "message1"); errors.rejectValue("map[key1]", "code2", "message2"); pc.getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "tb", errors); BindTag tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.map[key1]"); 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", "map[key1]".equals(status.getExpression())); assertTrue("Value is TestBean", status.getValue() instanceof TestBean); assertTrue("Correct value", "name4".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 2
Source File: ErrorsTagTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void withExplicitEmptyWhitespaceBodyContent() throws Exception { this.tag.setBodyContent(new MockBodyContent("", getWriter())); // 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"); 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, "Default Message"); }
Example 3
Source File: CreateUserFormValidator.java From Asqatasun with GNU Affero General Public License v3.0 | 6 votes |
/** * * @param userSubscriptionCommand * @param errors * @return */ private boolean checkEmail( CreateUserCommand userSubscriptionCommand, Errors errors) { if (userSubscriptionCommand.getEmail() == null || userSubscriptionCommand.getEmail().trim().isEmpty()) { errors.rejectValue(EMAIL_KEY, MISSING_EMAIL_KEY); return false; } else { String email = userSubscriptionCommand.getEmail(); if (userDataService.getUserFromEmail(userSubscriptionCommand.getEmail()) != null) { errors.rejectValue(EMAIL_KEY, EXISTING_ACCOUNT_WITH_EMAIL_KEY); return false; } else if (!emailCheckerPattern.matcher(email).matches()) { errors.rejectValue(EMAIL_KEY, INVALID_EMAIL_KEY); return false; } } return true; }
Example 4
Source File: ErrorsTagTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void asBodyTagWithExistingMessagesAttribute() throws Exception { String existingAttribute = "something"; getPageContext().setAttribute(ErrorsTag.MESSAGES_ATTRIBUTE, existingAttribute); Errors errors = new BeanPropertyBindingResult(new TestBean(), "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); assertNotNull(getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE)); assertTrue(getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE) instanceof List); String bodyContent = "Foo"; this.tag.setBodyContent(new MockBodyContent(bodyContent, getWriter())); this.tag.doEndTag(); this.tag.doFinally(); assertEquals(bodyContent, getOutput()); assertEquals(existingAttribute, getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE)); }
Example 5
Source File: PetValidator.java From DevOps-for-Web-Development with MIT License | 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 6
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"); } } } }
Example 7
Source File: GuiFragmentValidator.java From entando-core with GNU Lesser General Public License v3.0 | 5 votes |
private int validateGuiCode(GuiFragmentRequestBody request, Errors errors) { if (StringUtils.isEmpty(request.getGuiCode())) { errors.rejectValue("guiCode", ERRCODE_FRAGMENT_INVALID_GUI_CODE, new String[]{}, "guifragment.gui.notBlank"); return 400; } return 0; }
Example 8
Source File: UploadAuditSetUpFormValidator.java From Asqatasun with GNU Affero General Public License v3.0 | 5 votes |
/** * Control whether the uploaded files are of HTML type and whether their * size is under the maxFileSize limit. * * @param uploadAuditSetUpCommand * @param errors */ private void validateFiles(AuditSetUpCommand uploadAuditSetUpCommand, Errors errors) { boolean emptyFile = true; Metadata metadata = new Metadata(); MimeTypes mimeTypes = TikaConfig.getDefaultConfig().getMimeRepository(); String mime; for (int i=0;i<uploadAuditSetUpCommand.getFileInputList().length;i++ ) { try { CommonsMultipartFile cmf = uploadAuditSetUpCommand.getFileInputList()[i]; if (cmf.getSize() > maxFileSize) { Long maxFileSizeInMega = maxFileSize / 1000000; String[] arg = {maxFileSizeInMega.toString()}; errors.rejectValue(ID_INPUT_FILE_PREFIX + "[" + i + "]", FILE_SIZE_EXCEEDED_MSG_BUNDLE_KEY, arg, "{0}"); } if (cmf.getSize() > 0) { emptyFile = false; mime = mimeTypes.detect(new BufferedInputStream(cmf.getInputStream()), metadata).toString(); LOGGER.debug("mime " + mime + " " +cmf.getOriginalFilename()); if (!authorizedMimeType.contains(mime)) { errors.rejectValue(ID_INPUT_FILE_PREFIX + "[" + i + "]", NOT_HTML_MSG_BUNDLE_KEY); } } } catch (IOException ex) { LOGGER.warn(ex); errors.rejectValue(ID_INPUT_FILE_PREFIX + "[" + i + "]", NOT_HTML_MSG_BUNDLE_KEY); } } if(emptyFile) { // if no file is uploaded LOGGER.debug("emptyFiles"); errors.rejectValue(GENERAL_ERROR_MSG_KEY, NO_FILE_UPLOADED_MSG_BUNDLE_KEY); } }
Example 9
Source File: WidgetValidator.java From entando-core with GNU Lesser General Public License v3.0 | 5 votes |
@Override public void validate(Object target, Errors errors) { WidgetRequest widgetRequest = (WidgetRequest) target; if (StringUtils.isEmpty(widgetRequest.getCustomUi())) { errors.rejectValue("customUi", ERRCODE_NOT_BLANK, new String[]{}, "widgettype.customUi.notBlank"); } this.validateTitles(widgetRequest, errors); }
Example 10
Source File: AwsParamStoreProperties.java From spring-cloud-aws with Apache License 2.0 | 5 votes |
@Override public void validate(Object target, Errors errors) { AwsParamStoreProperties properties = (AwsParamStoreProperties) target; if (StringUtils.isEmpty(properties.getPrefix())) { errors.rejectValue("prefix", "NotEmpty", "prefix should not be empty or null."); } if (StringUtils.isEmpty(properties.getDefaultContext())) { errors.rejectValue("defaultContext", "NotEmpty", "defaultContext should not be empty or null."); } if (StringUtils.isEmpty(properties.getProfileSeparator())) { errors.rejectValue("profileSeparator", "NotEmpty", "profileSeparator should not be empty or null."); } if (!PREFIX_PATTERN.matcher(properties.getPrefix()).matches()) { errors.rejectValue("prefix", "Pattern", "The prefix must have pattern of: " + PREFIX_PATTERN.toString()); } if (!PROFILE_SEPARATOR_PATTERN.matcher(properties.getProfileSeparator()) .matches()) { errors.rejectValue("profileSeparator", "Pattern", "The profileSeparator must have pattern of: " + PROFILE_SEPARATOR_PATTERN.toString()); } }
Example 11
Source File: CategoryValidator.java From jcart with MIT License | 5 votes |
@Override public void validate(Object target, Errors errors) { Category category = (Category) target; String name = category.getName(); Category categoryByName = catalogService.getCategoryByName(name); if(categoryByName != null){ errors.rejectValue("name", "error.exists", new Object[]{name}, "Category "+category.getName()+" already exists"); } }
Example 12
Source File: ProductValidator.java From maven-framework-project with MIT License | 5 votes |
public void validate(Object target, Errors errors) { Set<ConstraintViolation<Object>> constraintViolations = beanValidator.validate(target); for (ConstraintViolation<Object> constraintViolation : constraintViolations) { String propertyPath = constraintViolation.getPropertyPath().toString(); String message = constraintViolation.getMessage(); errors.rejectValue(propertyPath, "", message); } for(Validator validator: springValidators) { validator.validate(target, errors); } }
Example 13
Source File: ErrorsMessageDemo.java From geekbang-lessons with Apache License 2.0 | 5 votes |
public static void main(String[] args) { // 0. 创建 User 对象 User user = new User(); user.setName("小马哥"); // 1. 选择 Errors - BeanPropertyBindingResult Errors errors = new BeanPropertyBindingResult(user, "user"); // 2. 调用 reject 或 rejectValue // reject 生成 ObjectError // reject 生成 FieldError errors.reject("user.properties.not.null"); // user.name = user.getName() errors.rejectValue("name", "name.required"); // 3. 获取 Errors 中 ObjectError 和 FieldError // FieldError is ObjectError List<ObjectError> globalErrors = errors.getGlobalErrors(); List<FieldError> fieldErrors = errors.getFieldErrors(); List<ObjectError> allErrors = errors.getAllErrors(); // 4. 通过 ObjectError 和 FieldError 中的 code 和 args 来关联 MessageSource 实现 MessageSource messageSource = createMessageSource(); for (ObjectError error : allErrors) { String message = messageSource.getMessage(error.getCode(), error.getArguments(), Locale.getDefault()); System.out.println(message); } }
Example 14
Source File: PasswordSettingsValidator.java From airsonic with GNU General Public License v3.0 | 5 votes |
public void validate(Object obj, Errors errors) { PasswordSettingsCommand command = (PasswordSettingsCommand) obj; if (command.getPassword() == null || command.getPassword().isEmpty()) { errors.rejectValue("password", "usersettings.nopassword"); } else if (!command.getPassword().equals(command.getConfirmPassword())) { errors.rejectValue("password", "usersettings.wrongpassword"); } }
Example 15
Source File: ForgotPasswordValidator.java From dubai with MIT License | 5 votes |
public void validate(ForgotPasswordForm forgotPasswordForm, HttpServletRequest request, Errors errors) { if (StringUtil.isEmpty(forgotPasswordForm.getLoginName()) && StringUtil.isEmpty(forgotPasswordForm.getEmail())) { errors.rejectValue("loginName", "", ""); errors.rejectValue("email", "", ""); errors.reject("", "用户名和电子邮件至少需要填写一项!"); } String captcha = forgotPasswordForm.getCaptcha(); String captchaInSession = (String) request.getSession().getAttribute(ShiroConstant.CAPTCHA_SESSION_KEY); if (!StringUtil.isEmpty(captcha) && !captcha.equalsIgnoreCase(captchaInSession)) { errors.rejectValue("captcha", "", "验证码错误!"); } }
Example 16
Source File: PageValidator.java From entando-core with GNU Lesser General Public License v3.0 | 5 votes |
public void validateChangePositionRequest(String pageCode, PagePositionRequest pageRequest, Errors errors) { if (!StringUtils.equals(pageCode, pageRequest.getCode())) { errors.rejectValue("code", ERRCODE_URINAME_MISMATCH, new String[]{pageCode, pageRequest.getCode()}, "page.code.mismatch"); } if (pageRequest.getParentCode() == null || pageRequest.getPosition() <= 0 || this.getPageManager().getDraftPage(pageRequest.getParentCode()) == null) { errors.reject(ERRCODE_CHANGE_POSITION_INVALID_REQUEST, new String[]{pageCode}, "page.move.position.invalid"); } }
Example 17
Source File: PremiumSettingsValidator.java From subsonic with GNU General Public License v3.0 | 5 votes |
public void validate(Object obj, Errors errors) { PremiumSettingsCommand command = (PremiumSettingsCommand) obj; if (!settingsService.isLicenseValid(command.getLicenseInfo().getLicenseEmail(), command.getLicenseCode())) { command.setSubmissionError(true); errors.rejectValue("licenseCode", "premium.invalidlicense"); } }
Example 18
Source File: CiTypeAttrValidator.java From we-cmdb with Apache License 2.0 | 5 votes |
private void validateInputType(Errors errors, CiTypeAttrDto ciTypeAttr) { InputType inputType = InputType.fromCode(ciTypeAttr.getInputType()); if (InputType.None.equals(inputType)) { errors.rejectValue("inputType", "inputType"); } else if (!(InputType.Reference.equals(inputType) || InputType.MultRef.equals(inputType))) { ciTypeAttr.setReferenceId(null); ciTypeAttr.setReferenceName(null); } if (!(InputType.Droplist.equals(inputType) || InputType.Reference.equals(inputType) || InputType.MultRef.equals(inputType))) { ciTypeAttr.setIsAccessControlled(false); } }
Example 19
Source File: CountryValidator.java From cacheonix-core with GNU Lesser General Public License v2.1 | 4 votes |
public void validate(Object object, Errors errors) { Country country = (Country) object; if (country.getCode() == this.badPlaceholderCode) { errors.rejectValue("bad.country.selected", "Please select a valid country"); } }
Example 20
Source File: ThirdPartyLoginInterfaceValidator.java From bbs with GNU Affero General Public License v3.0 | 3 votes |
public void validate(Object obj, Errors errors) {//对目标类对象进行校验,错误记录在errors中 ThirdPartyLoginInterface thirdPartyLoginInterface = (ThirdPartyLoginInterface) obj; if(thirdPartyLoginInterface.getName() == null || "".equals(thirdPartyLoginInterface.getName().trim())){ errors.rejectValue("name","errors.required", new String[]{"名称不能为空"},""); } if(thirdPartyLoginInterface.getSort() == null || thirdPartyLoginInterface.getSort() <0){ errors.rejectValue("sort","errors.required", new String[]{"排序必须为大于或等于0的数字"},""); } }