|
|||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Want a new Job?
Chapters
Services
Feature Zones
|
IntroductionMicrosoft just released the first preview of ASP.NET MVC Framework and it's Microsoft's way to develop Web applications based on the model-view-controller architecture. It will not replace the classic ASP.NET WebForms model. For more information about the new Framework, please see the Scott Guthrie's blog message. Since there is just a first preview version available, the final feature list is not complete. At this point of time, there is no built-in solution to validate an HTML form on the client and server-side using a standardized system. The Validator Toolkit for ASP.NET MVC offers a way to do form validation on the client and server-side using validation sets. The toolkit is a new project on Microsoft's Open Source Community site at CodePlex.com. NOTICE: The latest version of the source code and the sample site for the Validator Toolkit can be downloaded from the CodePlex project (source code tab). The screenshots below give you an idea about how the toolkit will work:
Here's another screenshot showing how the error messages can be displayed:
Now, let's start! SolutionAs mentioned above, the toolkit uses validation sets as a crucial element. Validation sets are special classes that derive from the The client-side uses the very powerful The validation plug-in used by the toolkit is slightly customized to support all the needed behaviour. Besides using the Before we go ahead, let's have a look at a sample validation set: public class LoginValidationSet : ValidationSet {
protected override ValidatorCollection GetValidators() {
return new ValidatorCollection (
new ValidateElement("username")
{ Required = true, MinLength = 5, MaxLength = 30 },
new ValidateElement("password")
{ Required = true, MinLength = 3, MaxLength = 50 }
);
}
}
This The order of the defined validators also defines the execution order of validation process. If the toolkit would use custom attributes to set validation rules instead of the method Of course, you can also write your own custom validators or you may use the Once a validation set class is defined, you attach it to the view and the HTML form processing controller action using the //
// File: LoginController.cs
//
public class LoginController : Controller {
[ControllerAction]
public void Login() {
RenderView("Login");
}
[ControllerAction]
[ValidationSet(typeof(LoginValidationSet))]
public void Authenticate() {
if(this.ValidateForm())
RenderView("Overview");
else
RenderView("Login");
}
}
...
//
// File: Login.aspx.cs (CodeBehind)
//
[ValidationSet(typeof(LoginValidationSet))]
public partial class Login : ViewPage {
[ValidationSet(typeof(LoginValidationSet))]
public partial class Login : ViewPage {
}
}
The controller action Within the HTML page, you need to initialize script validation for the login form ( <script type="text/javascript">
$(function(){
updateSettingsForSample1ValidationSet($('#loginForm').validate({rules:{}}));
});
</script>
In the next step, you define the HTML form as usual: <form id="loginForm" action="/Login/Authenticate" method="post">
Username: <input type="text" id="username" name="username" /><br />
Password: <input type="text" id="password" name="password" /><br />
<input type="submit" value="Login" />
</form>
Finally, the script that defines the validation rules must be defined: <% this.RenderValidationSetScripts(); %>
You also need to include the <script type="text/javascript" src="../../Content/jDate.js"></script>
<script type="text/javascript" src="../../Content/jQuery.Core.js"></script>
<script type="text/javascript" src="../../Content/jQuery.Delegate.js"></script>
<script type="text/javascript" src="../../Content/jQuery.Validation.js"></script>
That's basically all you need to do - include form validation on the client and server-side. The next section gives you an overview of the standard validators and their usage. Standard ValidatorsThe toolkit offers a handful of standard validators out of the box. The following table gives you an overview of the provided validators:
There are still some validators missing, e.g. a general regular expression validator or a specific email validator. Validation SetsEach validation set definition class derives from the public class LoginValidationSet : ValidationSet {
string Username = "";
string Password = "";
protected override ValidatorCollection GetValidators() {
return new ValidatorCollection
(
new ValidateElement("username")
{ Required = true, MinLength = 5, MaxLength = 30 },
new ValidateElement("password")
{ Required = true, MinLength = 3, MaxLength = 50 },
new ValidateScriptMethod("username", "validateUsername")
);
}
protected bool ValidateUsername() {
// DO HERE SOME VALIDATION AND RETURN RESULT AS BOOLEAN VALUE
return true;
}
protected override void OnValidate() {
if(Username.StartsWith("billy") && Password.StartsWith("gat"))
throw new ValidatorException("username", "The username/password combination ");
}
}
Creating non-public instance member fields of type The Once all validators defined with the Using the described techniques, the possibilities of the LocalizationIt's easy to localize error messages of the toolkit using the standard folder. If the default settings are not changed, the default error message for each validator is stored in the ValidationSet.resx file (in the folder App_GlobalResources). The naming convention for the resource key is as follows: To change the default name of the ValidationSet.resx resource file, a derived validation set class can set the name by using the The sample site within the Custom ValidatorsCreating custom validators is quite simple, but requires some basic knowledge of the
Here is the source code of the public class ValidateBuga : Validator {
public ValidateBuga(string elementsToValidate)
: base(elementsToValidate) {
}
public override ValidatorMethodData GetClientMethodData() {
return new ValidatorMethodData(
"buga",
"function(value,element,parameters){return value=='buga';}",
"$.format('" + ErrorMessageFormat + "')"
);
}
public override string GetClientRule(string element) {
return "buga:true";
}
public override string GetClientMessage(string element) {
return string.Format("buga:'{0}'", GetLocalizedErrorMessage(element))
.Replace("'", "\'");
}
protected override void Validate(string element) {
if(Values.ContainsKey(element) == false || (Values[element] ??
string.Empty).Trim() != "buga")
InsertError(element);
}
protected override string GetDefaultErrorMessageFormat() {
return "The field {0} must contain the value \"buga\"";
}
}
Another way to use custom validation is by using the validator SummaryThe | ||||||||||||||||||||||||||||||||||||||||||||