I am fairly new to development and attempting to learn C# development with Blazor. I am currently learning how to build forms using EditForms and validate using DataAnnotationsValidator.
I've successfully done most of what I need to do for validation before I move on to processing the form, however, I am having trouble with one important aspect of validation: The form I am working on is a registration form for a new user. Generally, when registering new users, you might wish to have a user re-enter a value like an email address or password to ensure that they have typed it correctly:
<InputText @bind-Value=User.email id="email" /><br />
<ValidationMessage For=@( () => User.email) />
<label for="confirm">Confirm Email</label><br />
<InputText @bind-Value=User.confirm id="confirm"/><br />
To validate these fields, I have class UserModel which I have instantiated as User().
@code
{
UserModel User = new UserModel();
class UserModel
{
[Required]
[EmailAddress(ErrorMessage = "Please enter a valid email address.")]
public string email { get; set; }
[Required]
[EmailAddress(ErrorMessage = "Please confirm your email address.")]
[Compare(email, ErrorMessage = "The email addresses you entered did not match.")]
public string confirm { get; set; }
public string fname { get; set; }
public string lname { get; set; }
public string pwd { get; set; }
public string error = "";
public void Submit()
{
}
}
In Microsoft's documentation for DataAnnotationsValidator, I found a Class CompareAttribute, which, according to the documentation "provides an attribute that compares two properties." I believe this will do what I need, but I am having trouble using it. Compare takes the argument otherProperty which I believe would be the other user input I am trying to match, however, I can't figure out how to pass the previous input as this argument.
I've tried email, however, an object reference is required. It doesn't seem like I'd want to reference an instance of the class within the class itself, so I tried this.email but got the error "Keyword 'this' is not available in the current context."
If anyone could help me figure out the proper way to use the Compare class in my situation, I would be very appreciative. Otherwise, if I am barking up the wrong tree, please let me know. Thanks!