Java Code Examples for org.apache.wicket.validation.IValidatable

The following examples show how to use org.apache.wicket.validation.IValidatable. These examples are extracted from open source projects. 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 Project: inception   Source File: RecommenderEditorPanel.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void validate(IValidatable<String> aValidatable)
{
    String newName = aValidatable.getValue();
    Recommender currentRecommender = recommender.getObject();
    Optional<Recommender> recommenderWithNewName = recommendationService
            .getRecommender(project.getObject(), newName);
    // Either there should be no recommender with the new name already existing or it should
    // be the recommender we are currently editing (i.e. the name has not changed)
    if (
            recommenderWithNewName.isPresent() &&
            !Objects.equals(recommenderWithNewName.get().getId(),
                    currentRecommender.getId())
    ) {
        aValidatable.error(new ValidationError(
                "Another recommender with the same name exists. Please try a different name"));
    }
}
 
Example 2
Source Project: the-app   Source File: RegistrationPage.java    License: Apache License 2.0 6 votes vote down vote up
private Component usernameField() {
    TextField<String> username = new TextField<>("username", new PropertyModel<>(userInfoModel, "username"));
    username.add(new IValidator<String>() {
        private static final long serialVersionUID = 5670647976176255775L;

        @Override
        public void validate(IValidatable<String> userNameValidatable) {
            UserInfo userInfo = userService.findByUsername(userNameValidatable.getValue());
            if (userInfo != null) {
                error("The entered username is already in use.");
            }
        }
    });
    username.setRequired(true);
    return username;
}
 
Example 3
Source Project: openmeetings   Source File: StrongPasswordValidator.java    License: Apache License 2.0 6 votes vote down vote up
private void error(IValidatable<String> pass, String key, Map<String, Object> params) {
	if (web) {
		ValidationError err = new ValidationError().addKey(key);
		if (params != null) {
			err.setVariables(params);
		}
		pass.error(err);
	} else {
		String msg = LabelDao.getString(key, 1L);
		if (params != null && !params.isEmpty() && !Strings.isEmpty(msg)) {
			for (Map.Entry<String, Object> e : params.entrySet()) {
				msg = msg.replace(String.format("${%s}", e.getKey()), "" + e.getValue());
			}
		}
		log.warn(msg);
		pass.error(new ValidationError(msg));
	}
}
 
Example 4
Source Project: openmeetings   Source File: StrongPasswordValidator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void validate(IValidatable<String> pass) {
	if (badLength(pass.getValue())) {
		error(pass, "bad.password.short", Map.of("0", getMinPasswdLength()));
	}
	if (noLowerCase(pass.getValue())) {
		error(pass, "bad.password.lower");
	}
	if (noUpperCase(pass.getValue())) {
		error(pass, "bad.password.upper");
	}
	if (noDigit(pass.getValue())) {
		error(pass, "bad.password.digit");
	}
	if (noSymbol(pass.getValue())) {
		error(pass, "bad.password.special");
	}
	if (hasStopWords(pass.getValue())) {
		error(pass, "bad.password.stop");
	}
}
 
Example 5
Source Project: openmeetings   Source File: ForgetPasswordDialog.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void onValidate() {
	String n = name.getConvertedInput();
	if (n != null) {
		IValidatable<String> val = new Validatable<>(n);
		Type type = rg.getConvertedInput();
		if (type == Type.email) {
			emailValidator.validate(val);
			if (!val.isValid()) {
				error(getString("234"));
			}
		}
		if (type == Type.login && n.length() < getMinLoginLength()) {
			error(getString("104"));
		}
	}
}
 
Example 6
Source Project: webanno   Source File: ManageUsersPage.java    License: Apache License 2.0 6 votes vote down vote up
private void validateRoles(IValidatable<Collection<Role>> aValidatable)
{
    Collection<Role> newRoles = aValidatable.getValue();
    if (newRoles.isEmpty()) {
        aValidatable.error(new ValidationError()
                .setMessage("A user has to have at least one role."));
    }
    // enforce users to have at least the ROLE_USER role
    if (!newRoles.contains(Role.ROLE_USER)) {
        aValidatable.error(new ValidationError()
                .setMessage("Every user must have 'ROLE_USER'."));
    }
    // don't let an admin user strip himself of admin rights
    if (userRepository.getCurrentUser().equals(getModelObject())
            && !newRoles.contains(Role.ROLE_ADMIN)) {
        aValidatable.error(new ValidationError()
                .setMessage("You cannot remove your own admin status."));
    }
}
 
