Search code examples
javavalidationmvvmserver-sidezk

Form validations (Server Side) examples in ZK MVVM


Can you please explain how to do form validations on the server side using the MVVM approach. I tried it but could not do it effectively. I have done small validations on the client side using intbox etc. But I want to do validations like:

  1. The value of an attribute should not exceed say 100.
  2. If value of attribute A is filled by the user then attribute B becomes mandatory and like that.
  3. If value of attribute A is 100 and B is 50 then value of attribute C becomes mandatory and cannot exceed 150

I am not able to figure out a way of doing it in MVVM. I am using ZK CE 6.0.0 version.

I tried the code mentioned below:

Validation.zul

<zk>
    <window title="Validation" border="normal"
        apply="org.zkoss.bind.BindComposer" id="validtionWin"
        viewModel="@id('vm') @init('com.nagarro.validator.CustomValidator')">
        <intbox
            value="@save(vm.quantity) @validator(vm.rangeValidator)" />

        <button label="Submit"></button>
    </window>
</zk>

ViewModel CustomValidator.java

import org.zkoss.bind.ValidationContext;
import org.zkoss.bind.Validator;
import org.zkoss.bind.validator.AbstractValidator;


public class CustomValidator implements Validator{

    private Validator rangeValidator;

    private String quantity;

    /**
     * @return the quantity
     */
    public String getQuantity() {
        return quantity;
    }

    /**
     * @param quantity
     *            the quantity to set
     */
    public void setQuantity(String quantity) {
        this.quantity = quantity;
    }
    @Override
    public void validate(ValidationContext ctx) {


    }

    /**
     * @return the rangeValidator
     */
    public Validator getRangeValidator() {
        return new AbstractValidator() {
            public void validate(ValidationContext ctx) {
                Integer val = (Integer)ctx.getProperty().getValue();
                if(val<10 || val>100){
                    addInvalidMessage(ctx, "value must not < 10 or > 100, but is "+val);
                }
            }
        };
    }

    /**
     * @param rangeValidator the rangeValidator to set
     */
    public void setRangeValidator(Validator rangeValidator) {
        this.rangeValidator = rangeValidator;
    }

}

Please figure out the mistake in the above code. :)

I get the following WARNING when I run the above code.

Jan 16, 2013 4:58:07 PM org.zkoss.bind.validator.AbstractValidator
addInvalidMessages:84 WARNING: ValidationMessages not found on binder
org.zkoss.bind.AnnotateBinder@cf7fda, please init it

How should I set the validation Message Please Help. :)


Solution

  • Check out this or use constraints for InputElements.
    If you need more details or have problems, please provide some code.

    Edit

    You are missing

    validationMessages="@id('vmsgs')
    

    at your Window.
    Please read this to understand.