Example usage for org.apache.wicket.validation IValidator IValidator

List of usage examples for org.apache.wicket.validation IValidator IValidator

Introduction

In this page you can find the example usage for org.apache.wicket.validation IValidator IValidator.

Prototype

IValidator

Source Link

Usage

From source file:ar.edu.udc.cirtock.view.intranet.negocio.FormularioInsumo.java

License:Apache License

public FormularioInsumo(final PageParameters parameters) {

    super(parameters);

    add(new FeedbackPanel("feedbackErrors", new ExactLevelFeedbackMessageFilter(FeedbackMessage.ERROR)));
    formulario = new Form("formulario_insumo");

    nombre = new RequiredTextField<String>("nombre", new Model());

    nombre.add(new IValidator<String>() {
        @Override/*w ww  .  j a  v  a2  s  . c o  m*/
        public void validate(IValidatable<String> validatable) {
            String nombre = validatable.getValue().trim().toUpperCase();
            if (!nombre.matches("^[\\w\\s]{3,20}$")) {
                ValidationError error = new ValidationError();
                error.setMessage("El campo 'nombre' no es valido");
                validatable.error(error);
            }
        }

    });
    formulario.add(nombre);

    descripcion = new RequiredTextField<String>("descripcion", new Model());

    descripcion.add(new IValidator<String>() {
        @Override
        public void validate(IValidatable<String> validatable) {
            String descripcion = validatable.getValue().trim().toUpperCase();
            if (!descripcion.matches("^[A-Za-z  ]{3,50}$")) {
                ValidationError error = new ValidationError();
                error.setMessage("El campo 'descripcion' no es valido");
                validatable.error(error);
            }
        }

    });
    formulario.add(descripcion);

    cantidad = new NumberTextField<Integer>("cantidad", new Model());
    cantidad.setType(Integer.class);
    cantidad.add(new IValidator<Integer>() {
        @Override
        public void validate(IValidatable<Integer> validatable) {
            Integer cantidad = validatable.getValue();
            if (cantidad < 0) {
                ValidationError error = new ValidationError();
                error.setMessage("El campo 'cantidad' no es valido");
                validatable.error(error);
            }
        }
    });

    formulario.add(cantidad);

    formulario.add(new Button("enviar") {

        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        public void onSubmit() {
            String desc = (String) descripcion.getModelObject();
            String nomb = (String) nombre.getModelObject();
            Integer cant = cantidad.getModelObject();
            Connection conn = null;
            try {

                conn = CirtockConnection.getConection("cirtock", "cirtock", "cirtock");
                Insumo ins = new Insumo();
                ins.setDescripcion(desc);
                ins.setNombre(nomb);
                ins.setCantidad(cant);
                ins.insert("", conn);

            } catch (CirtockException e) {
                System.out.println("Error al acceder a la base de datos");
            } finally {
                try {
                    conn.close();
                } catch (SQLException e) {
                    ;
                }
            }
            setResponsePage(InsumoPage.class);
        };
    });

    add(formulario);
}

From source file:com.cubeia.backoffice.web.wallet.AccountList.java

License:Open Source License

