Regular Expression
The System.ComponentModel.DataAnnotations.RegularExpressionAttribute maps to the pattern validation method in jQuery Validation additional-methods.js.
Here's the model, note that the RegularExpression attribute decorates the sole property on the model:
using System.ComponentModel.DataAnnotations;
namespace jQuery.Validation.Unobtrusive.Native.Demos.Models
{
public class RegularExpressionModel
{
[RegularExpression("^hello$")]
public string RegularExpression { get; set; }
}
}
Here's the view (which uses the model):
@model jQuery.Validation.Unobtrusive.Native.Demos.Models.RegularExpressionModel
@using (Html.BeginForm())
{
<div class="row">
@Html.LabelFor(x => x.RegularExpression, "Only \"hello\" can be entered:")
@Html.TextBoxFor(x => x.RegularExpression, true)
</div>
<div class="row">
<button type="submit" class="btn btn-default">Submit</button>
<button type="reset" class="btn btn-info">Reset</button>
</div>
}
Here's the HTML that the view generates:
<form action="/Demo/Email" method="post">
<div class="row">
<label for="RegularExpression">Only "hello" can be entered:</label>
<input data-msg-pattern="The field RegularExpression must match the regular expression '^hello$'." data-rule-pattern="^hello$"
id="RegularExpression" name="RegularExpression" type="text" value="goodbye" />
</div>
<div class="row">
<button type="submit" class="btn btn-default">Submit</button>
<button type="reset" class="btn btn-info">Reset</button>
</div>
</form>
Here's the JavaScript that initialises the validation:
<script type="text/javascript" src="/Scripts/additional-methods.min.js"></script>
$("form").validate({
submitHandler: function (form) {
alert("This is a valid form!");
}
});