Example 7
/**
 * @see AbstractValidator#onValidate(IValidatable)
 */
protected void onValidate(IValidatable validatable)
{
	//setup list
	List<String> regexs = new ArrayList<String>();
	regexs.add("\\+?([0-9]+|\\s+)+(\\w+)?+"); //matches 1,2,3,5 with 10
	regexs.add("\\({1}[0-9]+\\){1}([0-9]+|\\s+)+(\\w+)?+"); //matches 4 with 10
	regexs.add("([0-9]+(\\-|\\.)?)+(\\w+)?+"); //matches 6, 7 with 10
	regexs.add("\\({1}[0-9]+\\){1}([0-9]+|\\s+|\\-?|\\.?)+(\\w+)?+"); //matches 8,9 with 10
	
	//check each, if none, error
	for(String r: regexs) {
		Pattern p = Pattern.compile(r);
		if (p.matcher((String)validatable.getValue()).matches()) {
			return;
		}
	}
	
	//if we haven't matched, error.
	error(validatable);
}
 
Example 8
Source Project: ontopia   Source File: IdentityValidator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void onValidate(IValidatable<String> validatable) {
  String value = validatable.getValue();
  if (value == null) return;
  LocatorIF locator;
  try {
    locator = new URILocator(value);
  } catch (Exception e) {
    reportError("validators.IdentityValidator.invalidURI", value);
    return;
  }

  Topic topic = fieldInstanceModel.getFieldInstance().getInstance();
  TopicMap topicMap = topic.getTopicMap();
  TopicMapIF topicMapIf = topicMap.getTopicMapIF();
  TopicIF topicIf = topic.getTopicIF();

  TopicIF otopic = topicMapIf.getTopicBySubjectIdentifier(locator);
  if (otopic != null && !Objects.equals(topicIf, otopic))
    reportError("validators.IdentityValidator.subjectIdentifierClash", value);

  otopic = topicMapIf.getTopicBySubjectLocator(locator);
  if (otopic != null && !Objects.equals(topicIf, otopic))
    reportError("validators.IdentityValidator.subjectLocatorClash", value);
}
 
Example 9
Source Project: ontopia   Source File: DateFormatValidator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void onValidate(IValidatable<String> validatable) {
  final String value = validatable.getValue();
  if (value == null) return;
  try {
    DateFormat df = createDateFormat();
    df.parse(value);
  } catch (ParseException e) {
    String message = Application.get().getResourceSettings().getLocalizer().getString(resourceKey(), (Component)null, 
          new Model<Serializable>(new Serializable() {
            @SuppressWarnings("unused")
            public String getValue() {
              return value;
            }
          }));
    component.error(AbstractFieldInstancePanel.createErrorMessage(fieldInstanceModel, new Model<String>(message)));
  }
}
 
Example 10
Source Project: ontopia   Source File: RegexValidator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void onValidate(IValidatable<String> validatable) {
  final String value = validatable.getValue();
  final String regex = getRegex();
  
  if (value == null) return;
  try {
    if (value.matches(regex))
      return;
    else
      reportError(resourceKeyInvalidValue(), value, regex);
            
  } catch (PatternSyntaxException e) {
    reportError(resourceKeyInvalidRegex(), value, regex);
  }
}
 
Example 11
Source Project: ontopia   Source File: URIValidator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void onValidate(IValidatable<String> validatable) {
  final String value = validatable.getValue();
  if (value == null) return;
  try {
    new URILocator(value);
  } catch (Exception e) {
    String message = Application.get().getResourceSettings().getLocalizer().getString(resourceKey(), (Component)null, 
        new Model<Serializable>(new Serializable() {
          @SuppressWarnings("unused")
          public String getValue() {
            return value;
          }
        }));
    component.error(AbstractFieldInstancePanel.createErrorMessage(fieldInstanceModel, new Model<String>(message)));
  }
}
 