/**
* Constructor that is invoked when page is invoked without a session.
* 
* @param parameters//from  ww w  .j  a v a 2 s  .  c  o m
*            Page parameters
*/
public AccountList(final PageParameters parameters) {
    Form<AccountList> searchForm = new Form<AccountList>("searchForm",
            new CompoundPropertyModel<AccountList>(this));
    TextField<Long> idField = new TextField<Long>("userId");
    searchForm.add(idField);
    TextField<Long> userNameField = new TextField<Long>("accountId");
    searchForm.add(userNameField);

    final CheckBoxMultipleChoice<AccountStatus> statusesChoice = new CheckBoxMultipleChoice<AccountStatus>(
            "includeStatuses", Arrays.asList(AccountStatus.values()));
    statusesChoice.setSuffix(" ");
    statusesChoice.add(new IValidator<Collection<AccountStatus>>() {
        private static final long serialVersionUID = 1L;

        @Override
        public void validate(IValidatable<Collection<AccountStatus>> validatable) {
            if (statusesChoice.getInputAsArray() == null) {
                ValidationError error = new ValidationError().setMessage("Select one or more status");
                validatable.error(error);
            }
        }

    });

    searchForm.add(statusesChoice);

    CheckBoxMultipleChoice<AccountType> typesChoice = new CheckBoxMultipleChoice<AccountType>("includeTypes",
            asList(AccountType.values()));
    typesChoice.setSuffix(" ");
    searchForm.add(typesChoice);

    add(searchForm);
    add(new FeedbackPanel("feedback"));

    ISortableDataProvider<Account, String> dataProvider = new AccountDataProvider();
    ArrayList<IColumn<Account, String>> columns = new ArrayList<IColumn<Account, String>>();

    columns.add(new AbstractColumn<Account, String>(new Model<String>("Account Id")) {
        private static final long serialVersionUID = 1L;

        @Override
        public void populateItem(Item<ICellPopulator<Account>> item, String componentId,
                IModel<Account> model) {
            Account account = model.getObject();
            Long accountId = account.getId();
            LabelLinkPanel panel = new LabelLinkPanel(componentId, "" + accountId,
                    "details for account id " + accountId, AccountDetails.class,
                    params(AccountDetails.PARAM_ACCOUNT_ID, accountId));
            item.add(panel);
        }

        @Override
        public boolean isSortable() {
            return true;
        }

        @Override
        public String getSortProperty() {
            return AccountsOrder.ID.name();
        }
    });

    columns.add(new AbstractColumn<Account, String>(new Model<String>("User id")) {
        private static final long serialVersionUID = 1L;

        @Override
        public void populateItem(Item<ICellPopulator<Account>> item, String componentId,
                IModel<Account> model) {
            Account account = model.getObject();
            Long userId = account.getUserId();
            Component panel = new LabelLinkPanel(componentId, "" + userId, UserSummary.class,
                    params(UserSummary.PARAM_USER_ID, userId)).setVisible(userId != null);
            item.add(panel);
        }

        @Override
        public boolean isSortable() {
            return true;
        }

        @Override
        public String getSortProperty() {
            return AccountsOrder.USER_ID.name();
        }
    });

    columns.add(new PropertyColumn<Account, String>(new Model<String>("Account name"),
            AccountsOrder.ACCOUNT_NAME.name(), "information.name"));
    columns.add(new PropertyColumn<Account, String>(new Model<String>("Status"), AccountsOrder.STATUS.name(),
            "status"));
    columns.add(
            new PropertyColumn<Account, String>(new Model<String>("Type"), AccountsOrder.TYPE.name(), "type"));
    columns.add(new PropertyColumn<Account, String>(new Model<String>("Currency"), "currencyCode"));
    columns.add(new DatePropertyColumn<Account, String>(new Model<String>("Creation date"),
            AccountsOrder.CREATION_DATE.name(), "created"));
    columns.add(new DatePropertyColumn<Account, String>(new Model<String>("Close date"),
            AccountsOrder.CLOSE_DATE.name(), "closed"));
    columns.add(new AbstractColumn<Account, String>(new Model<String>("Actions")) {
        private static final long serialVersionUID = 1L;

        @Override
        public void populateItem(Item<ICellPopulator<Account>> item, String componentId,
                IModel<Account> model) {
            Account account = model.getObject();
            Long accountId = account.getId();
            LabelLinkPanel panel = new LabelLinkPanel(componentId, "transactions",
                    "transactions involving account id " + accountId, TransactionList.class,
                    params(TransactionList.PARAM_ACCOUNT_ID, accountId));
            item.add(panel);
        }
    });

    AjaxFallbackDefaultDataTable<Account, String> userTable = new AjaxFallbackDefaultDataTable<Account, String>(
            "accountTable", columns, dataProvider, 20);
    add(userTable);
}

From source file:com.cubeia.games.poker.admin.wicket.pages.wallet.AccountList.java

License:Open Source License

