I have a question on validation in mvc3. The built in validation looks great. However, I've had to use javascript in one case, causing it to be inconsistent w/look and feel (alert window vs nice red text). We have a form which contains a few fields for user input. When submitted, some ajax code fires a link which maps to a controller method that takes the values submitted from the form and kicks off processes which result in a client database being created. The question is: What is the best way to do validation on the fields (length, character, etc) since there is no model directly mapped to the fields on that form? My solution was to write some javascript functions but is there a cleaner way to do it?
<td>@Html.TextBox("NewClientId")</td>
...
<script language="javascript">
function ValidateFieldLength(min, max, element) {
var len = element.value.length;
if (len < min || len > max)
return false;
else {
return true;
}
}
function createNewClient() {
if (!ValidateFieldLength(3,3,document.getElementById('NewClientId'))) {
alert("Invalid Client ID length");
return;
}
$.ajax({
url: '/api/Clients',
type: 'PUT',
data: JSON.stringify({
ClientId: $('#NewClientId').val(),
Name: $('#NewClientName').val()
}),
contentType: 'application/json; charset=utf-8',
success: function (reponse) {
//alert(reponse.data.model.Id);
alert("Database created");
},
error: function (err) {
alert(err);
}
});
}
The other option I would see is adding the validation data attributes manually to the html element. By this way you can avoid duplicating the error messages and other properties in both server and client side.
For ex.
@Html.TextBox("NoOfJoinees", "", new
{
size = 5,
data_val_required="No. of joinees is required",
data_val_number = "The field No. of joinees must be a number.",
data_val_range = "No. of joinees should be minimum 2 and not more than 10",
data_val_range_max="10",
data_val_range_min="2"
})
In the above textbox I've added three types of validations: required, type and range so easily by adding the data attributes. The unobtrusive validation library shipped by microsoft will take care of the rest.
You should read the error messages and other constants from a single place. So you don't need to replicate them when you are doing the validation at the server-side.
You could use jQuery.validate and use some of the built in validation methods.
jQuery.validate
Though might be overkill for what your doing and would still require you to do server side validation.
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