Sunday, 10 June 2012

MVVM Example for Form Validation

In this post, we will see how we can validate the form inputs on click of submit button and show all the errors in one window.


ZK Version : ZK 6
Project Name : MVVMFormValidation
Project Structure :



Demo.zul

<?page title="new page title" contentType="text/html;charset=UTF-8"?>
<zk>
    <window id="win" title="Person" width="420px" height="150px"
        border="normal" minimizable="false" mode="modal" maximizable="false"
        closable="true" apply="org.zkoss.bind.BindComposer"
        viewModel="@id('vm') @init('ViewModels.DemoVM')"
        action="show: slideDown;hide: slideUp">

        <grid width="400px">
            <rows>
                <row>
                    First Name:
                    <textbox id="fname" value="@bind(vm.firstName)" />
                </row>
                <row>
                    Last Name:
                    <textbox id="lname" value="@bind(vm.lastName)" />
                </row>
            </rows>
        </grid>
        <separator />
        <div align="center">
            <button id="Submit" label="Submit"  onClick="@command('save')" mold="trendy" />
        </div>
    </window>
</zk>

ValidateWindow.zul

<?xml version="1.0" encoding="UTF-8"?>
<zk>
    <window id="modalDialog" title=" " width="420px" height="auto"
        border="normal" minimizable="false" mode="modal" maximizable="false"
        closable="true" action="hide: slideUp"
        apply="org.zkoss.bind.BindComposer"
        viewModel="@id('vm') @init('ViewModels.formValidationVM')">

        <listbox vflex="1" id="test" model="@load(vm.allMessages)">
            <listhead sizable="true">
                <listheader label="Messages" width="300px" />
            </listhead>
            <template name="model" var="p1">
                <listitem>
                    <listcell label="@load(p1.message)" />
                </listitem>
            </template>
        </listbox>
        <separator />
        <div align="center">
            <button label="Ok" onCreate="self.setFocus(true)"
                onClick="modalDialog.detach()" />
        </div>
    </window>
</zk>


showWindow.java

package DomainUtil;

import java.util.HashMap;
import java.util.List;
import org.zkoss.zk.ui.Executions;

import MyDomain.ValidationMessage;

public class showWindow {
    public static void ShowValidation( List<ValidationMessage> vList) {
        final HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("vList", vList);
        Executions.createComponents("ValidateWindow.zul", null, map);
    }
}


ValidationMessage.java

package MyDomain;

public class ValidationMessage {
    private String message;

    public ValidationMessage(String message)
    {
        this.message= message;
    }

    public ValidationMessage()
    {
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

}


DemoVM.java

package ViewModels;

import java.util.ArrayList;
import java.util.List;
import org.zkoss.bind.annotation.Command;
import org.zkoss.zul.Messagebox;
import DomainUtil.showWindow;
import MyDomain.ValidationMessage;

public class DemoVM {

    private String firstName;
    private String lastName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Command
    public void save() throws Exception {
        if (IsValidInput())
            Messagebox.show("All are valid. Now you can Save into DB");        
    }

    public boolean IsValidInput() {

        List<ValidationMessage> vList = new ArrayList<ValidationMessage>();

        if ((firstName == null || "".equals(firstName))) {
            vList.add(new ValidationMessage("First Name Cannot be Empty"));
        }

        if ((lastName == null || "".equals(lastName))) {
            vList.add(new ValidationMessage("Last Name Cannot be Empty"));
        }

        if (vList.size() > 0) {
            showWindow.ShowValidation(vList);
            return false;
        } else
            return true;
    }
}


formValidationVM.java

package ViewModels;
import MyDomain.ValidationMessage;

import org.zkoss.bind.annotation.ExecutionArgParam;
import org.zkoss.bind.annotation.Init;

import java.util.List;

public class formValidationVM {

    private List<ValidationMessage> allMessages = null;

    
    public List<ValidationMessage> getAllMessages() {
        return allMessages;
    }

    public void setAllMessages(List<ValidationMessage> allMessages) {
        this.allMessages = allMessages;
    }
    
    @Init
    public void init(@ExecutionArgParam("vList") List<ValidationMessage> vList) {
        setAllMessages(vList);
    }

}


Now run the demo.zul file and do not give any value, you can see the following output

image

Download the source as war file

1 comment:

  1. We are a third party technical support service. Avast Customer Support is here to help you out with the whole procedure to Download Avast Antivirus online, We not only fix your Avast Support related issues but will guide with how to get started with your new Avast product once it gets installed successfully. Call on our Toll Free no. 1 855 966 3855
    Gmail Customer service is a third party technical support service for Gmail users when they face any technical issue or error in their Gmail account. Our Gmail Customer Support team solves issues like forgot Gmail account password, Gmail configuration or Sync issues, recover deleted emails and many more. Toll Free number (800) 986-9271
    How you install or reinstall Office 365 or Office 2016 depends on whether your Office product is part of an Office for home or Office for business plan. If you're not sure what you have, see what office com setup products are included in each plan and then follow the steps for your product. The steps below also apply if you're installing a single, stand-alone Office application such as Access 2016 or Visio 2016. Need Help with office setup Enter Product Key? Call 1-800-000-0000 Toll Free
    Norton Tech Support is a third party service provider and not in any way associated with Norton or any of its partner companies. We offer support for Norton products and sell subscription based additional warranty on computer and other peripheral devices. Call our Toll Free number 1 855 966 3855
    Other Services
    Norton Toll Free , Office-Setup , office.com/setup.

    ReplyDelete