/**
* Constructor that is invoked when page is invoked without a session.
* 
* @param parameters//  w w w .  j a  v  a  2 s  .co m
*            Page parameters
*/
public AccountList(final PageParameters parameters) {
    super(parameters);
    Form<AccountList> searchForm = new Form<AccountList>("searchForm",
            new CompoundPropertyModel<AccountList>(this));
    TextField<Long> idField = new TextField<Long>("userId");
    searchForm.add(idField);
    TextField<Long> userNameField = new TextField<Long>("accountId");
    searchForm.add(userNameField);

    final CheckBoxMultipleChoice<AccountStatus> statusesChoice = new CheckBoxMultipleChoice<AccountStatus>(
            "includeStatuses", Arrays.asList(AccountStatus.values()));
    statusesChoice.setSuffix(" ");
    statusesChoice.add(new IValidator<Collection<AccountStatus>>() {
        private static final long serialVersionUID = 1L;

        @Override
        public void validate(IValidatable<Collection<AccountStatus>> validatable) {
            if (statusesChoice.getInputAsArray() == null) {
                ValidationError error = new ValidationError().setMessage("Select one or more status");
                validatable.error(error);
            }
        }

    });

    searchForm.add(statusesChoice);

    CheckBoxMultipleChoice<AccountType> typesChoice = new CheckBoxMultipleChoice<AccountType>("includeTypes",
            asList(AccountType.values()));
    typesChoice.setSuffix(" ");
    searchForm.add(typesChoice);

    add(searchForm);
    add(new FeedbackPanel("feedback"));

    ISortableDataProvider<Account, String> dataProvider = new AccountDataProvider();
    ArrayList<IColumn<Account, String>> columns = new ArrayList<IColumn<Account, String>>();

    columns.add(new AbstractColumn<Account, String>(new Model<String>("Account Id")) {
        private static final long serialVersionUID = 1L;

        @Override
        public void populateItem(Item<ICellPopulator<Account>> item, String componentId,
                IModel<Account> model) {
            Account account = model.getObject();
            Long accountId = account.getId();
            LabelLinkPanel panel = new LabelLinkPanel(componentId, "" + accountId,
                    "details for account id " + accountId, AccountDetails.class,
                    params(AccountDetails.PARAM_ACCOUNT_ID, accountId));
            item.add(panel);
        }

        @Override
        public boolean isSortable() {
            return true;
        }

        @Override
        public String getSortProperty() {
            return AccountsOrder.ID.name();
        }
    });

    columns.add(new AbstractColumn<Account, String>(new Model<String>("User id")) {
        private static final long serialVersionUID = 1L;

        @Override
        public void populateItem(Item<ICellPopulator<Account>> item, String componentId,
                IModel<Account> model) {
            Account account = model.getObject();
            Long userId = account.getUserId();
            Component panel = new LabelLinkPanel(componentId, "" + userId, UserSummary.class,
                    params(UserSummary.PARAM_USER_ID, userId)).setVisible(userId != null);
            item.add(panel);
        }

        @Override
        public boolean isSortable() {
            return true;
        }

        @Override
        public String getSortProperty() {
            return AccountsOrder.USER_ID.name();
        }
    });

    columns.add(new PropertyColumn<Account, String>(new Model<String>("Account name"),
            AccountsOrder.ACCOUNT_NAME.name(), "information.name"));
    columns.add(new PropertyColumn<Account, String>(new Model<String>("Status"), AccountsOrder.STATUS.name(),
            "status"));
    columns.add(
            new PropertyColumn<Account, String>(new Model<String>("Type"), AccountsOrder.TYPE.name(), "type"));
    columns.add(new PropertyColumn<Account, String>(new Model<String>("Currency"), "currencyCode"));
    columns.add(new DatePropertyColumn<Account, String>(new Model<String>("Creation date"),
            AccountsOrder.CREATION_DATE.name(), "created"));
    columns.add(new DatePropertyColumn<Account, String>(new Model<String>("Close date"),
            AccountsOrder.CLOSE_DATE.name(), "closed"));
    columns.add(new AbstractColumn<Account, String>(new Model<String>("Actions")) {
        private static final long serialVersionUID = 1L;

        @Override
        public void populateItem(Item<ICellPopulator<Account>> item, String componentId,
                IModel<Account> model) {
            Account account = model.getObject();
            Long accountId = account.getId();
            LabelLinkPanel panel = new LabelLinkPanel(componentId, "transactions",
                    "transactions involving account id " + accountId, TransactionList.class,
                    params(TransactionList.PARAM_ACCOUNT_ID, accountId));
            item.add(panel);
        }
    });

    AjaxFallbackDefaultDataTable<Account, String> userTable = new AjaxFallbackDefaultDataTable<Account, String>(
            "accountTable", columns, dataProvider, 20);
    add(userTable);
}

