我有一个网络应用程序。在客户表单中,我进行了空验证,但现在我必须测试该值是否有特殊字符,例如:ÁÉëÍÏ......
这是 .java 空验证:
private void testFields(String name) {
if (applicationField == null) {
LOG.error("The request is invalid");
}
try {
Field f = applicationField.class.getDeclaredField(name);
f.setAccessible(true);
Object value = f.get(applicationField);
boolean emp = false;
if (value instanceof String) {
String strVal = (String) value;
if (StringUtils.isEmpty(strVal)) {
emp = true;
}
} else if (value == null) {
emp = true;
}
if (emp) {
addMissingField(name);
}
} catch (Exception e) {
LOG.error("Failed to validate the field: " + name, e);
}
}
private void addMissingField(String name){
if (StringUtils.isEmpty(missingFields)) {
missingFields = name;
} else {
missingFields += " " + name;
}
}
在 .jsp 中,我在提交按钮中进行了此操作:
$("#submit")
.button()
.click(function(event) {
event.preventDefault();
var submitButton = $(this);
submitButton.button("disable");
$("input:text").each(function(idx,elem){
$(elem).val($(elem).val().toUpperCase());
});
var form = $("#customerForm");
var action = form.attr('action');
var queryString = form.serialize();
console.log(notifier);
var taskId = notifier.start("Processing Request");
$.ajax({
method: "post",
url: action,
data: queryString,
statusCode: {
201: function() {
window.location.replace(".........");
}
}
}).always(function(data){
notifier.done(taskId);
submitButton.button("enable");
}).done(function(data){
if(data.missingFields){
messageDialog("Sorry, Missing required fields to register the application", true);
markMissingFields(data.missingFields);
console.log("This is the missing Fields: " + data.missingFields);
}
}).fail(function(data){
messageDialog("There was an error processing the request", true);
});
});
所以,空验证工作得很好。但有时用户插入的数据如:MÖDRIC、JHÖN 或 CÁRLOS,会在数据库的差异过程中产生问题。
我想知道如果值为空或同时具有特殊字符,我该如何包含特殊字符验证测试。
所以我需要一个好方法来在 .java 或 .jsp 中实现这一点。
最佳答案
在 javascript 中你可以使用正则表达式:
var str = "ábcde";
var str2 = "abcd";
var patt = new RegExp("[^a-zA-Z0-9\-\\/(),_\s]+")
var res = patt.test(str);
patt.test(str); //true
patt.test(str2); //false
关于java - 如何使用java和javascript进行特殊字符验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28459642/