jsf表单验证_JSF验证示例教程–验证器标签,定制验证器

jsf表单验证

JSF validation model defines a set of standard classes for validating the UI components. The JSF library defines a group of core tags that corresponds to javax.faces.validator.Validator implementations. Apart from the standard error messages validation model allows us to define the custom validations. Validations in JSF can be categorized into Imperative and Declarative.

JSF验证模型定义了一组用于验证UI组件的标准类。 JSF库定义了一组与javax.faces.validator.Validator实现相对应的核心标记。 除了标准的错误消息验证模型,我们还可以定义自定义验证。 JSF中的验证可以分为命令式和声明式。

JSF验证–声明式验证器 (JSF Validation – Declarative Validator)

The validations that are fired using JSF standard validators or Bean validators fall under declarative type.

使用JSF标准验证器或Bean验证器触发的验证属于声明性类型。

Examples for JSF standard validators are Length validator, Required validator etc..

JSF标准验证器的示例包括长度验证器,必需验证器等。

Consider an example for standard validator. Create mobile.xhtml as

考虑标准验证器的示例。 创建mobile.xhtml为

mobile.xhtml

mobile.xhtml

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:h="https://java.sun.com/jsf/html">
<h:head>
</h:head>
<h:body>
	<h3>Add Mobile Details</h3>
	<h:form>
		<h:panelGrid columns="3">
			<h:outputLabel for="mname">Mobile Name:</h:outputLabel>
			<h:inputText id="mname" required="true"
				requiredMessage="Mobile Name is mandatory"></h:inputText>
			<br>
			<br>

			<h:outputLabel for="color">Color:</h:outputLabel>
			<h:inputText id="color" required="true"></h:inputText>
			<br>
			<br>

			<h:outputLabel for="model">Model Number:</h:outputLabel>
			<h:inputText id="model"></h:inputText>
			<br>
			<br>

			<h:commandButton value="Submit"></h:commandButton>
		</h:panelGrid>
	</h:form>
</h:body>
</html>

Here we are setting the required attribute to true which makes the field mandatory and fires the custom message “value is required” for color field and user defined message for mobile name field as the message is specified in the requiredmessage attribute.

在这里,我们将required属性设置为true,这使该字段成为必填字段,并在colors字段和移动名称字段的用户定义消息中触发自定义消息“ value is required”,因为该消息是在requiredmessage属性中指定的。

Run the application and you will see the below output on pressing submit button.

运行该应用程序,然后按提交按钮,您将看到以下输出。

JSF命令式验证 (JSF Imperative validation)

The standard validation messages would not be sufficient in all the cases and sometimes may require complex validations.Imperative validation allows users to do this by

标准验证消息并非在所有情况下都足够,有时可能需要复杂的验证。即时验证允许用户通过以下方式进行验证:

  1. Firing the validation from the Bean method

    从Bean方法触发验证
  2. Use annotation @FacesValidator in the class during runtime

    在运行时在类中使用注释@FacesValidator

Firing the validation from the Bean method
In this type of validation we write a method in the bean to validate the UIComponents and invoke this method from the jsf page through a validator attribute in the inputText tag.

从Bean方法触发验证
在这种类型的验证中,我们在Bean中编写了一个方法来验证UIComponent,并通过inputText标记中的validator属性从jsf页面调用此方法。

Now lets see consider an example of firing a validation from the Bean.

现在,让我们来看一个从Bean触发验证的示例。

mob.xhtml

mob.xhtml

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:h="https://java.sun.com/jsf/html">
<h:head>
</h:head>
<h:body>
	<h3>Add Mobile Details</h3>
	<h:form>
		<h:outputLabel for="mno">Model Number:</h:outputLabel>
		<h:inputText id="mno" value="#{mobile.mno}" required="true" size="4"
			disabled="#{mobile.mno}" validator="#{mobile.validateModelNo}">
		</h:inputText>
		<h:commandButton value="Submit"></h:commandButton>
	</h:form>