From source file:com.doculibre.constellio.wicket.panels.admin.relevance.collection.rules.AddEditBoostRulePanel.java

License:Open Source License

public AddEditBoostRulePanel(String id, BoostRule boostRule, Integer boostRuleListPosition) {
    super(id, true);

    this.boostRuleListPosition = boostRuleListPosition;
    this.boostRuleDTO = new BoostRuleDTO(boostRule);

    Form form = getForm();// w  ww. j a  v  a 2  s .  com
    form.setModel(new CompoundPropertyModel(boostRuleDTO));// pr eviter les repetitions

    TextField regex = new TextField("regex");// grace a setModel plus besoin de : new PropertyModel(this, "regex")
    regex.add(new IValidator() {
        @Override
        public void validate(IValidatable validatable) {
            String regex = (String) validatable.getValue();
            String errorMessage = FormElementValidationService.validateContent(new StringBuilder(regex),
                    FormElementValidationService.ContentType.REGEX, ConstellioSession.get().getLocale());
            if (!errorMessage.isEmpty()) {
                validatable.error(new ValidationError().setMessage(errorMessage));
            }
        }

    });
    form.add(regex);

    TextField boost = new TextField("boost", Double.class);
    boost.setRequired(true);
    form.add(boost);
}

From source file:com.doculibre.constellio.wicket.panels.admin.relevance.indexField.EditIndexFieldRelevancePanel.java

License:Open Source License

public EditIndexFieldRelevancePanel(String id, IModel indexField) {
    super(id, true);

    this.indexField = indexField;
    setName(((IndexField) indexField.getObject()).getName());
    setIndexBoost(((IndexField) indexField.getObject()).getBoost().toString());

    Form form = getForm();/*from  w w w .  ja  va 2s .c  om*/
    form.setModel(new CompoundPropertyModel(this));// a cause de repetitions

    Label name = new Label("name");// grace a setModel plus besoin de : new PropertyModel(this, "regex")
    form.add(name);

    TextField indexBoost = new TextField("boost");
    indexBoost.add(new IValidator() {
        @Override
        public void validate(IValidatable validatable) {
            String indexBoost = (String) validatable.getValue();
            String errorMessage = FormElementValidationService.validateContent(new StringBuilder(indexBoost),
                    FormElementValidationService.ContentType.DOUBLE, ConstellioSession.get().getLocale());
            if (!errorMessage.isEmpty()) {
                validatable.error(new ValidationError().setMessage(errorMessage));
            } else {
                double boostTodouble = Double.parseDouble(indexBoost);
                if (boostTodouble < 0) {
                    validatable.error(new ValidationError().setMessage(indexBoost + " < 0"));
                }
            }
        }
    });
    form.add(indexBoost);
}

From source file:com.doculibre.constellio.wicket.panels.admin.relevance.query.EditQueryRelevancePanel.java

License:Open Source License

public EditQueryRelevancePanel(String id, IModel indexField) {
    super(id, true);

    this.indexField = indexField;
    setName(((IndexField) indexField.getObject()).getName());
    setBoostDismax(((IndexField) indexField.getObject()).getBoostDismax().toString());

    Form form = getForm();/*from   ww  w. j a  va2  s  .  c om*/
    form.setModel(new CompoundPropertyModel(this));// a cause de repetitions

    Label name = new Label("name");// grace a setModel plus besoin de : new PropertyModel(this, "regex")
    form.add(name);

    TextField boost = new TextField("boostDismax");
    boost.add(new IValidator() {
        @Override
        public void validate(IValidatable validatable) {
            String boost = (String) validatable.getValue();
            String errorMessage = FormElementValidationService.validateContent(new StringBuilder(boost),
                    FormElementValidationService.ContentType.DOUBLE, ConstellioSession.get().getLocale());
            if (!errorMessage.isEmpty()) {
                validatable.error(new ValidationError().setMessage(errorMessage));
            } else {
                double boostTodouble = Double.parseDouble(boost);
                if (boostTodouble < 0) {
                    validatable.error(new ValidationError().setMessage(boost + " < 0"));
                }
            }
        }
    });
    form.add(boost);
}