Example 12
public void validate(IValidatable<Object> validatable) {
	Validator validator = HibernateValidatorProperty.validatorFactory.getValidator();
	
	@SuppressWarnings("unchecked")
	Set<ConstraintViolation<Object>> violations = validator.validateValue((Class<Object>)beanModel.getObject().getClass(), propertyName, validatable.getValue());
	
	if(!violations.isEmpty()){
		for(ConstraintViolation<?> violation : violations){
			ValidationError error = new ValidationError(violation.getMessage());
			
			String key = violation.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName();
			if(getValidatorPrefix()!=null) key = getValidatorPrefix()+"."+key;
			
			error.addKey(key);
			error.setVariables(new HashMap<String, Object>(violation.getConstraintDescriptor().getAttributes()));
			
			//remove garbage from the attributes
			error.getVariables().remove("payload");
			error.getVariables().remove("message");
			error.getVariables().remove("groups");
			
			validatable.error(error);
		}
	}
}
 
Example 13
Source Project: AppStash   Source File: RegistrationPage.java    License: Apache License 2.0 6 votes vote down vote up
private Component usernameField() {
    TextField<String> username = new TextField<>("username", new PropertyModel<>(userInfoModel, "username"));
    username.add(new IValidator<String>() {
        private static final long serialVersionUID = 5670647976176255775L;

        @Override
        public void validate(IValidatable<String> userNameValidatable) {
            UserInfo userInfo = userService.findByUsername(userNameValidatable.getValue());
            if (userInfo != null) {
                error("The entered username is already in use.");
            }
        }
    });
    username.setRequired(true);
    return username;
}
 
Example 14
/**
 * @see AbstractValidator#onValidate(IValidatable)
 */
protected void onValidate(IValidatable validatable)
{
	//setup list
	List<String> regexs = new ArrayList<String>();
	regexs.add("\\+?([0-9]+|\\s+)+(\\w+)?+"); //matches 1,2,3,5 with 10
	regexs.add("\\({1}[0-9]+\\){1}([0-9]+|\\s+)+(\\w+)?+"); //matches 4 with 10
	regexs.add("([0-9]+(\\-|\\.)?)+(\\w+)?+"); //matches 6, 7 with 10
	regexs.add("\\({1}[0-9]+\\){1}([0-9]+|\\s+|\\-?|\\.?)+(\\w+)?+"); //matches 8,9 with 10
	
	//check each, if none, error
	for(String r: regexs) {
		Pattern p = Pattern.compile(r);
		if (p.matcher((String)validatable.getValue()).matches()) {
			return;
		}
	}
	
	//if we haven't matched, error.
	error(validatable);
}
 
Example 15
Source Project: inception   Source File: IriValidator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void validate(IValidatable<String> validatable)
{
    if (!URIUtil.isValidURIReference(validatable.getValue())) {
        validatable.error(new ValidationError(this));
    }
}
 
Example 16
Source Project: inception   Source File: GeneralSettingsPanel.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void validate(IValidatable<String> aValidatable)
{
    String kbName = aValidatable.getValue();
    if (kbService.knowledgeBaseExists(projectModel.getObject(), kbName)) {
        String message = String.format(
                "There already exists a knowledge base in the project with name: [%s]!",
                kbName);
        aValidatable.error(new ValidationError(message));
    }
}
 
Example 17
Source Project: onedev   Source File: ParamListEditPanel.java    License: MIT License 5 votes vote down vote up
@Override
protected void onInitialize() {
	super.onInitialize();
	
	add(newParamsView(getDefaultParamBean().getClass()));
	
	add(new INullAcceptingValidator<List<Serializable>>() {

		@SuppressWarnings("deprecation")
		@Override
		public void validate(IValidatable<List<Serializable>> validatable) {
			int index = 0;
			for (Serializable each: validatable.getValue()) {
				ParamSupply param = (ParamSupply) each;
				if (param.getValuesProvider() instanceof SpecifiedValues) {
					SpecifiedValues specifiedValues = (SpecifiedValues) param.getValuesProvider();
					try {
						ParamSupply.validateParamValues(specifiedValues.getValues());
					} catch (ValidationException e) {
						if (!getFlag(FLAG_RENDERING)) {
							RepeatingView paramsView = (RepeatingView) get("params");
							paramsView.get(index).get("values").error(e.getMessage());
						}
					}
				}
				index++;
			}
		}
		
	});
	
	setOutputMarkupId(true);
}
 
