After trying to avoid JavaScript for years, Iv started using Query for validation in MVC asp.net, as there does not seem to be an official way of doing validation, Iv been surprised how good jQuery is.
Firstly is there a way to get intellisense working for jQuery and its validation plugin, so that i don have to learn the api?
Secondly how do I create a validation summary for this, it currently appends the error to the right of the text box.:
<script type="text/javascript">
$().ready(function() {
$("#CreateLog").validate({
rules: {
UserName: {
required: true,
minLength: 2,
}
},
messages: {
UserName: {
required: "Please enter a username",
minLength: "Your username must consist of at least 2 characters",
}
}
});
});
</script>
<form id="CreateLog" action="Create" method="post" />
<label>UserName</label><br />
<%=Html.TextBox("UserName")%>
<br />
<div class="error"> </div>
<input type=submit value=Save />
</form>
I tried adding this to the script:
errorLabelContainer: $("#CreateLog div.error")
and this to the html:
<div class="error"> </div>
But this didn't work.
The jQuery validation plugin leverages a CSS selector like syntax to apply a set of validation rules. You can download the plugin (js) file from jQuery website. The password and confirm password objects are matched by the validation plugin for you and shows the message on the equalTo attribute if they don't match.
The above properties are set True by default which means MVC 5 platform ensures that client side validation on form validation is on. For jQuery form validation to work, we set "HtmlHelper. UnobtrusiveJavaScriptEnabled = false;" property false in the register form instead of "web.
Validation in JQuery: Using JQuery, a form is validated on the client-side before it is submitted to the server, hence saves the time and reduce the load on the server. Form Validation means to validate or check whether all the values are filled correctly or not.
Try specifying both a wrapper and a label container in your options. I also added display:none;
to the style of error-container to let jQuery decide when to show it.
$().ready(function() {
$("#CreateLog").validate({
errorLabelContainer: $("ul", $('div.error-container')),
wrapper: 'li',
rules: {
UserName: {
required: true,
minLength: 2,
}
},
messages: {
UserName: {
required: "Please enter a username",
minLength: "Your username must consist of at least 2 characters"
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="error-container">
<ul></ul>
</div>
<form id="CreateLog" action="Create" method="post" />
<label>UserName</label><br />
<%=Html.TextBox("UserName")%>
<br />
<input type=submit value=Save />
</form>
That should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With