From source file:com.evolveum.midpoint.web.page.admin.roles.component.MultiplicityPolicyDialog.java

License:Apache License

private IValidator<String> prepareMultiplicityValidator() {
    return new IValidator<String>() {

        @Override/* w w  w. j a v a  2s. com*/
        public void validate(IValidatable<String> toValidate) {
            String multiplicity = toValidate.getValue();

            if (!StringUtils.isNumeric(multiplicity) && !multiplicity.equals(MULTIPLICITY_UNBOUNDED)) {
                error(getString("MultiplicityPolicyDialog.message.invalidMultiplicity"));
            }
        }
    };
}

From source file:com.userweave.pages.user.configuration.UserEditProfessionalPanel.java

License:Open Source License

public UserEditProfessionalPanel(String id, UserModel userModel) {
    super(id, userModel);

    add(new ServicePanel("servicePanel", ServicePanelType.OWN_HOSTING));
    add(new ServicePanel("servicePanel2", ServicePanelType.ADVANCE_PRODUCT));

    companyContainer = new WebMarkupContainer("companyContainer");
    getForm().add(companyContainer);//from w  w  w .j a  va2  s  .  c  om
    companyContainer.setOutputMarkupPlaceholderTag(true);

    company = new TextField("company");

    company.add(AjaxBehaviorFactory.getUpdateBehavior("onblur", UserEditProfessionalPanel.this));

    companyContainer.add(company);

    DropDownChoice position = new DropDownChoice("position", Arrays.asList(User.Position.values()),
            new LocalizedPositionChoiceRenderer(this));

    position.add(AjaxBehaviorFactory.getUpdateBehavior("onchange", UserEditProfessionalPanel.this));

    companyContainer.add(position);

    TextField url = new TextField("companyUrl");

    url.add(AjaxBehaviorFactory.getUpdateBehavior("onblur", UserEditProfessionalPanel.this));

    companyContainer.add(url);

    TextField vatin = new TextField("VATIN");

    vatin.add(AjaxBehaviorFactory.getUpdateBehavior("onblur", UserEditProfessionalPanel.this));

    companyContainer.add(vatin);

    TextField employment = new TextField("employment");

    employment.add(AjaxBehaviorFactory.getUpdateBehavior("onblur", UserEditProfessionalPanel.this));

    companyContainer.add(employment);

    // set initial visibility
    companyContainer.setVisible(getUser().getBusinessRole() == BusinessRole.Company);
    company.setRequired(((User) getDefaultModelObject()).getBusinessRole() == BusinessRole.Company);

    RadioChoice businessRole = new RadioChoice("businessRole", Arrays.asList(User.BusinessRole.values()),
            new LocalizedBusinessRoleChoiceRenderer(this)).setSuffix("");
    businessRole.add(new IValidator() {

        @Override
        public void validate(IValidatable validatable) {
            Object o = validatable.getValue();

            User.BusinessRole val = (User.BusinessRole) o;

            if (val == BusinessRole.Company) {
                company.setRequired(true);
            } else {
                company.setRequired(false);
            }
        }
    });

    businessRole.add(new AjaxFormChoiceComponentUpdatingBehavior() {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            boolean actsAsCompany = getUser().getBusinessRole() == BusinessRole.Company;
            companyContainer.setVisible(actsAsCompany);
            company.setRequired(actsAsCompany);
            target.addComponent(companyContainer);
            onSubmit(target);
        }
    });

    getForm().add(businessRole);
}

From source file:com.userweave.pages.user.registration.UserRegistrationForm.java

License:Open Source License