</h:body>
</html>

In this page we are invoking the validateModelno method of the java bean in the validator tag attribute.

在此页面中,我们将在Validator标签属性中调用java bean的validateModelno方法。

Create Mobile.java as

创建Mobile.java

package com.journaldev.jsf.bean;

import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;

@ManagedBean
@SessionScoped
public class Mobile implements Serializable {

	private static final long serialVersionUID = -7250065889869767422L;

	// @NotNull(message="Please enter the model number")
	private String mno;

	public String getMno() {
		return mno;
	}

	public void setMno(String mno) {
		this.mno = mno;
	}

	public void validateModelNo(FacesContext context, UIComponent comp,
			Object value) {

		System.out.println("inside validate method");

		String mno = (String) value;

		if (mno.length() < 4) {
			((UIInput) comp).setValid(false);

			FacesMessage message = new FacesMessage(
					"Minimum length of model number is 4");
			context.addMessage(comp.getClientId(context), message);

		}

	}

}

Here we are checking for the length of the model no and if the length is less than 4 we are specifying the message as “Minimum length of model number is 4”.

在这里,我们正在检查型号no的长度,如果长度小于4,则将消息指定为“型号最小长度为4”。

Now Run the application which produces the following output.

现在,运行产生以下输出的应用程序。

在Bean中使用@FacesValidator –自定义JSF验证程序 (Using @FacesValidator in the Bean – Custom JSF Validator)

In this method we use @FacesValidator annotation, specify the name for the validator and implement the Validator by overriding the validate method.

在此方法中,我们使用@FacesValidator批注,指定验证器的名称并通过覆盖validate方法来实现Validator。

mobvalidator.xhtml

mobvalidator.xhtml

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:h="https://xmlns.jcp.org/jsf/html"
	xmlns:f="https://java.sun.com/jsf/core">
<h:head>
</h:head>
<h:body>
	<h:form>
		<h3>Validation using Faces validator</h3>
		<h:outputLabel for="mno" value="Model Number: " />
		<h:inputText id="mno" value="#{mobileValidator.mno}">
		<f:validator validatorId="mobileValidator" />
		</h:inputText>
		<h:message for="mno" style="color:blue" />
		<p></p>
		<h:commandButton value="Submit"></h:commandButton>
	</h:form>
</h:body>
</html>

In this we are calling the custom validator named “mobileValidator” in the validatorId attribute of the <f:validator> tag.

在此,我们在<f:validator>标记的validateatorId属性中调用名为“ mobileValidator”的自定义验证器。

Create MobileValidator.java as

创建MobileValidator.java

package com.journaldev.jsf.bean;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

@ManagedBean
@SessionScoped
@FacesValidator("mobileValidator")
public class MobileValidator implements Validator {

	private String mno;

	public String getMno() {
		return mno;
	}

	public void setMno(String mno) {
		this.mno = mno;
	}

	int maximumlength = 6;

	public MobileValidator() {
	}

	@Override
	public void validate(FacesContext fc, UIComponent uic, Object obj)
			throws ValidatorException {

		String model = (String) obj;

		if (model.length() > 6) {
			FacesMessage msg = new FacesMessage(
					" Maximum Length of 6 is exceeded.Please enter values within range");
			msg.setSeverity(FacesMessage.SEVERITY_ERROR);

			throw new ValidatorException(msg);
		}

	}

}

Here we override the standard validate method and implement our own logic for validating the input fields.

在这里,我们重写了标准的validate方法,并实现了自己的逻辑来验证输入字段。

Run the application and see the output as shown below.

运行该应用程序,然后查看输出,如下所示。

Finally below image shows the project structure.

JSF Form Validation, Custom Validator

最后,下图显示了项目结构。

You can download the project from below link and play around with it to learn more.

您可以从下面的链接下载该项目并进行试用以了解更多信息。

翻译自: https://www.journaldev.com/7035/jsf-validation-example-tutorial-validator-tag-custom-validator

jsf表单验证

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值