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() {}@Overridepublic 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.

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

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

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

Download JSF Validation Example Project下载JSF验证示例项目

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

jsf表单验证

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

  1. jsf表单验证_JSF:在正确的阶段进行验证(了解生命周期)

    jsf表单验证 嗨,大家好! 尽管标题强调验证一词,但本文实际上是关于JSF生命周期的. 那是因为我相信,真正了解生命周期的最简单方法之一就是通过做出我们一直在做的事情:验证用户输入. 通常,了解所谓 ...

  2. jsf表单验证_动态表单,JSF世界期待已久

    jsf表单验证 新的PrimeFaces扩展版本0.5.0带来了新的DynaForm组件. 通常,如果知道行/列的数量,元素的位置等,则可以通过h:panelGrid或p:panelGrid构建非常简 ...

  3. html表单边框怎么加颜色?html form标签的边框颜色实例

    本篇文章主要的讲述了HTML表单的边框加颜色,可以更改任何你想要的颜色都可以,有实例解析,方便观看,接下来让我们一起来看看这篇关于HTML表单的边框颜色的文章吧 打造全网web前端全栈资料库(总目录) ...

  4. jsf入门实例_JSF selectManyListBox示例教程

    jsf入门实例 JSF allows users to select multiple values for a single field with the help of <h:selectM ...

  5. jsf集成spring_JSF Spring Hibernate集成示例教程

    jsf集成spring Welcome to JSF Spring Hibernate Integration example tutorial. In our last tutorial, we s ...

  6. java 填充pdf_Java如何创建和填充PDF表单域(代码示例)

    本篇文章给大家带来的内容是关于Java如何创建和填充PDF表单域(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助. 表单域,可以按用途分为多种不同的类型,常见的有文本框.多行 ...

  7. HTML与cgi post传递与接收,CGI实例--表单GET与POST示例

    CGI概述 CGI(Common Gateway Interface: 公用网关接口)规定了Web服务器调用其他可执行程序(CGI程 序)的接口协议标准.Web服务器通过调用CGI程序实现和Web浏览 ...

  8. html表单页面css样式代码,前端html表单与css样式(示例代码)

    1,from标签 from标签的功能是向服务器传输数据,实现用户交互的重要标签. from标签的具体使用: input标签使用示例: 姓名: 用户名: 密码: 爱好:骑车游戏电影 男女 第一句:act ...

  9. javascript实现下拉框表单美化的详细实例教程

    html的表单有很强大的功能,在web早期的时候,表单是页面向服务器发起通信的主要渠道.但有些表单元素的样式没办法通过添加css样式来达到满意的效果,而且不同的浏览器之间设置的样式还存在兼容问题,比如 ...

最新文章

  1. LeetCode实战:只出现一次的数字
  2. python好学不-Python爬虫好学吗?
  3. [leetcode]Divide Two Integers
  4. MySQL-常用引擎
  5. 产品要不要做先回答的10个问题
  6. ElasticSearch学习29_基于Elasticsearch实现搜索推荐
  7. 深井软岩巷道群支护技术与应用_深井软岩巷道深浅孔帷幕注浆技术
  8. 如何提取sql语句中绑定变量的值?
  9. 输入三科成绩 C语言,C语言题,对我的程序找错修改。输入10个学生学号,三科成绩,求总成绩和平均分,并按成绩由高到低输出...
  10. 反卷积,上采样,上池化的理解
  11. 学习java 第三天 数据类型以及存储大小取值范围 (one 大白 (●—●))
  12. Pyhton网络爬虫实例_豆瓣电影排行榜_Xpath方法爬取
  13. PreScan快速入门到精通第二讲PreScan功能介绍
  14. 《计算机科学概论(第12版)》—第1章1.3节海量存储器
  15. java 实现橡皮擦_基于canvas剪辑区域功能实现橡皮擦效果
  16. PSD是什么文件格式
  17. 【neusoft】 Linux 的学习与使用
  18. TensorFlow2.0保存模型
  19. 写一个简单的MTK图片管理工具
  20. 自动驾驶Apollo安装步骤

热门文章

  1. ACM PKU 1019 Number Sequence http://acm.pku.edu.cn/JudgeOnline/problem?id=1019
  2. Visual C++中的异常处理浅析[轉]
  3. net use 使用
  4. [转载] pythonjson构建二维数组_python二维键值数组生成转json的例子
  5. [转载] [556]python实现神经网络
  6. phoenix timestamp字段查询
  7. 【Flask】 结合wtforms的文件上传表单
  8. jquery 固定导航
  9. jQuery标题文字淡入淡出显示效果
  10. 使用php://input