我正在对phoneNumber属性进行验证,并尝试强制用户仅键入数字。但由于某些原因,如果我将方法返回类型设置为对象类型它完美地工作,但是当我将其设置为String类型时,我的对象无法验证。控制台没有给出任何消息,并且ajax调用返回完全正常的消息。
观点:
<div id ="EditModal" class="modal fade" role="dialog">
<form class="modal-dialog" th:action="@{/EditPhoneNumber}" th:object="${phoneNumber}" method="POST" id="PhoneEditForm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<input type="text" class="hidden" id="edit-modal-phone-number-id" name="id" value=""/>
<input type="text" placeholder="Number" id="edit-modal-phone-number-number" name="number" value=""/>
<input type="text" class="hidden" id="edit-modal-person-id" name="personID" th:value="${personID}"/>
<p id="EditFormError"></p>
</div>
<div class="modal-footer">
<button type="submit" id="SubmitEdit" class="btn btn-default" >Submit</button>
<button type="button" class = "btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</form>
</div>
控制器:
@RequestMapping(value = "/ValidateEditPhoneNumber",method = RequestMethod.POST)
public @ResponseBody String ValidatePhoneNumber(@Validated @RequestBody PhoneNumberRequest phoneNumber, BindingResult result) {
if(result.hasErrors()) {
return "Something happened";
}
else return "SUCCESS";
}
@RequestMapping(value = "/EditPhoneNumber", method = RequestMethod.POST)
public String editPerson(@ModelAttribute(value="phoneNumber") PhoneNumberRequest phone) {
personService.updatePhoneNumber(phone.getId(), phone.getNumber());
return "redirect:All";
}
ajax功能:
<script>
$(document).ready(function(){
$("#SubmitEdit").click(function(e){
e.preventDefault();
console.log("it ran here");
var inputID = $("#edit-modal-phone-number-id").val();
var inputNumber = $("#edit-modal-phone-number-number").val();
var inputPersonID = $("#edit-modal-person-id").val();
$.ajax({
type: "POST",
url : "/ValidateEditPhoneNumber",
dataType : "text",
data : JSON.stringify({"id" : inputID, "number" : inputNumber, "personID" : inputPersonID}),
contentType: "application/json",
success : function(result){
console.log(result);
$("#PhoneEditForm").submit();
},
error : function(result){
alert("Error "+result.responseText);
console.log(JSON.stringify(result));
}
});
});
});
</script>
我的实体:
@NotNull
private long id;
@NotEmpty
@Pattern(regexp="(^$|[0-9])")
private String number;
@NotNull
private long personID;
//getter,setter