Example 18
Source Project: openmeetings   Source File: RegisterDialog.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void onInitialize() {
	super.onInitialize();
	add(feedback.setOutputMarkupId(true));
	add(firstNameField = new RequiredTextField<>("firstName", new PropertyModel<String>(RegisterDialog.this, "firstName")));
	add(lastNameField = new RequiredTextField<>("lastName", new PropertyModel<String>(RegisterDialog.this, "lastName")));
	add(loginField = new RequiredTextField<>("login", new PropertyModel<String>(RegisterDialog.this, "login")));
	add(passwordField = new PasswordTextField("password", new PropertyModel<String>(RegisterDialog.this, "password")));
	add(confirmPassword = new PasswordTextField("confirmPassword", new Model<String>()).setResetPassword(true));
	add(emailField = new RequiredTextField<>("email", new PropertyModel<String>(RegisterDialog.this, "email")) {
		private static final long serialVersionUID = 1L;

		@Override
		protected String[] getInputTypes() {
			return new String[] {"email"};
		}
	});
	add(captcha = new Captcha("captcha"));
	firstNameField.setLabel(new ResourceModel("117"));
	lastNameField.setLabel(new ResourceModel("136"));
	loginField.add(minimumLength(getMinLoginLength())).setLabel(new ResourceModel("114"));
	passwordField.setResetPassword(true).add(new StrongPasswordValidator(new User()) {
		private static final long serialVersionUID = 1L;

		@Override
		public void validate(IValidatable<String> pass) {
			User u = new User();
			u.setLogin(loginField.getRawInput());
			u.setAddress(new Address());
			u.getAddress().setEmail(emailField.getRawInput());
			setUser(u);
			super.validate(pass);
		}
	}).setLabel(new ResourceModel("110"));
	confirmPassword.setLabel(new ResourceModel("116"));
	emailField.add(RfcCompliantEmailAddressValidator.getInstance()).setLabel(new ResourceModel("119"));
	AjaxButton ab = new AjaxButton("submit") { // FAKE button so "submit-on-enter" works as expected
		private static final long serialVersionUID = 1L;
	};
	add(ab);
	setDefaultButton(ab);
}
 
Example 19
Source Project: openmeetings   Source File: Captcha.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void onInitialize() {
	super.onInitialize();
	add(captchaText.setLabel(new ResourceModel("captcha.text")).add(new IValidator<String>() {
		private static final long serialVersionUID = 1L;

		@Override
		public void validate(IValidatable<String> validatable) {
			if (!randomText.equals(validatable.getValue())) {
				validatable.error(new ValidationError(getString("bad.captcha.text")));
			}
		}
	}).setOutputMarkupId(true));
	add(new BootstrapAjaxLink<>("refresh", Model.of(""), Buttons.Type.Outline_Info, new ResourceModel("lbl.refresh")) {
		private static final long serialVersionUID = 1L;

		@Override
		public void onClick(AjaxRequestTarget target) {
			captchaImageResource.invalidate();
			target.add(captcha);
		}

		@Override
		protected Icon newIcon(String markupId) {
			return new Icon(markupId, FontAwesome5IconType.sync_s);
		}
	});
}
 
Example 20
Source Project: webanno   Source File: TagEditorPanel.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void validate(IValidatable<String> aValidatable)
{
    String newName = aValidatable.getValue();
    String oldName = aValidatable.getModel().getObject();
    if (!StringUtils.equals(newName, oldName) && isNotBlank(newName)
            && annotationSchemaService.existsTag(newName, selectedTagSet.getObject())) {
        aValidatable.error(new ValidationError(
                "Another tag with the same name exists. Please try a different name"));
    }
}
 
