Reputation: 2398
I have an ASP.NET 4.5 Web Site project which is using Razor views. This is not an MVC project, it is an empty web site with just a few .cshtml files in it.
I have a form where I want to validate. I found a site here that explains how to do this with a Razor view, but the Validation class does not have the methods shown in the example. I then came across the required
attribute in HTML5, and I added that to each <input>
in my form. This is validating the form when I submit it, but it is using generic error messages like shown in the image:
Here are my questions:
Is there some way to customize these messages?
Is there some way to validate other requirements besides required
- like making sure its a number, or a certain length, etc?
*Note** I am not using MVC, so no models, etc. I also was trying to use something built in to ASP.NET if possible, and not use jQuery Validation directly.
Thanks in advance!
Upvotes: 2
Views: 3857
Reputation:
Yeah you can do a lot of validation with HTML5 only
Along with the text input type, there are now a host of other options, including email, url, number, tel, date and many others.
You can use setCustomValidity to customize messages and whatnot.
Upvotes: 1
Reputation: 22619
You can set your custom message with data-val-required
attribute.
Make sure you added the jquery validation
and Microsoft jquery unobstrustive js
file in your page.
Below are the example. You can mix all data-val attributes and achieve all your combination
Example 1: Required, length
<input type="text" value="" name="UserName" id="checking-user"
data-val="true"
data-val-required="The UserName field is required."
data-val-length-max="100"
data-val-length="The field UserName must be a string a maximum length of 100."
/>
Example 2: Required, Number and Regex
<input type="text" value="" name="PaidAmount"
data-val="true"
data-val-required="Amount is required"
data-val-regex-pattern="[-+]?[0-9]*\.?[0-9]?[0-9]"
data-val-regex="Amount should be in numbers"
data-val-number="The field PaidAmount must be a number."
/>
Upvotes: 4