Part 83 - RegularExpression attribute in asp.net mvc

Regular expression attribute is great for pattern matching validation. Let's understand using Regular expression attribute with an example. We will be continuing with the example that we started in Part 80 of the asp.net mvc tutorial.

Here is the requirement for validating Name property
1. Name can contain first and last name with a single space. 
2. Last name is optional. If last name is not present, then there shouldn't be any space after the first name.
3. Only upper and lower case alphabets are allowed.

This requirement can be very easily met using RegularExpression attribute. In Employee.cs class file, decorate Name property with RegularExpression attribute.  
[RegularExpression(@"^(([A-za-z]+[\s]{1}[A-za-z]+)|([A-Za-z]+))$")]
public string Name { getset; }

Notice that, we are passing regular expression string to the attribute constructor. Regular expressions are great for pattern matching and ensures that, the value for name property is in the format that we want. Also, notice that we are using a verbatim literal(@ symbol) string, as we don't want escape sequences to be processed. We discussed verbatim literal in Part 4 of C# tutorial.

Understanding and writing regular expressions is beyond the scope of this video. If you are interested in learning to write regular expressions, here is a link from MSDN
http://msdn.microsoft.com/en-us/library/az24scfc.aspx

The following website is very helpful, for writing and testing regular expressions. This website also contains commonly used regular expressions. Infact, I have picked up the regular expression for validating Name property from here.
http://gskinner.com/RegExr/

Let's discuss another example of using validation attribute. A valid internet email address should have an @ and a DOT symbol in it. To match this pattern, use the following regular expression.
^[\w-\._\+%]+@(?:[\w-]+\.)+[\w]{2,6}$

In Employee.cs class file, decorate Email property with RegularExpression attribute as shown below.
[RegularExpression(@"^[\w-\._\+%]+@(?:[\w-]+\.)+[\w]{2,6}$", ErrorMessage = "Please enter a valid email address")]
public string Email { getset; } 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值