Reputation: 27
I have a "Postcode" text box and in order for it to insert correctly in my database it require a white space in the middle i.e "N18 2JY".
Is there a way I can validate/check to see whether a user has entered the postcode correctly and give an error message if its missing?
Thanks in advance :)
Upvotes: 0
Views: 2485
Reputation: 291
@Martin Liversage answered is better answer for MVC pattern to control the validations.
If you think the Regular expression is very common, then you can override the RegularExpressionAttribute like sample below:-
public class AlphaSpaceAttribute : RegularExpressionAttribute, IClientValidatable
{
public AlphaSpaceAttribute()
: base(@"^([a-zA-Z ]*)\s*")
{
}
public override string FormatErrorMessage(string name)
{
return Resources.UDynamics.EM_10003;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(this.ErrorMessage),
ValidationType = "regex",
};
rule.ValidationParameters.Add("pattern", @"^([a-zA-Z ]*)\s*");
yield return rule;
}
}
Above code I override the RegularExpressionAttribute to only allow A-Z and spacing. Keep in mind one property only allow one RegularExpressionAttribute.
Upvotes: 0
Reputation: 106826
You can do that using unobtrusive validation which will allow the validation to be performed client side if possible but also server side if client side validation is circumvented. Briefly you need to add one or more validation attributes to your view model:
class MyViewModel {
[RegularExpression("[^ ]+ [^ ]+")]
public String PostCode { get; set; }
}
and then in the view for the view model render the post code field:
Html.EditorFor(model => model.PostCode)
In the action you post to when the form is submitted you need to verify that the model is valid:
public ActionResult Save(MyViewModel viewModel) {
if (!ModelState.IsValid)
return View(viewModel);
... process a valid submission
}
You also need to turn on unobtrusive validation in Web.config
:
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
Upvotes: 3