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);
}
});
}