struts系列:校验(二)自定义校验器

一、自定义校验类

public class PasswordValidator extends FieldValidatorSupport {

    @Override
    public void validate(Object object) throws ValidationException {
        String fieldName = getFieldName();
        Object fieldValue = getFieldValue(fieldName, object);
        if (fieldValue == null)
            addFieldError(fieldName, "the password can not be null, please input");
        if (!fieldValue.equals("1234576")) {
            addFieldError(fieldName, object);
        }
    }

}

二、注册到校验器中

1. 新建一个validators.xml,内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
        "-//Apache Struts//XWork Validator Definition 1.0//EN"
        "http://struts.apache.org/dtds/xwork-validator-definition-1.0.dtd">

<validators>
    <validator name="pwdcheck" class="com.sanro.strutsDemo.action.service.PasswordValidator"/>
</validators>    

2. 将这个文件放置在struts.xml相同路径下。

三、在校验XML中引用

    <field name="password">
        <field-validator type="pwdcheck">
            <message>密码 is not right!</message>
        </field-validator>
    </field>

 

posted @ 2018-07-17 22:51  一沙世界  阅读(151)  评论(0编辑  收藏  举报