我试图创建一个Java Spring表单来检查输入字符串是否包含特殊字符。例如,当用户键入包含特殊字符的字符串时,将弹出一条消息,指出输入的字符串包含特殊字符。
我的问题是如何在验证器中实现java函数以检查输入字符串中的特殊字符?
验证码
package com.mkyong.customer.validator;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.mkyong.customer.model.Customer;
public class CustomerValidator implements Validator{
Pattern pattern = Pattern.compile("[a-zA-Z0-9]*");
String str = "userName";
Matcher matcher = pattern.matcher(str);
@Override
public boolean supports(Class clazz) {
//just validate the Customer instances
return Customer.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userName",
"required.userName", "Keyword is required.");
}
if (!matcher.matches()) {
System.out.println("string '"+str + "' contains special character");
} else {
System.out.println("string '"+str + "' doesn't contains special character");
}
}
答案 0 :(得分:0)
试一下:
String REGEX = "[^&%$#@!~]*";
Pattern pattern = Pattern.compile(REGEX);
它应该可以正常工作。字符类外的^表示行的开头。
String REGEX = "^[&%$##@!~]";
String REGEX = "[^&%$#@!~]*";
字符类[]中的^表示字符类中字符的取反。