0

I am learning MVC (version 5) by doing a sample project. Hence I am not using any scaffolding and doing everything from scratch. I have a View Model, which has a Password field with the following validations.

    [Display(Name = "Password")]
    [DataType(DataType.Password)]
    [Required(ErrorMessage = "{0} is Required.")]
    [Range(1, 4, ErrorMessage = "{0} has to be between {1} and {2} characters.")]
    public string Password { get; set; }

Now in my .cshtml, I have a password textbox rendered using @Html.EditorFor. Since I am learning, I don't have any css added. I have added references to jquery-1.10.2.js, jquery.validate.js and jquery.validate.unobstrusive.js in the cshtml file. The validations are working properly, except for the above password field. If I enter only 1 character in the password textbox, validation passes, whereas anything more than that fails, which is strange. I am not able to understand this. Can anyone please help me with this?

3
  • When you put 2 characters it exceed the range i.e.12 which is greater than 4, but what you inter pretending as length. please see the answer for details Commented Apr 21, 2017 at 9:30
  • 1
    As stated already, range is for numbers, not length of strings. Also, the question is really about how to properly use the Unobtrusive Validation plugin as part of ASP, not the underlying jQuery Validate. Edited tags. Commented Apr 21, 2017 at 14:29
  • Thanks Sparky. Your comment answers the question better. Please add your comment as Reply and I will mark it as Reply. Commented Apr 22, 2017 at 16:02

1 Answer 1

1

As you are using this as string please use below method

[StringLength(4, MinimumLength = 1, ErrorMessage = "{0} has to be between {1} and {2} characters.")]

What you have done is specified value in range so when you put 1 to 4 in the field its valid if you put 5 its not valid because it exceeds the range.

When you need length not the actual value you should use string length on property.

Hope this will solve the problem

Sign up to request clarification or add additional context in comments.

Comments

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.