Example 21
Source Project: webanno   Source File: TagSetEditorPanel.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void validate(IValidatable<String> aValidatable)
{
    String newName = aValidatable.getValue();
    String oldName = aValidatable.getModel().getObject();
    if (!StringUtils.equals(newName, oldName) && isNotBlank(newName)
            && annotationSchemaService.existsTagSet(newName, selectedProject.getObject())) {
        aValidatable.error(new ValidationError(
                "Another tag set with the same name exists. Please try a different name"));
    }
}
 
Example 22
Source Project: webanno   Source File: ToggleBox.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void validate(IValidatable<Boolean> aValidatable)
{
    if (aValidatable.getValue() == null) {
        aValidatable.error(new ValidationError("You need to make a choice."));
    }
}
 
Example 23
Source Project: webanno   Source File: KeyBindingsConfigurationPanel.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void validate(IValidatable<String> aValidatable)
{
    String keyCombo = aValidatable.getValue();
    KeyBinding keyBinding = new KeyBinding(keyCombo, null);
    if (!keyBinding.isValid()) {
        aValidatable.error(new ValidationError("Invalid key combo: [" + keyCombo + "]"));
    }
}
 
Example 24
Source Project: webanno   Source File: ProjectDetailPanel.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void validate(IValidatable<String> aValidatable)
{
    String newName = aValidatable.getValue();
    if (isNotBlank(newName) && !NameUtil.isNameValid(newName)) {
        aValidatable.error(new ValidationError(
                "Project name shouldn't contain characters such as /\\*?&!$+[^]"));
    }
}
 
Example 25
Source Project: webanno   Source File: ProjectDetailPanel.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void validate(IValidatable<String> aValidatable)
{
    String newName = aValidatable.getValue();
    String oldName = aValidatable.getModel().getObject();
    if (!StringUtils.equals(newName, oldName) && isNotBlank(newName)
            && projectService.existsProject(newName)) {
        aValidatable.error(new ValidationError(
                "Another project with the same name exists. Please try a different name"));
    }
}
 
Example 26
Source Project: webanno   Source File: ManageUsersPage.java    License: Apache License 2.0 5 votes vote down vote up
private void validateUsername(IValidatable<String> aValidatable)
{
    if (userRepository.exists(aValidatable.getValue()) && isCreate) {
        aValidatable.error(new ValidationError().addKey("username.alreadyExistsError")
                .setVariable("name", aValidatable.getValue()));
    }
    else if (aValidatable.getValue().contains(" ")) {
        aValidatable.error(new ValidationError().addKey("username.containsSpaceError"));
    }
    else if (!NameUtil.isNameValid(aValidatable.getValue())) {
        aValidatable.error(new ValidationError().addKey("username.invalidCharactersError"));
    }
}
 
Example 27
Source Project: webanno   Source File: ManageUsersPage.java    License: Apache License 2.0 5 votes vote down vote up
private void validateEnabled(IValidatable<Boolean> aValidatable)
{
    if (!aValidatable.getValue()
            && userRepository.getCurrentUser().equals(getModelObject())) {
        aValidatable.error(new ValidationError()
                .setMessage("You cannot disable your own account."));
    }
}
 
Example 28
Source Project: wicket-spring-boot   Source File: UsernameTextField.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void validate(IValidatable<String> validatable) {
	final String field = validatable.getValue();
	if(service.usernameExists(field)){
		ValidationError error = new ValidationError();
		error.setMessage(getString(getClass().getSimpleName()));
		validatable.error(error);
	}
	
}
 
Example 29
@Override
public void validate(IValidatable<String> validatable) {
	super.validate(validatable);
	
	final String value = validatable.getValue();
	
	if(value==null || value.length()==0) return;
	
	try {
		if(!isNIFValid(value)) validatable.error(new ValidationError(this));
	} catch(NumberFormatException e){
		validatable.error(new ValidationError(this));
	}
}
 
Example 30
Source Project: wicket-orientdb   Source File: DateFormatValidator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void validate(IValidatable<String> validatable) {
	String pattern = validatable.getValue();
	try {
		newDateFormat(pattern).format(new Date());
	} catch (Exception e) {
		ValidationError error = new ValidationError(this);
		error.setVariable("pattern", pattern);
		validatable.error(decorate(error, validatable));
	}
}