下面列出了java.beans.PropertyEditorSupport#org.springframework.validation.Errors 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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);
}
}
@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);
}
}
@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);
}
}
@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]));
}
@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);
}
}
@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);
}
@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);
}
}
@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]));
}
/**
*
* @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;
}
@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);
}
@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);
}
@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);
}
}
@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);
}
}
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");
}
}
}
@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");
}
@Override
public void validate(Object target, Errors errors) {
String value = (String) target;
if (invalidValue.equals(value)) {
errors.reject("invalid value '"+invalidValue+"'");
}
}
@Test
public void withNonEscapedErrors() throws Exception {
this.tag.setHtmlEscape(false);
// 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");
}
@Test
void acceptsBackslashAsProfileSeparator() {
AwsParamStoreProperties properties = new AwsParamStoreProperties();
properties.setProfileSeparator("\\");
Errors errors = new BeanPropertyBindingResult(properties, "properties");
properties.validate(properties, errors);
assertThat(errors.getFieldError("profileSeparator")).isNull();
}
@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);
}
@RequestMapping("VIEW")
@RenderMapping
public void myHandle(@ModelAttribute("testBean") TestBean tb, Errors errors, RenderResponse response, PortletSession session) throws IOException {
assertTrue(tb.isJedi());
assertNull(session.getAttribute("testBean"));
response.getWriter().write("test-" + tb.getName() + "-" + errors.getFieldError("age").getCode());
}
@Override
public void validate(Object target, Errors errors, Object... validationHints) {
if (this.targetValidator != null) {
Set<Class<?>> groups = new LinkedHashSet<Class<?>>();
if (validationHints != null) {
for (Object hint : validationHints) {
if (hint instanceof Class) {
groups.add((Class<?>) hint);
}
}
}
processConstraintViolations(
this.targetValidator.validate(target, groups.toArray(new Class<?>[groups.size()])), errors);
}
}
protected int getTargetPage(HttpServletRequest request, Object command, Errors errors, int currentPage) {
OrderForm orderForm = (OrderForm) command;
if (currentPage == 0 && orderForm.isShippingAddressRequired()) {
return 1;
}
else {
return 2;
}
}
@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);
}
public String handle(
@CookieValue("cookie") int cookieV,
@PathVariable("pathvar") String pathvarV,
@RequestHeader("header") String headerV,
@RequestHeader(defaultValue = "#{systemProperties.systemHeader}") String systemHeader,
@RequestHeader Map<String, Object> headerMap,
@RequestParam("dateParam") Date dateParam,
@RequestParam Map<String, Object> paramMap,
String paramByConvention,
@Value("#{request.contextPath}") String value,
@ModelAttribute("modelAttr") @Valid TestBean modelAttr,
Errors errors,
TestBean modelAttrByConvention,
Color customArg,
HttpServletRequest request,
HttpServletResponse response,
@SessionAttribute TestBean sessionAttribute,
@RequestAttribute TestBean requestAttribute,
User user,
@ModelAttribute OtherUser otherUser,
Model model,
UriComponentsBuilder builder) {
model.addAttribute("cookie", cookieV).addAttribute("pathvar", pathvarV).addAttribute("header", headerV)
.addAttribute("systemHeader", systemHeader).addAttribute("headerMap", headerMap)
.addAttribute("dateParam", dateParam).addAttribute("paramMap", paramMap)
.addAttribute("paramByConvention", paramByConvention).addAttribute("value", value)
.addAttribute("customArg", customArg).addAttribute(user)
.addAttribute("sessionAttribute", sessionAttribute)
.addAttribute("requestAttribute", requestAttribute)
.addAttribute("url", builder.path("/path").build().toUri());
assertNotNull(request);
assertNotNull(response);
return "viewName";
}
@Override
public void validate(@Nullable Object target, Errors errors) {
String value = (String) target;
if (invalidValue.equals(value)) {
errors.reject("invalid value '"+invalidValue+"'");
}
}
/**
* The combinaison DOMAIN + MANUAL is forbidden. That's what we try to
* determine here
* @param ccc
* @param errors
* @return
*/
private boolean checkTypeAudit(CreateContractCommand ccc, Errors errors) {
// TODO Auto-generated method stub
// taoufiq
boolean manual = false;
boolean scenario = false;
boolean upload = false;
boolean pages = false;
Map<String, Boolean> functionalityMap = ccc.getFunctionalityMap();
for (Entry<String, Boolean> it : functionalityMap.entrySet()) {
switch (it.getKey()) {
case "MANUAL":
if (it.getValue() != null) {
manual = true;
}
break;
case "SCENARIO":
if (it.getValue() != null) {
scenario = true;
}
break;
case "UPLOAD":
if (it.getValue() != null) {
upload = true;
}
break;
case "PAGES":
if (it.getValue() != null) {
pages = true;
}
break;
}
}
if (!pages && !upload && !scenario && manual) {
return false;
}
return true;
}
/** @see org.springframework.validation.Validator#validate(Object, Errors). */
public void validate(Object aCmd, Errors aErrors) {
CreateUserCommand cmd = (CreateUserCommand) aCmd;
ValidationUtils.rejectIfEmptyOrWhitespace(aErrors, CreateUserCommand.PARAM_ACTION, "required", getObjectArrayForLabel(CreateUserCommand.PARAM_ACTION), "Action command is a required field.");
if (CreateUserCommand.ACTION_SAVE.equals(cmd.getAction())) {
//If an Update or a Insert check the following
ValidationUtils.rejectIfEmptyOrWhitespace(aErrors, CreateUserCommand.PARAM_FIRSTNAME, "required", getObjectArrayForLabel(CreateUserCommand.PARAM_FIRSTNAME), "Firstname is a required field.");
ValidationUtils.rejectIfEmptyOrWhitespace(aErrors, CreateUserCommand.PARAM_LASTNAME, "required", getObjectArrayForLabel(CreateUserCommand.PARAM_LASTNAME), "Lastname is a required field.");
ValidationUtils.rejectIfEmptyOrWhitespace(aErrors, CreateUserCommand.PARAM_USERNAME, "required", getObjectArrayForLabel(CreateUserCommand.PARAM_USERNAME), "Username is a required field.");
ValidationUtils.rejectIfEmptyOrWhitespace(aErrors, CreateUserCommand.PARAM_AGENCY_OID, "required", getObjectArrayForLabel(CreateUserCommand.PARAM_AGENCY_OID), "Agency is a required field.");
ValidationUtils.rejectIfEmptyOrWhitespace(aErrors, CreateUserCommand.PARAM_EMAIL, "required", getObjectArrayForLabel(CreateUserCommand.PARAM_EMAIL), "Email is a required field.");
ValidatorUtil.validateStringMaxLength(aErrors, cmd.getAddress() ,200,"string.maxlength",getObjectArrayForLabelAndInt(CreateUserCommand.PARAM_ADDRESS,200),"Address field too long");
if (cmd.getEmail() != null && cmd.getEmail().length() > 0) {
ValidatorUtil.validateRegEx(aErrors, cmd.getEmail(), ValidatorUtil.EMAIL_VALIDATION_REGEX, "invalid.email",getObjectArrayForLabel(CreateUserCommand.PARAM_EMAIL),"the email address is invalid" );
}
if (cmd.getOid() == null) {
//for a brand new user validate these things
if (cmd.isExternalAuth() == false) {
//Only check the password fields if not using an external Authentication Source
ValidationUtils.rejectIfEmptyOrWhitespace(aErrors, CreateUserCommand.PARAM_PASSWORD, "required", getObjectArrayForLabel(CreateUserCommand.PARAM_PASSWORD), "Password is a required field.");
ValidationUtils.rejectIfEmptyOrWhitespace(aErrors, CreateUserCommand.PARAM_CONFIRM_PASSWORD, "required", getObjectArrayForLabel(CreateUserCommand.PARAM_CONFIRM_PASSWORD), "Confirm password is a required field.");
ValidatorUtil.validateValueMatch(aErrors, cmd.getPassword(), cmd.getConfirmPassword(), "string.match", getObjectArrayForTwoLabels(CreateUserCommand.PARAM_PASSWORD, CreateUserCommand.PARAM_CONFIRM_PASSWORD), "Your passwords did not match.");
ValidatorUtil.validateNewPassword(aErrors,cmd.getPassword(),"password.strength.failure", new Object[] {}, "Your password must have at least 1 Upper case letter, 1 lower case letter and a number.");
}
} else {
//for existing users validate these additional things
}
}
}
public void validate(Object obj, Errors errors) {
logger.debug("Validator called");
UserForm newUser = (UserForm) obj;
validateUsername(errors, newUser);
validatePassword(errors, newUser);
validateConfirmPassword(errors, newUser);
validateEmail(errors, newUser.getEmail());
writeResultToLog(errors);
}
@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");
}
}
/**
* Helper method to validate a new password for a user id.
* @param aErrors The errors object to populate
* @param aNewPwd the new password for the user id
* @param aErrorCode the error code
* @param aValues the values
* @param aFailureMessage the default message
*/
public static void validateNewPassword(Errors aErrors, String aNewPwd, String aErrorCode, Object[] aValues, String aFailureMessage) {
if (aNewPwd != null && !aNewPwd.trim().equals("")) {
Perl5Compiler ptrnCompiler = new Perl5Compiler();
Perl5Matcher matcher = new Perl5Matcher();
try {
Perl5Pattern lcCharPattern = (Perl5Pattern) ptrnCompiler.compile("[a-z]");
Perl5Pattern ucCharPattern = (Perl5Pattern) ptrnCompiler.compile("[A-Z]");
Perl5Pattern numericPattern = (Perl5Pattern) ptrnCompiler.compile("[0-9]");
if (aNewPwd.length() < 6) {
aErrors.reject(aErrorCode, aValues, aFailureMessage);
return;
}
if (!matcher.contains(aNewPwd, lcCharPattern)) {
aErrors.reject(aErrorCode, aValues, aFailureMessage);
return;
}
if (!matcher.contains(aNewPwd, ucCharPattern)) {
aErrors.reject(aErrorCode, aValues, aFailureMessage);
return;
}
if (!matcher.contains(aNewPwd, numericPattern)) {
aErrors.reject(aErrorCode, aValues, aFailureMessage);
return;
}
}
catch (MalformedPatternException e) {
LogFactory.getLog(ValidatorUtil.class).fatal("Perl patterns malformed: " + e.getMessage(), e);
}
}
}