I am using ASP.NET MVC4
and jQuery Validate
and jQuery Validate unobtrusive
.
I have various elements on my form, but I only need to have one element validated. The other elements DO NOT need to be validated. Basically what happens is I have a textbox that accepts a number, and a button (NOT to submit the form) that takes the number in this texbox and does a remote call to check if the number exists, if not then it must display an error message.
My view's code:
<td class="edit-label">Change Control ID/Incident Number: <span class="required">**</span></td>
<td>
@Html.TextBoxFor(x => x.ChangeIncidentNumber)
<button id="verifyButton" type="button">Verify</button>
@Html.ValidationMessageFor(x => x.ChangeIncidentNumber)
</td>
My view model:
public class SearchServerViewModel
{
// Partial view model
public string ChangeIncidentNumber { get; set; }
}
My HTML output for the textbox:
<td class="edit-label">Change Control ID/Incident Number: <span class="required">**</span></td>
<td>
<input data-val="true" data-val-required="Required" id="ChangeIncidentNumber" name="ChangeIncidentNumber" type="text" value="792952" />
<button id="verifyButton" type="button">Verify</button>
<span class="field-validation-valid" data-valmsg-for="ChangeIncidentNumber" data-valmsg-replace="true"></span>
</td>
My jQuery code:
<script src="/Assets/JavaScripts/jquery-validate/jquery.validate.min.js"></script>
<script src="/Assets/JavaScripts/jquery-validate/jquery.validate.unobtrusive.min.js"></script>
<script>
$(document).ready(function () {
$("#ChangeIncidentNumber").validate({
rules: {
ChangeIncidentNumber: {
required: true,
remote: '/Server/ValidateChangeIncidentNumber'
}
},
messages: {
ChangeIncidentNumber: {
required: "Required",
remote: "custom message:"
}
}
});
$('#verifyButton').click(function () {
var isValid = $('#ChangeIncidentNumber').valid();
});
});
</script>
My action method:
public ActionResult ValidateChangeIncidentNumber(string ChangeIncidentNumber)
{
// Do whatever needs to be done
return Json("Test error text", JsonRequestBehavior.AllowGet);
}
In my web.config:
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
The required part works, it displays the Required message if the textbox is empty. But if there is a value it is not hitting my action method. Not sure why?