在我的应用程序中,我有很多字段,用户可以在其中插入数值。要求是提交后必须删除任何前导,前导或内联空格。我总共有大约10个领域需要这种形式。
编辑:它的Spring MVC应用程序。数据通过网络插入。数字(电话)字段是字符串类型,如果插入则跟随有效,但在进入转换器和其他验证器之前应该被剥离:" +44 123456 55"," +4 4 1 2 3 4"或任何包含空格的东西。
我已经调查了各方面,但没有通过反思改变价值观的运气。
到目前为止,我已经提出了自定义注释@NumericValue
,并将其放在需要格式化的所有字段上。我目前的解决方案是传入一个包含这些字段的对象,并通过使用以下方法循环删除它们:
public static void formatNumericFields(Object object) {
for (Field field : object.getClass().getDeclaredFields())
for (Annotation annotation : field.getDeclaredAnnotations())
if (annotation.annotationType().equals(NumericValue.class)) {
field.setAccessible(true);
if (getField(field, object) != null)
setField(field, object, getField(field, object).toString().replace(" ", ""));
}
}
我会问是否有更实际的方法来做我想要实现的目标。我不想分别在所有字段上执行.replace("","")。现在我将在3个不同的控制器中调用该方法,传递需要格式化的表单数据。感谢。
答案 0 :(得分:0)
用户输入后,您是否只能忘记空格?您可以使用PlainDocument-Filter
的{{1}}来执行此操作:
JTextFields
正如我对您的问题的评论中提到的,我还使用了PlainDocument doc = new PlainDocument();
doc.setDocumentFilter(new DocumentFilter() {
@Override
public void insertString(FilterBypass fb, int off, String str, AttributeSet attr) throws BadLocationException {
// Remove all whitespaces:
fb.insertString(off, str.replaceAll("\\s", ""), attr);
// This below could be used instead to remove all non-digits (whitespaces, letters, etc.)
//fb.insertString(off, str.replaceAll("\\D++", ""), attr);
}
@Override
public void replace(FilterBypass fb, int off, int len, String str, AttributeSet attr) throws BadLocationException {
// Remove all whitespaces:
fb.insertString(off, str.replaceAll("\\s", ""), attr);
// This below could be used instead to remove all non-digits (whitespaces, letters, etc.)
//fb.insertString(off, str.replaceAll("\\D++", ""), attr);
}
});
JTextField textfield = new JTextField();
textfield.setDocument(doc);
而不是.replaceAll("\\s", "");
,因此它不仅会删除空格,还会删除标签,输入等等。