1

I have a MVC4 view with Razor view engine in ASP.Net. I am trying to validate something custom for the 2 password textboxes, but when I try to change the validation message in 'check(this)' javascript function it is still displaying the original validation text of 'This data is a must' when it should be displaying 'Passwords do not match'.

Question: Why javascript is not able to setCustomValidity for a password field?

@{
    ViewBag.Title = "HelloWorld";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>HelloWorld</h2>
<div>This is a sample Hello World page</div>
<h1>@ViewBag.Title</h1>
<h2>@ViewBag.Message</h2>
@using (Html.BeginForm("HandleSubmit", "Home"))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary()

    <fieldset>
        <legend>Registration Form</legend>
        <ol>
            <li>
                @Html.TextBox("username", null, new { @required = "required", @oninvalid = "this.setCustomValidity('This data is a must')", @placeholder = "Input User Name" })
            </li>
            <li>
                @Html.Label("pwd", "Password")
                @Html.Password("pwd", null, new { @required = "required", @oninvalid = "this.setCustomValidity('This data is a must')", @placeholder = "Input Password" })
            </li>
            <li>
                @Html.Label("cpwd", "Confirm Password")
                @Html.Password("cpwd", null, new { @required = "required", @oninvalid = "this.setCustomValidity('This data is a must')", @placeholder = "Confirm Password", @onblur = "check(this)" })
            </li>
        </ol>
        <input type="submit" value="TestPost" onclick="checkpwds()" />
        <div style="color:red;font-weight:bold">@ViewBag.Feedback</div>
    </fieldset>
}
<script language='javascript' type='text/javascript'>
    function check(input) {
        if (input.value != document.getElementById('pwd').value) {
            input.setCustomValidity('Password Must be Matching.');
        } else {
            input.setCustomValidity('');
        }
    }

    function checkpwds() {
        if (document.getElementById('pwd').value != document.getElementById('pwd').value) {
            document.getElementById('pwd').setCustomValidity('Password Must be Matching.');
        } else {
            document.getElementById('pwd').setCustomValidity('');
        }
    }
</script>

UPDATE 1: As suggested by Stephen in his comments below, I removed the oninvalid event from all textboxes, and called the 'check' JavaScript method when focus leaves a textbox i.e. in onblur event, I was able to make this work. Modified code is given below.

I have used a single JavaScript function called 'check' as the validation method for all textboxes, in which I can put any custom validation I feel like, and I call this method in onblur event of all textboxes. This allows me complete freedom in how I want to validate. You could also use the oninput event for firing the validation method of check instead of onblur, which would clear the validation message as soon as you have typed valid input instead of clearing it on leaving focus.

 @{
    ViewBag.Title = "HelloWorld";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>HelloWorld</h2>
<div>This is a sample Hello World page</div>
<h1>@ViewBag.Title</h1>
<h2>@ViewBag.Message</h2>
@using (Html.BeginForm("HandleSubmit", "Home"))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary()

    <fieldset>
        <legend>Registration Form</legend>
        <ol>
            <li>
                @Html.TextBox("username", null, new { placeholder = "Input User Name",
                               @onblur = "check(this)" })
            </li>
            <li>
                @Html.Label("pwd", "Password")
                @Html.Password("pwd", null, new { @placeholder = "Input Password", 
                                @onblur = "check(this)" })
            </li>
            <li>
                @Html.Label("cpwd", "Confirm Password")
                @Html.Password("cpwd", null, new {  @placeholder = "Confirm Password",
                                 @onblur = "check(this)" })
            </li>
        </ol>
        <input type="submit" value="TestPost"  />
        <div style="color:red;font-weight:bold">@ViewBag.Feedback</div>
    </fieldset>
}
<script language='javascript' type='text/javascript'>
    function check(input) {

        if (input.id == "cpwd" && input.value != document.getElementById('pwd').value && input.value != '') {
            input.setCustomValidity('Password Must be Matching.');
        }
        else if (input.value == '') {
            input.setCustomValidity('Required Data!'); 
        }
        else {
            input.setCustomValidity('');
        }
    }
</script>
Sunil
  • 20,653
  • 28
  • 112
  • 197
  • you are also using model validations???? – Kartikeya Khosla Aug 28 '14 at 05:15
  • 1
    You may need to call `checkValidity();` to trigger updating the message –  Aug 28 '14 at 05:18
  • @Exception, I am not using Model validation. I am just learning MVC4 with this practice sample without a model. – Sunil Aug 28 '14 at 05:22
  • @StephenMuecke, Where does this checkValidity method need to be called in my sample code? – Sunil Aug 28 '14 at 05:27
  • 1
    I haven't used it before so not sure, but try after the `if/else` block in the `checkpwds()` function. I suspect `@oninvalid = "this.setCustomValidity('This data is a must')"` may be overriding what you doing in `checkpwds()`. You could try moving the `@oninvalid` bit to a seperate function, add some breakpoints and step through the code so see which gets called first. –  Aug 28 '14 at 05:36

1 Answers1

1
document.addEventListener("DOMContentLoaded", function() {
    var elements = document.getElementsByTagName("INPUT");
    for (var i = 0; i < elements.length; i++) {
        elements[i].oninvalid = function(e) {
            e.target.setCustomValidity("");
            if (!e.target.validity.valid) {
                e.target.setCustomValidity("This field cannot be left blank");
            }
        };
        elements[i].oninput = function(e) {
            e.target.setCustomValidity("");
        };
    }
})

For detail check this - HTML5 form required attribute. Set custom validation message?

Community
  • 1
  • 1
Systematix Infotech
  • 2,345
  • 1
  • 14
  • 31