1

I have the following model

public AccountInfo {

    // loads of other property here as well.

    public string Password { get; set; }

    public string NewPassword { get; set; }

    [Compare("NewPassword", ErrorMessage = "New Passwords dont match.")]
    public string ConfirmNewPassword { get; set; }

}

I am using data annotations to display client side validation message.

Now I am working on the change user profile details page.

What I am required to do is, Along with the other details such as email, full name, address etc, I have to show 3 fields namely

  • Current password
  • New password
  • Confirm New password

Now the scene is that these are optional fields and user may not fill it. But when he does, I want to make sure all the 3 fields are filled., if not I want to show some validation error using data annotation.

Any Thoughts ?

6

2 Answers 2

1

There isn't any built in data annotation for this. You could create your custom attribute to do the validation, but it's not easy. As such, I would suggest you to use Jquery Validation / Javascript to handle this.

Basically you would want to override the submit event and do your own validation logic in there. You code will be similar to this:

function SubmitToServer() { 
    if ($('#Password').length == 0 || ($('#Password').length > 0 && $('#NewPassword ').length > 1 && $(formId).valid()) {
        $(formId).submit();
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

did client side validation using jquery.
0

You can use [Required] to tell the RAZOR that these are must or mandatory like that..

[Required]
public string Password { get; set; }

 [Required]
 public string NewPassword { get; set; }

 [Required]
 [Compare("NewPassword", ErrorMessage = "New Passwords dont match.")]
 public string ConfirmNewPassword { get; set; }

If you want to Provide range of value means use this one - [Range(1, 100)]

If you want to use password lenght means use this one - [StringLength(5)]

1 Comment

thanks for your answer, BUT this is not what I am looking for. please read the question again. I want to make sure all the 3 fields are filled if even one of them is filled and they can all be empty also.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.