I have a simple 'user registration' page with a 'username' field along with other fields. My requirement is 'username' should not be duplicate, for this I have written a ajax function which checks if username is duplicate and if it is duplicate it prints an error message below the 'username' field, this flow is working fine, problem occurs when I click on submit button, even with the 'username not unique' message i am able to save the page [although i can catch exception and handle it accordingly]. I know this is happening because i am just displaying the error message and not binding error to 'username' field. How can I bind error message to username field(in case of username duplicate error) so that page is not submitted until this error is removed?
Code is below
1.JQuery
function check_username(){
$("#usernamentavlberror").empty();
var developerData = {};
developerData["userName"] = $("#username").val();
$.ajax({
type: 'POST',
contentType : "application/json",
url: '/checkForDuplicateUsername',
data : JSON.stringify(developerData),
dataType : 'json',
success: function(data){
if(data == "userNameExists"){
alert("inside user")
$("#usernamentavlberror").html("UserName Not Available");
}
else {
//do perform other actions like displaying error messages etc.,
}
},
error : function(data) {
alert("error---"+data);
}
});
}
- Thymeleaf page
<form action="#" th:action="@{/signup}" th:object="${user}" method=post>
<div class="form-group input-group">
<div class="input-group-prepend">
<span class="input-group-text"> <i class="fa fa-user"></i>
</span>
</div>
<input name="username" th:field="*{username}" class="form-control" placeholder="User Name" type="text" id="username">
</div>
<div class="form-group input-group" th:if="${#fields.hasErrors('username')}" th:errors="*{username}"></div>
<div class="form-group input-group" id="usernamentavlberror"></div>
.
.
</form>```