NumberValidator 用于测试某个值是否符合一组验证约束。您可以将 JavaScript 数字传递给此验证器,也可以将已使用所提供的 NumberConverter 转换为数字的字符串传递给此验证器,如果转换失败,则值无效。
可以在构造验证器时提供验证约束,也可以使用 GetAttribute/SetAttribute 调用来添加/除去验证约束。可以提供任意数目的约束。不提供约束是没有意义的。
如果提供了 required 约束并设置为 true,则验证器将要求值不为空(如果提供了数字)或者值不是空字符串(如果提供了字符串)。如果未设置 required,则会将空值/空字符串视为有效值,而不考虑任何其他约束。即,如果未设置 required,则空值始终是有效值。
如果指定了 minimum-bound 作为约束,则值(如果不为空)必须大于或等于所指定的界限。如果指定了 maximum-bound 作为约束,则值必须小于或等于最大值界限。
如果指定了模数,则进行模数测试时将使用该数字的各个位,而不考虑分组/小数点字符。最后一位是校验数位,模数算法将对其他各个位进行处理以测试它们的“和”是否等于该校验数位。此约束可用于验证 16 位的数字是否是有效的信用卡号以及验证诸如帐号之类的数字。
可以使用 JavaScript EL 表达式来测试某个值是否在集合内以及测试某个值是否在不连续的范围内,等等。目前,不能使用此表达式将一个值与页面上的另一个值进行比较。
hX_5.addValidator("id", new hX_5.NumberValidator(attributes)); 其中
id |
组件所连接至的 HTML 标记的 ID。 |
属性名称 |
描述 |
---|---|
required |
如果是必需的,则该值可能不能为 NULL 或空字符串。如果不是必需的,则该值可以为 NULL 或空字符串,并跳过其他验证约束。 |
minimum-bound |
允许的最小值。范围应格式化为 yyyyMMddHHmmssSSS,其中结尾组件可能会被忽略。 |
maximum-bound |
允许的最大值。范围应格式化为 yyyyMMddHHmmssSSS,其中结尾组件可能会被忽略。 |
modulus |
值必须通过 IBM® 模数 10 公式(值为 10)或 IBM 模数 11 公式(值为 11)自检算法。请参阅 http://publib.boulder.ibm.com/iseries/v5r2/ic2924/index.htm?info/rzakc/rzakcmstdfcheck.htm(搜索“M10/M10F”)。 |
constraint-expression |
必须满足的 JavaScript EL 表达式。JavaScript EL 表达式与 JSF EL 表达式相同,但以下各方面除外:
|
API 调用 |
描述 |
---|---|
boolean = validate(value, converter) |
验证值(字符串或日期对象)。需要转换器对象或转换器的 ID。如果值通过验证,则返回 true。如果值失败,则返回 false,并设置 lastError。 |
string = lastError() |
如果转换失败,则将失败原因作为本地化字符串返回。 |
object = setAttribute(attribute) |
设置属性,或如果以前已设置属性,则更改其值。 |
string = getAttribute(attribute-name) |
检索属性的当前值。 |
验证一对输入字段的值。
// Construct a converter with a pattern of $ ###,##0.00;($ ###,##0.00) hX.addConverter("AZ", new hX.NumberConverter("pattern:$ ###,##0.00;($ ###,##0.00)", "strict:2", "locale:,.%‰-$")); // Construct a converter with a pattern of 0000,0000,0000,0000 hX.addConverter("BZ", new hX.NumberConverter("pattern:0000,0000,0000,0000", "strict:2", "locale:--XXXX")); // Construct a validator that checks that a field is present and between -100,000 and 100,000 but not zero hX.addValidator("1Z", new hX.NumberValidator("required:true", "constraint-expression:(@testValue >= -100000 && @testValue <= 100000 && @testvalue != 0)")); // Construct a validator that checks that a field is present and a valid credit card number hX.addValidator("2Z", new hX.NumberValidator("required:true", "modulus:10")); // Validate a pair of values var x = document.getElementById("form1:textA"); var v = hX.getValidatorById("1Z"); if (!v.validate(x.value, "AZ")) alert ("ERROR: " + v.lastError()); x = document.getElementById("form1:textB"); v = hX.getValidatorById("2Z"); if (!v.validate(x.value, "BZ")) alert ("ERROR: " + v.lastError());