List of usage examples for org.springframework.validation ValidationUtils rejectIfEmptyOrWhitespace
public static void rejectIfEmptyOrWhitespace(Errors errors, String field, String errorCode, @Nullable Object[] errorArgs)
From source file:org.opentides.web.validator.SystemCodesValidator.java
@Override public void validate(Object target, Errors errors) { SystemCodes systemCodes = (SystemCodes) target; ValidationUtils.rejectIfEmpty(errors, "category", "error.required", new Object[] { "Category" }); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "key", "error.required", new Object[] { "Key" }); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "value", "error.required", new Object[] { "Value" }); if (systemCodesService.isDuplicateKey(systemCodes)) { errors.reject("error.duplicate-key", new Object[] { "\"" + systemCodes.getKey() + "\"", "key" }, "\"" + systemCodes.getKey() + "\" already exists. Please try a different key."); }//from w ww . j a v a 2s.c om if (!systemCodes.isParentValid()) { errors.reject("error.parent-invalid", new Object[] { "\"" + systemCodes.getKey() + "\"", "\"" + systemCodes.getParent().getKey() + "\"" }, "\"" + systemCodes.getKey() + "\" conflicts with \"" + systemCodes.getParent().getKey() + "\". Please try a different one."); } if (!StringUtil.isEmpty(systemCodes.getParentString())) { SystemCodes parent = systemCodesService.findByKey(systemCodes.getParentString()); if (parent == null) { errors.reject("error.parent-does-not-exist", new Object[] { systemCodes.getParentString() }, systemCodes.getParentString() + " does not exist, please choose a valid Parent."); } } }
From source file:org.jasig.schedassist.web.owner.schedule.AvailableBlockFormBackingObjectValidator.java
public void validate(Object target, Errors errors) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "startTimePhrase", "field.required", "Start time field is required."); AvailableBlockFormBackingObject fbo = (AvailableBlockFormBackingObject) target; Date startTime = null;/*w w w . ja va2s . c o m*/ Date endTime = null; // validate startTimePhrase (if present) if (StringUtils.isNotBlank(fbo.getStartTimePhrase())) { try { startTime = CommonDateOperations.parseDateTimePhrase(fbo.getStartTimePhrase()); } catch (InputFormatException e) { errors.rejectValue("startTimePhrase", "field.parseexception", "Start time does not match expected format (YYYYmmDD-hhmm)"); } } // validate endTimePhrase if present if (StringUtils.isNotBlank(fbo.getEndTimePhrase())) { try { endTime = CommonDateOperations.parseDateTimePhrase(fbo.getEndTimePhrase()); } catch (InputFormatException e) { errors.rejectValue("endTimePhrase", "field.parseexception", "End time does not match expected format (YYYYmmDD-hhmm)"); } } if (fbo.getVisitorLimit() < 1) { errors.rejectValue("visitorLimit", "visitorLimit.toosmall", "Visitor limit must be greater than or equal to 1."); } if (fbo.getVisitorLimit() > 99) { errors.rejectValue("visitorLimit", "visitorLimit.toolarge", "Maximum value for visitor limit is 99."); } if (null != startTime && null != endTime) { // validate AvailabilityBlock construction try { AvailableBlockBuilder.createBlock(fbo.getStartTimePhrase(), fbo.getEndTimePhrase()); } catch (InputFormatException e) { errors.reject("field.inputformatexception", e.getMessage()); } } }
From source file:com.persistent.cloudninja.validator.ProvisioningTenantDTOValidator.java
@Override public void validate(Object target, Errors errors) { ProvisioningTenantDTO provisioningTenantDTO = (ProvisioningTenantDTO) target; String identityProvider = provisioningTenantDTO.getIdentityProvider(); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "demoKey", "field is required", "The Demo Key field is required."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "tenantId", "field is required", "The Service Alias field is required."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "companyName", "field is required", "The Company Name field is required."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "memberId", "field is required", "The User id field is required."); // Validate only if STS if (identityProvider.equals(CLOUDNINJASTS)) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "memberName", "field is required", "The Name field is required."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "memberPassword", "field is required", "The Password field is required."); }//w ww. j a va 2 s.c o m String demoKey = provisioningTenantDTO.getDemoKey(); String tenantId = provisioningTenantDTO.getTenantId(); String companyName = provisioningTenantDTO.getCompanyName(); String memberId = provisioningTenantDTO.getMemberId(); String memberName = provisioningTenantDTO.getMemberName(); String memberPassword = provisioningTenantDTO.getMemberPassword(); String numberAndLetterRegex = "^[a-zA-Z0-9]+$"; if (!demoKey.isEmpty() && !demoKey.equals(expectedDemoKey)) { errors.rejectValue("demoKey", "Invalid Demo Key", "Demo Key is not valid."); } // validations for tenant-id field if (!tenantId.isEmpty()) { Pattern p = Pattern.compile(numberAndLetterRegex); Matcher m = p.matcher(tenantId); if (!m.matches()) { errors.rejectValue("tenantId", "", "Only letters and numbers are allowed."); } if (!validLength(3, 20, tenantId)) { errors.rejectValue("tenantId", "", "The field Service Alias must be a string with a minimum length of 3 and a maximum length of 20."); } } // validations for Company name if (!companyName.isEmpty()) { if (!validLength(3, 30, companyName)) { errors.rejectValue("companyName", "", "The field Company Name must be a string with a minimum length of 3 and a maximum length of 30."); } } // validate user id if (!memberId.isEmpty()) { if (!validLength(4, 150, memberId)) { errors.rejectValue("memberId", "", "The field User id must be a string with a minimum length of 4 and a maximum length of 150."); } } // Validate only if STS if (identityProvider.equals(CLOUDNINJASTS)) { // Validate Name if (!memberName.isEmpty()) { if (!validLength(4, 30, memberName)) { errors.rejectValue("memberName", "", "The field Name must be a string with a minimum length of 4 and a maximum length of 30."); } } // Validate password if (!memberPassword.isEmpty()) { String msg = "The field Password must contain at least one digit, special symbols '@#$%'," + " lower and uppercase characters with a minimum length of 6 and a maximum length of 20."; Pattern pattern; Matcher matcher; String PASSWORD_PATTERN = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})"; pattern = Pattern.compile(PASSWORD_PATTERN); matcher = pattern.matcher(memberPassword); if (!matcher.matches()) { errors.rejectValue("memberPassword", "", msg); } } } }
From source file:net.maritimecloud.endorsement.validators.EndorsementValidator.java
@Override public void validate(Object target, Errors errors) { Endorsement endorsement = (Endorsement) target; Set<ConstraintViolation<Object>> constraintViolations = validator.validate(target); for (ConstraintViolation<Object> constraintViolation : constraintViolations) { String propertyPath = constraintViolation.getPropertyPath().toString(); String message = constraintViolation.getMessage(); errors.rejectValue(propertyPath, "", message); }//from ww w . java 2 s .c o m ValidationUtils.rejectIfEmptyOrWhitespace(errors, "serviceMrn", "serviceMrn.empty", "serviceMrn is required."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "serviceVersion", "serviceVersion.empty", "serviceVersion is required."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "orgMrn", "orgMrn.empty", "orgMrn is required."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "orgName", "orgName.empty", "orgName is required."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userMrn", "userMrn.empty", "userMrn is required."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "serviceLevel", "serviceLevel.empty", "serviceLevel is required."); if (!"specification".equals(endorsement.getServiceLevel())) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "parentMrn", "parentMrn.empty", "parentMrn and parentVersion is dependant on each other."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "parentVersion", "parentVersion.empty", "parentMrn and parentVersion is dependant on each other."); } }
From source file:org.jasig.schedassist.web.visitor.CreateAppointmentFormBackingObjectValidator.java
public void validate(Object command, Errors errors) { CreateAppointmentFormBackingObject fbo = (CreateAppointmentFormBackingObject) command; if (fbo.isMultipleVisitors()) { if (!fbo.isConfirmJoin()) { errors.rejectValue("confirmJoin", "confirmJoin.false", "Please mark the checkbox to confirm you wish to join the appointment."); }/*from w w w .ja v a 2 s . co m*/ } else { // reason cannot be null if only 1 visitor ValidationUtils.rejectIfEmptyOrWhitespace(errors, "reason", "field.required", "Reason for the meeting is required."); // selectedDuration only present if 1 visitor if (!fbo.getMeetingDurationsAsList().contains(fbo.getSelectedDuration())) { errors.rejectValue("selectedDuration", "selectedDuration.outofbounds", "Unacceptable value for meeting duration"); } } }
From source file:se.gothiaforum.validator.actorsform.ActorArticleValidator.java
/** * This method validate the object target. * //w ww .j av a 2 s. c o m * @param target * the object to validate * @param errors * a list to register found validation errors */ @Override public void validate(Object target, Errors errors) { ActorArticle actorArticle = (ActorArticle) target; ValidatorUtils.removeLeadingAndTrailingWhitespacesOnAllStringFields(actorArticle); // Remove leading and // trailing spaces on // all String fields ValidationUtils.rejectIfEmptyOrWhitespace(errors, "companyName", "code.missing", "invalid-companyName"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "intro", "code.missing", "invalid-intro"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "code.missing", "invalid-name"); // ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address", "code.missing", "invalid-address"); if (actorArticle.getCompanyName().length() > ValidationConstants.LENGHT_VALIDATION_DEFAULT) { errors.rejectValue("companyName", "code.to.long", "to-long-companyName"); } if (actorArticle.getCompanyName().contains(".")) { errors.rejectValue("companyName", "code.contains.dot", "contains-dot"); } if (actorArticle.getOrganizationName().length() > ValidationConstants.LENGHT_VALIDATION_DEFAULT) { errors.rejectValue("organizationName", "code.to.long", "to-long-organizationName"); } if (actorArticle.getIntro().length() > ValidationConstants.LENGHT_VALIDATION_INTRO) { errors.rejectValue("intro", "code.to.long", "to-long-intro"); } if (actorArticle.getDetailedDescription().length() > ValidationConstants.LENGHT_VALIDATION_DESCRIPTION) { errors.rejectValue("detailedDescription", "code.to.long", "to-long-detailedDescription"); } if (actorArticle.getExternalHomepage().length() > ValidationConstants.LENGHT_VALIDATION_URL) { errors.rejectValue("externalHomepage", "code.to.long", "to-long-externalHomepage"); System.out.println("error"); } if (actorArticle.getName().length() > ValidationConstants.LENGHT_VALIDATION_DEFAULT) { errors.rejectValue("name", "code.to.long", "to-long-name"); } if (actorArticle.getTitle().length() > ValidationConstants.LENGHT_VALIDATION_DEFAULT) { errors.rejectValue("title", "code.to.long", "to-long-title"); } if (actorArticle.getAddress().length() > ValidationConstants.LENGHT_VALIDATION_ADDRESS) { errors.rejectValue("address", "code.to.long", "to-long-address"); } if (!isEmail(actorArticle.getMail())) { errors.rejectValue("mail", "code.invalid.email.format", "invalid-mail"); } if (!isPhoneNumber(actorArticle.getPhone())) { errors.rejectValue("phone", "code.invalid.phone.format", "invalid-phone-number"); } if (!isPhoneNumberEmptyIsOk(actorArticle.getMobilePhone())) { errors.rejectValue("mobilePhone", "code.invalid.mobilePhone.format", "invalid-mobile-phone-number"); } if (!isPhoneNumberEmptyIsOk(actorArticle.getFax())) { errors.rejectValue("fax", "code.invalid.fax.format", "invalid-fax-number"); } }
From source file:com.google.ie.common.validation.IdeaValidator.java
@Override public void validate(Object target, Errors errors) { Idea idea = (Idea) target;//from ww w.j av a 2 s. c o m ValidationUtils.rejectIfEmptyOrWhitespace(errors, TITLE, IdeaExchangeErrorCodes.FIELD_REQUIRED, IdeaExchangeConstants.Messages.REQUIRED_FIELD); ValidationUtils.rejectIfEmptyOrWhitespace(errors, DESCRIPTION, IdeaExchangeErrorCodes.FIELD_REQUIRED, IdeaExchangeConstants.Messages.REQUIRED_FIELD); if (!idea.isIdeaRightsGivenUp()) { errors.rejectValue(IDEA_RIGHTS_GIVEN_UP, IdeaExchangeErrorCodes.FIELD_ALWAYS_TRUE, IdeaExchangeConstants.Messages.FIELD_ALWAYS_TRUE); log.warn("Validation Error : " + IDEA_RIGHTS_GIVEN_UP + " -: " + IdeaExchangeConstants.Messages.FIELD_ALWAYS_TRUE); } if (!idea.isIpGivenUp()) { errors.rejectValue(IP_GIVEN_UP, IdeaExchangeErrorCodes.FIELD_ALWAYS_TRUE, IdeaExchangeConstants.Messages.FIELD_ALWAYS_TRUE); log.warn("Validation Error : " + IP_GIVEN_UP + " -: " + IdeaExchangeConstants.Messages.FIELD_ALWAYS_TRUE); } if (!StringUtils.isBlank(idea.getTitle()) && idea.getTitle().trim().length() > LENGTH_500) { errors.rejectValue(TITLE, IdeaExchangeErrorCodes.LENGTH_EXCEED_LIMIT, IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE); log.warn("Validation Error : " + TITLE + " -: " + IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE); } if (!StringUtils.isBlank(idea.getDescription()) && idea.getDescription().trim().length() > LENGTH_3000) { errors.rejectValue(DESCRIPTION, IdeaExchangeErrorCodes.LENGTH_EXCEED_LIMIT, IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE); log.warn("Validation Error : " + DESCRIPTION + " -: " + IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE); } if (!StringUtils.isBlank(idea.getIdeaSummary()) && idea.getIdeaSummary().trim().length() > LENGTH_3000) { errors.rejectValue(IDEA_SUMMARY, IdeaExchangeErrorCodes.LENGTH_EXCEED_LIMIT, IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE); log.warn("Validation Error : " + IDEA_SUMMARY + " -: " + IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE); } if (!StringUtils.isBlank(idea.getMonetization()) && idea.getMonetization().trim().length() > LENGTH_500) { errors.rejectValue(MONETIZATION, IdeaExchangeErrorCodes.LENGTH_EXCEED_LIMIT, IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE); log.warn("Validation Error : " + MONETIZATION + " -: " + IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE); } if (!StringUtils.isBlank(idea.getTargetAudience()) && idea.getTargetAudience().trim().length() > LENGTH_500) { errors.rejectValue(TARGET_AUDIENCE, IdeaExchangeErrorCodes.LENGTH_EXCEED_LIMIT, IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE); log.warn("Validation Error : " + TARGET_AUDIENCE + " -: " + IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE); } if (!StringUtils.isBlank(idea.getCompetition()) && idea.getCompetition().trim().length() > LENGTH_500) { errors.rejectValue(COMPETITION, IdeaExchangeErrorCodes.LENGTH_EXCEED_LIMIT, IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE); log.warn("Validation Error : " + COMPETITION + " -: " + IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE); } if (idea.getTags() != null && idea.getTags().length() > ZERO) { ValidationUtils.invokeValidator(stringValidatorForTagTitle, idea.getTags(), errors); } if (log.isDebugEnabled()) { if (errors.hasErrors()) { log.debug("Validator found " + errors.getErrorCount() + " errors"); for (Iterator<FieldError> iterator = errors.getFieldErrors().iterator(); iterator.hasNext();) { FieldError fieldError = iterator.next(); log.debug("Error found in field: " + fieldError.getField() + " Message :" + fieldError.getDefaultMessage()); } } else { log.debug("Validator found no errors"); } } }
From source file:org.jasig.schedassist.web.owner.schedule.BlockBuilderFormBackingObjectValidator.java
public void validate(Object command, Errors errors) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "startTimePhrase", "field.required", "Start time field is required."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "endTimePhrase", "field.required", "End time field is required."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "daysOfWeekPhrase", "field.required", "Days of week field is required."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "startDatePhrase", "field.required", "Start date field is required."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "endDatePhrase", "field.required", "End date field is required."); BlockBuilderFormBackingObject fbo = (BlockBuilderFormBackingObject) command; if (!StringUtils.isBlank(fbo.getDaysOfWeekPhrase())) { Matcher daysMatcher = DAYS_OF_WEEK_PATTERN.matcher(fbo.getDaysOfWeekPhrase()); if (!daysMatcher.matches()) { errors.rejectValue("daysOfWeekPhrase", "invalid.daysOfWeekPhrase", "Days of week must contain only 'NMTWRFS' (N is Sunday, S is Saturday)."); }//from ww w.ja va 2s . co m } if (!StringUtils.isBlank(fbo.getStartDatePhrase())) { Matcher m = DATE_PATTERN.matcher(fbo.getStartDatePhrase()); if (!m.matches()) { errors.rejectValue("startDatePhrase", "startDatePhrase.invalidFormat", "Start Date must contain 2 digit month, 2 digit day, and 4 digit year (mm/dd/yyyy)."); } } if (!StringUtils.isBlank(fbo.getEndDatePhrase())) { Matcher m = DATE_PATTERN.matcher(fbo.getEndDatePhrase()); if (!m.matches()) { errors.rejectValue("endDatePhrase", "endDatePhrase.invalidFormat", "End Date must contain 2 digit month, 2 digit day, and 4 digit year (mm/dd/yyyy)."); } } SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); Date startDate = null; Date endDate = null; if (!StringUtils.isBlank(fbo.getStartDatePhrase())) { try { startDate = dateFormat.parse(fbo.getStartDatePhrase()); } catch (ParseException e) { errors.rejectValue("startDatePhrase", "field.parseexception", "Start date does not match expected format (mm/dd/yyyy)."); } } if (!StringUtils.isBlank(fbo.getEndDatePhrase())) { try { endDate = dateFormat.parse(fbo.getEndDatePhrase()); } catch (ParseException e) { errors.rejectValue("endDatePhrase", "field.parseexception", "End date does not match expected format (mm/dd/yyyy)."); } } if (null != startDate && null != endDate) { if (CommonDateOperations.approximateDifference(startDate, endDate) > 730) { errors.rejectValue("endDatePhrase", "endDatePhrase.toofarout", "End date is more than 2 years after startDate; please scale back your end date."); } } boolean startTimePhraseValid = true; boolean endTimePhraseValid = true; Matcher startTimeMatcher = null; if (!StringUtils.isBlank(fbo.getStartTimePhrase())) { startTimeMatcher = TIME_PATTERN.matcher(fbo.getStartTimePhrase()); if (!startTimeMatcher.matches()) { errors.rejectValue("startTimePhrase", "field.timeparseexception", "Start time does not match expected format (hh:mm am|pm)."); startTimePhraseValid = false; } else if (Integer.parseInt(startTimeMatcher.group(1)) > 12) { errors.rejectValue("startTimePhrase", "field.militarytime", "Start time should start with a number between 1 and 12; do not use military time."); startTimePhraseValid = false; } } else { startTimePhraseValid = false; } Matcher endTimeMatcher = null; if (!StringUtils.isBlank(fbo.getEndTimePhrase())) { endTimeMatcher = TIME_PATTERN.matcher(fbo.getEndTimePhrase()); if (!endTimeMatcher.matches()) { errors.rejectValue("endTimePhrase", "field.timeparseexception", "End time does not match expected format (hh:mm am|pm)."); endTimePhraseValid = false; } else if (Integer.parseInt(endTimeMatcher.group(1)) > 12) { errors.rejectValue("endTimePhrase", "field.militarytime", "End time should start with a number between 1 and 12; do not use military time."); endTimePhraseValid = false; } } else { endTimePhraseValid = false; } // TODO validate difference between start and end time phrase (>= 15 minutes)not if (startTimePhraseValid && endTimePhraseValid) { long minutesDifference = approximateMinutesDifference(startTimeMatcher, endTimeMatcher); if (minutesDifference < 15) { errors.rejectValue("endTimePhrase", "endTimePhrase.tooshort", "End time has to be at least 15 minutes later than the start time."); } } if (fbo.getVisitorsPerAppointment() < 1) { errors.rejectValue("visitorsPerAppointment", "visitors.toosmall", "Visitors per appointment must be greater than or equal to 1."); } if (fbo.getVisitorsPerAppointment() > 99) { errors.rejectValue("visitorsPerAppointment", "visitors.toosmall", "Maximum allowed value for visitors per appointment is 99."); } if (StringUtils.isBlank(fbo.getMeetingLocation())) { // forcibly set to null to guarantee proper storage fbo.setMeetingLocation(null); } else { if (fbo.getMeetingLocation().length() > 100) { errors.rejectValue("location", "location.toolong", "Location field is too long (" + fbo.getMeetingLocation().length() + "); maximum length is 100 characters."); } } if (!errors.hasErrors()) { // try to run the block builder and report any inputformatexceptions try { if (null != startDate && null != endDate) { AvailableBlockBuilder.createBlocks(fbo.getStartTimePhrase(), fbo.getEndTimePhrase(), fbo.getDaysOfWeekPhrase(), startDate, endDate); } } catch (InputFormatException e) { errors.reject("createBlocksFailed", e.getMessage()); } } }