實際上,您可以通過自定義驗證程序來解決此問題,該驗證程序可以獲取另一個字段並相互比較這些值。下面的代碼使用valdr-bean驗證來生成valodation.json。
如果您不想使用它,只需查看JS代碼並手動在您的validation.json中添加驗證器即可。
的Java註釋(該valdr驗證的服務器端的聲明):
package validation;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR,
ElementType.PARAMETER, ElementType.ANNOTATION_TYPE })
public @interface DateFormat {
String message();
Class[] groups() default { };
String beforeFieldName();
}
的Java Bean(註釋的使用,這個類在代validation.json的使用):
package pojo;
import validation.DateFormat;
public class RegistrationPojo implements BasePojo {
@NotNull(message = "message.date1.required")
private Date date1;
@NotNull(message = "message.date2.required")
@DateFormat(message = "message.date2.date", beforeFieldName = "date1")
private Date date2;
}
JS(實施自定義驗證的和在valdr對其進行註冊):
module.factory('validation.DateFormat', [
function() {
return {
name: 'validation.DateFormat',
validate: function (value, constraint) {
var minOk = true;
var maxOk = true;
var format = false; // constraint.pattern is mandatory
//do not validate for required here, if date is null, date will return true (valid)
console.log("my date validator called");
console.log(" beforeFieldName: " + constraint.beforeFieldName);
var field = document.querySelector('[name="' + constraint.beforeFieldName + '"]');
console.log("field value: " + (field ? field.value : "null"));
return (!field || value > field.value);
}
};
}]);
module.config([
"valdrProvider",
function(valdrProvider) {
valdrProvider.addValidator('validation.DateFormat');
}]);