public UserRegistrationForm(String id, IModel userModel, final ModalWindow agbModalWindow) {
    super(id);//from w w  w . j  a  v  a  2s  .  c  om

    setModel(new CompoundPropertyModel(userModel));

    WebMarkupContainer container = new WebMarkupContainer("container");
    add(container);

    companyContainer = new WebMarkupContainer("companyContainer");
    container.add(companyContainer);
    companyContainer.setOutputMarkupPlaceholderTag(true);
    // set initial visibility
    companyContainer.setVisible(getUser().getBusinessRole() == BusinessRole.Company);

    //add(new TextField("email").setRequired(true).setEnabled(getUser().getEmail() == null));

    add(new CheckBox("verified").setEnabled(false));

    //add(new ExternalLink("agb",new Model("http://usability-methods.com/en/termsofuse") , new StringResourceModel("agb", this, null)));

    add(new AjaxLink("agb") {

        @Override
        public void onClick(AjaxRequestTarget target) {
            agbModalWindow.show(target);
        }

    });

    container.add(new TextField("surname").setRequired(true));
    container.add(new TextField("forename").setRequired(true));

    container.add(new DropDownChoice("locale", LocalizationUtils.getSupportedConfigurationFrontendLocales(),
            new LocaleChoiceRenderer(null)));

    container.add(new RadioChoice("gender", Arrays.asList(User.Gender.values()),
            new LocalizedGenderChoiceRenderer(this)).setSuffix(""));

    container.add(new CallnumberPanel("callnumberPanel", new PropertyModel(getModel(), "callnumber")));

    RadioChoice businessRole = new RadioChoice("businessRole", Arrays.asList(User.BusinessRole.values()),
            new LocalizedBusinessRoleChoiceRenderer(this)).setSuffix("");
    businessRole.add(new IValidator() {

        @Override
        public void validate(IValidatable validatable) {
            Object o = validatable.getValue();

            User.BusinessRole val = (User.BusinessRole) o;

            if (val == BusinessRole.Company) {
                company.setRequired(true);
            } else {
                company.setRequired(false);
            }
        }
    });

    businessRole.add(new AjaxFormChoiceComponentUpdatingBehavior() {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            boolean actsAsCompany = getUser().getBusinessRole() == BusinessRole.Company;
            companyContainer.setVisible(actsAsCompany);
            target.addComponent(companyContainer);
        }
    });
    container.add(businessRole);

    companyContainer.add(new DropDownChoice("position", Arrays.asList(User.Position.values()),
            new LocalizedPositionChoiceRenderer(this)));

    companyContainer.add(new TextField("employment"));

    companyContainer.add(company = new TextField("company"));
    //add(new TextField("education"));               
    companyContainer.add(new TextField("companyUrl"));
    companyContainer.add(new TextField("VATIN"));

    container.add(new AddressForRegistrationPanel("addressPanel", new PropertyModel(getModel(), "address")));

    container.add(new CheckBox("receiveNews"));
    //add(new CheckBox("verified").setRequired(true).setEnabled(!getUser().isVerified()));

    container.add(new DefaultButton("saveButton", new StringResourceModel("save", this, null), this) {
        @Override
        protected void onSubmit(AjaxRequestTarget target, Form form) {
            UserRegistrationForm.this.onSave(target);
        }

        @Override
        protected void onError(AjaxRequestTarget target, Form form) {
            target.addComponent(UserRegistrationForm.this.get("feedback"));

        }
    });

    add(new FeedbackPanel("feedback").setOutputMarkupId(true));
}

From source file:de.voolk.marbles.web.pages.content.RenamePage.java

License:Open Source License

@SuppressWarnings("serial")
public RenamePage(PageParameters parameters) {
    super(parameters);
    final TextField<String> pageName = new TextField<String>("pageName",
            new PropertyModel<String>(getMarblesPage(), "name"));
    pageName.add(new IValidator<String>() {
        @Override/*from w ww  .j  a  v  a 2 s .  co m*/
        public void validate(IValidatable<String> validatable) {
            String name = validatable.getValue();
            if (!uniqueInLevel(name)) {
                validatable.error(new IValidationError() {
                    @Override
                    public String getErrorMessage(IErrorMessageSource arg0) {
                        return new StringResourceModel("pagename.not.unique", RenamePage.this,
                                new Model<ValueMap>()).getObject();
                    }
                });
            }
        }

    });
    pageName.setRequired(true);
    pageName.add(StringValidator.minimumLength(1));
    @SuppressWarnings({ "rawtypes" })
    Form form = new Form("renameForm") {
        @Override
        protected void onSubmit() {
            String name = pageName.getModelObject();
            int id = savePageName(name);
            PageParameters parameters = new PageParameters();
            parameters.put("id", id);
            setResponsePage(DisplayPage.class, parameters);
        }
    };
    form.add(pageName);
    form.add(new Button("save", new ResourceModel("save")));
    add(form);
    add(new FeedbackPanel("feedback"));
}