// 验证 名称是否重复
function saveFun() {
var flag = true;
var contentTypeId = $("#contentTypeId").val();
var nameObj = $('#nameAttribute');
if (nameObj.length > 0) {
//验证名称的唯一性
var name = nameObj.val();
var nameTrim = $.trim(name);
if(nameTrim == ''){
flag = false;
alert("名称不能为空");
}else if(checkLeftIsNull(name)){
flag = false;
alert("请去掉名称左侧空格");
}else if(checkRightIsNull(name)){
flag = false;
alert("请去掉名称右侧空格");
}else{
// 验证是否左侧有空格 如果是的话 则让去掉左侧空格 左侧空格 右侧空格
flag = checkNameIsChongFu(nameTrim,contentTypeId);
if(!flag){
alert("名称重复,请修改");
}
}
}
if(flag){
var msgs = $('span[name=validateMsg]:visible');
if (msgs.length > 0) {
alert('您有填写内容的格式不正确的信息!');
}
flag = (msgs.length == 0);
}
if(flag){
$('#formID').submit();
}
}
function checkLeftIsNull(data){
var regexEmail = /^\s+/;
if (data.match(regexEmail) == null) {
return false;
}
return true;
}
function checkRightIsNull(data){
var regexEmail = /\s+$/;
if (data.match(regexEmail) == null) {
return false;
}
return true;
}
// 验证 知识的名称是否重复
function checkNameIsChongFu(name,contentTypeId){
var flag;
$.ajax({
url : '<c:url value="/contentmanage!checkName"/>',
type : 'post',
async: false,//使用同步的方式,true为异步方式
data : {name:name,hidContentTypeId:contentTypeId},//这里使用json对象
dataType : 'json',
success : function(data){
//code here...
var obj = eval(data);
if(obj.status == "1"){
flag = true;
}else{
flag = false;
}
}
});
return flag;
}
后台:
public String checkName(){
Map map = new HashMap();
KnowledgeClient knowledgeClient = new KnowledgeClient();
KnowledgeSelector selector = new KnowledgeSelector();
selector.setType(Constants.ASSIST_QUERY_EXSIT);
selector.setCatalogId(hidContentTypeId);
selector.setAssistParam(new AssistParam(name));
KnowledgeResponse response =knowledgeClient.getAssistInfo(selector);
int status = response.getStatus();
System.out.println(response.getStatus());
if (status == Constants.SUCCESS){
logger.info("知识名称name为: " + name + "不重复,可以使用");
map.put("status", "1");
}else if(status == Constants.NAME_IDENTIFY_EXSIT){
logger.info("知识名称name为: " + name + "重复");
map.put("status", "2");
}else{
logger.info("验证名称name为: "+ name + "是否重复失败,失败原因为:" + response.getDesc());
map.put("status", "3");
}
JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(map);
return ajaxJson(jsonObject.toString());
}
// 根据字符串输出JSON,返回null
public String ajaxJson(String jsonString) {
return ajax(jsonString, "text/html");
}
// AJAX输出,返回null
public String ajax(String content, String type) {
try {
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType(type + ";charset=UTF-8");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.getWriter().write(content);
response.getWriter().flush();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
使用的包 : json-lib-2.1-jdk15.jar
jquery1.5