Reputation: 947
Ok, so I have a WPF Application (using MVVM) consisting of a View that has two textboxes: First Name and Last Name.
Both of them must consist of only letters. I've achieved that by using attributes on the corresponding entity (Worker):
[RegularExpression(@"^[a-zA-Z]+$", ErrorMessage = "First Name must consist of letters only.")]
public string FirstName
[RegularExpression(@"^[a-zA-Z]+$", ErrorMessage = "Last Name must consist of letters only.")]
public string LastName
And it works great. But...I also need to have the following validation rule: At least one of the fields: FirstName or LastName Must be filled.
Any ideas on how to implement validation involving two fields?
The expected result is: If non of the fields is filled, then a validation msg will appear beside the FirstName textbox: At least first name or last name must be filled. The same message will also appear near the the last name textbox. Once I fill one of those fields, Both messages will disppear.
Another challenge, is that if I enter a digit in first name textbox, I want an error message only on the First name textbox: First Name must consist of letters only. And I want the error of at least one of the fields must be filled (near both of the textboxes) to dissapear.
Thanks!
Upvotes: 0
Views: 546
Reputation: 3496
One way is write your own Custom Validation attributes... its not too hard.. i have created couple of custom validation attributes for "Less than" and "Greater than" values which involves two fields... you can modify them for your lastname and firstname validation which is much simpler compared to "Less than" and "Greater Than"
here is the link
http://bathinenivenkatesh.blogspot.co.uk/2011/09/custom-validation-attributes.html
Upvotes: 0
Reputation: 69985
You'd be better off implementing the IDataErrorInfo
Interface, or if you're using .NET 4.5, the newer INotifyDataErrorInfo
Interface. Using the IDataErrorInfo
interface as an example, you'd need to implement an indexer for your data type class and in the indexer, you can define any complicated rules that you can think of:
public override string this[string propertyName]
{
get
{
string error = string.Empty;
if ((propertyName == "FirstName" || propertyName == "LastName") &&
(FirstName == string.Empty || LastName == string.Empty))
error = "You must enter either the First Name or Last Name fields.";
return error;
}
}
Upvotes: 3