I'm using micrososofts unobtrusive jquery validation with MVC4 / razor and the default behavior appears to be to first validate on click of submit, and then after that validate onkeyup.
I'd like to change it so it starts validating onblur, and then after the first submit continues to validate on keyup as normal.
Is there a way I can change it to start validating on blur for all forms?
This is the default behaviour when using jquery validate directly or via Microsoft unobtrusive validation. If you enter a non valid entry into a field, that field will be validated on blur even before the field is submitted. If you focus and then blur a field without entering anything this field will only be validated on submitting the form.
From the documentation page section "A few things to look for when playing around with the demo"
Before a field is marked as invalid, the validation is lazy [but] if
the user enters something in a non-marked field, and tabs/clicks away
from it (blur the field), it is validated
I have forked the fiddle in the comment to demonstrate this using the unobtrusive plugin and some rendered html. http://jsfiddle.net/8wkS2/
"Links to jsfiddle.net must be accompanied by code." so here is the rendered markup produced by the server
<input type="text" name="field1" id="field1"
data-val="true"
data-val-required="This field is required"
data-val-length="The field LastName must be a string with a minimum length of 5."
data-val-length-min="5" />
Related
I am using jQuery unobtrusive validation in ASP.NET MVC4 to validate an input contains digits only:
HTML
<input class="form-control"
data-val="true"
data-val-digits="This field may only contain digits."
data-val-range="This field must be between 0 and 25."
data-val-range-max="25"
data-val-range-min="0"
data-val-required="This field is required."
id="DaysHoliday"
name="DaysHoliday"
type="number"
value="">
When I enter "3.5" in the input I correctly get the validation message "This field may only contain digits."
When I enter "foo" in the input I would expect to see the digits validation message, but I actually get the required validation message "This field is required."
Why is the wrong message displayed?
Here is a demo that works fine for me in Safari, Firefox and Chrome, but NOT Explorer 10: http://jsfiddle.net/e0uz8nrs/
Your issue appears to be browser-specific and being caused by the type="number" designation of the field. It simply does not recognize text characters as anything, and therefore you get the same message as an empty field.
You could change the field to type="text" and it will behave more like you expect. I don't believe there's any other workaround for this.
I am showing a text field on a GSP template that is in a formRemote and has content auto populated and is disabled (no editing allowed to user). When the form is submitted, I don't see the content of this field among the params going to the controller. I do see it when I remove the disabled="true" attribute from the text field. Any way to resolve this? Here is the field in question:
<label>Secondary ID:</label> <g:textField name="secondaryId" disabled="true" style="border-radius: 5px" value="${recordToEdit ? recordToEdit.secondaryId : '' }"></g:textField>
Disabled form elements do not get submitted by the browser. You will need to enable the field(s) (through use of Javascript) prior to submitting the form.
I am using Struts2.0.14 for my application. I have a button to clear the textboxes. I have a few boxes which are stateful and values are persistent after the form is submitted.
My problem is that when I press the button before submitting the form it clears all values from the textboxes. But when I submit the form and press reset again, the textboxes do not reset.
I'm not sure if this is your problem, but: to "reset" the fields of an HTML form is not the same as to "clear" them, it just means to reset their values to their "default" values, those that were set (typically) in the value="..." attribute of the field tag.
Now, consider the typical server-side form validation workflow, when the user has entered some field values, submited the form, and get it back from the server with some errors marked (typically in Struts2, this corresponds to the INPUT result). Here, the new HTML page that is returned to the user will have its form fields filled with the previously submitted values. Now, from the client side perspective, those are the "default" values of the form: if you "reset" the form (perhaps after editing it), those are the values that will be restored.
I have a "change password" page that needs to hash any passwords entered on the page via Javascript before sending. To complicate it, the page is loaded via a jQuery load() call, and is submitted by a jQuery.Form ajaxForm() call. Had everything working in MVC2, but MVC3 is giving me trouble.
That is, I have a page with a "Change Password" link that when clicked, loads the change password page into a jQuery modal popup, then the form on the change password page get's submitted via the jQuery.Form library (Essentially just wraps a $.ajax call), and returns it's result into the modal same modal popup.
Essentially, I have a model with two properties, OldPassword and NewPassword. I have two hidden fields generated by by view for these. They hold the hashed value of two other fields, PrehashOldPassword and PrehashNewPassword, and get updated via keyup events (I know, this means it does a whole SHA256 hash on every keyup... inefficient, but got the job doen for testing). The key here is that the regex validation and required field validation needs to be executed on these Prehash fields, which exist on the client side only (As obviously I don't want to transmit these fields to the server in any way).
So I manually create these two and add on the data-val-* attributes to the elements, i.e. they are NOT generated by the MVC helpers, etc. I am guessing that this is where I'm missing something. When the form submits with all fields empty, all of the errors popup that should, but the form goes right ahead and submits anyway.
==
So the things I've tried:
Yes, the unobtrusive library parse() method already get's called to parse the AJAX loaded form contents, and it appears to get all of the data validation stuff correctly, since I see the errors show up as fields blur(), and when I hit submit (before the ajax request completes and replaces the content of the popup).
Possible note: this call to the unobtrusive library's parse method happens AFTER the AJAX successfully loads the change password page into the popup... the AJAX form submit binding is put on document.ready of the loaded content, ergo, the AJAX form submission binding MAY be binding prior to, and thus firing before, the validation calls that the parse method may bind to the submit event...
However, (1) I am doing this same sort of thing in other places without issue, the ONLY DIFFERENCE being that I am manually putting these data-val-* attributes on elements I am creating manually! And (2), if I cause some kind of error on the OldPassword or NewPassword fields, i.e. a required field validation error by not loading a value into them, they display their error, and successfully STOP the form from submitting through the jQuery.Form method.
So I think something has to be wrong here:
<input id="PrehashNewPassword" type="password" name="PrehashNewPassword" data-val-required="The password field is required." data-val-regex-pattern="<%= RegexHelper.PasswordRegularExpression %>" data-val-regex="<%= RegexHelper.PasswordRegularExpressionError %>" data-val="true" />
I know that jquery.validate is getting the rules right, since I DO see the errors. It's just not stopping the form from submitting when their is an error in these manually generated elements, unless I do something like this, and add a pre-submit callback on the form's AJAX submission:
$("#ChangePasswordForm").ajaxForm({
beforeSubmit: function () { if (!$('#ChangePasswordForm').valid()) { return false; } },
target: '#overlay'
});
While this works, it is kind of ugly and I believe it causes the validation to be called twice... Not a huge deal, but less than ideal. So is there some other call that I need to make in the unobtrusive library to bind these?
Not sure if you found the problem, but you may try to
return false
in there if the form is not valid...
.
.
.
if (!$('form').valid()) {
return false;
}
// JSON POST...
.
.
.
If that doesn't work, then you could try to use:
$.validator.unobtrusive.parse($("#dynamicData"));
after dynamically adding your custom inputs. "dynamicData" is the ID of an element wrapped around the form
above found from here: http://weblogs.asp.net/imranbaloch/archive/2011/03/05/unobtrusive-client-side-validation-with-dynamic-contents-in-asp-net-mvc.aspx
Out of interest, what happens if you just get the form to validate?
<script type="text/javascript">
$("form").submit(function (evt) {
// validate here should trigger invalid fields
$('form').valid();
// JSON POST...
// stop form submitting
evt.preventDefault();
});
</script>
What if I have ChangePassword form with hidden ID field of the user.
BadPerson knows id of GoodPerson. He opens Change Password form with FireBug, changes his Id to GoodPerson's Id, so password changes for GoodPerson.
Of course I can create some server logic that will prevent this, but I think there should be some out of the box solution, which throws if hidden field been changed, which I don't know.
EDIT
Ok, Change Password is a bad example. Any edit form where I have id in hidden field has same problem.
I agree with Darin that forms authentication will take care of the specific problem mentioned above (changing a password). This answer is for the more general question of making sure that a hidden field's value is not changed.
The best solution to this is to include another hidden field which contains a hash of the first hidden field's value. That way if the 1st hidden field is changed you will know it. The generated HTML looks something like this:
<input id="productId" name="productId" type="hidden" value="1" />
<input id="productId_sha1" name="productId_sha1" type="hidden" value="vMrgoclb/K+6EQ+6FK9K69V2vkQ=" />
This article shows how to do it and includes source code for an extension Html.SecuredHiddenField which will take care of the logic for you.
There is nothing that will let you know that a value of a hidden field's value has been changed or not. For a user to change his password it means that he needs to be authenticated. When using forms authentication the ID of the currently authenticated user is stored in an encrypted cookie which cannot be modified.
This is to say that you shouldn't use hidden fields for storing the currently connected user. Just use the built-in FormsAuthentication mechanism in ASP.NET and never store such information in hidden fields. The way ASP.NET knows that the value of the cookie hasn't been tampered with is that it signs it with the machineKey specified in the configuration.
There's an important rule that you should follow when dealing with security and authentication: always use built-in security mechanisms, never roll your own.