Validating form values

Thursday, February 25, 2010 Posted by Jagadeesh Manne
in this post we will create methods for validate form values and set errors to bean if those values are invalid.
now create methods.

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package validation;
import model.UserBean;
/**
*
* @author Jagadeesh
*/
public class ValidateForm {


UserBean validBean = new UserBean();
public UserBean validateData(UserBean ubean)
{

//if given username value is not valid then seterror
// message and set empty value to input field
if(ubean.getUserName().length()==0)
{
validBean.setUserNameError("please enter valid name");
validBean.setIsValid(false);
validBean.setUserName("");
}
else
if(!ubean.getUserName().matches("[a-zA-Z]*"))
{
validBean.setUserNameError("please enter valid name");
validBean.setIsValid(false);
validBean.setUserName("");

}
//if given username value is valid then seterror message to
// empty and set value to bean
else
{
validBean.setUserNameError("");
validBean.setIsValid(true);
validBean.setUserName(ubean.getUserName());
}


//if given username value is not valid then seterror message
// and set empty value to input field
if(!ubean.getDateOfBirth().matches("\\d{1,2}-\\d{1,2}-\\d{4}"))
{
validBean.setDateOfBirthError("please enter valid date");
validBean.setIsValid(false);
validBean.setDateOfBirth("");

}
//if given username value is valid then seterror message
// to empty and set value to bean
else
{
validBean.setDateOfBirthError("");
validBean.setIsValid(true);
validBean.setDateOfBirth(ubean.getDateOfBirth());
}


//if given username value is not valid then seterror message 
//and set empty value to input field

if(!ubean.getEmail().matches("^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$"))
{
validBean.setEmailError("please enter valid email");
validBean.setIsValid(false);
validBean.setEmail("");
}
//if given username value is valid then seterror message
//to empty and set value to bean
else
{
validBean.setEmailError("");
validBean.setIsValid(true);
validBean.setEmail(ubean.getEmail());
}

//if given username value is not valid then seterror message
// and set empty value to input field
if(!ubean.getPhoneNo().matches("\\d{10}"))
{
validBean.setPhoneNoError("please enter valid phoneno");
validBean.setIsValid(false);
validBean.setPhoneNo("");
}
//if given username value is valid then seterror message to 
// empty and set value to bean
else
{
validBean.setPhoneNoError("");
validBean.setIsValid(true);
validBean.setPhoneNo(ubean.getPhoneNo());
}
return validBean;
}
}

Labels:

Post a Comment