I know what the jQuery Validation plugin is. I know the jQuery Unobtrusive Validation library was made by Microsoft and is included in the ASP.NET MVC framework. But I cannot find a single online source that explains what it is. What is the difference between the standard jQuery Validation library and the "unobtrusive" version?
Brad Wilson has a couple great articles on unobtrusive validation and unobtrusive ajax.
It is also shown very nicely in this Pluralsight video in the section on " AJAX and JavaScript".
Basically, it is simply Javascript validation that doesn't pollute your source code with its own validation code. This is done by making use of data- attributes in HTML.
With the unobtrusive way:
You don't have to call the validate() method.
You specify requirements using data attributes (data-val, data-val-required, etc.)
Jquery Validate Example:
<input type="text" name="email" class="required">
<script>
$(function () {
$("form").validate();
});
</script>
Jquery Validate Unobtrusive Example:
<input type="text" name="email" data-val="true"
data-val-required="This field is required.">
<div class="validation-summary-valid" data-valmsg-summary="true">
<ul><li style="display:none"></li></ul>
</div>
For clarification, here is a more detailed example demonstrating Form Validation using jQuery Validation Unobtrusive.
Both use the following JavaScript with jQuery:
$("#commentForm").validate({
submitHandler: function(form) {
// some other code
// maybe disabling submit button
// then:
alert("This is a valid form!");
// form.submit();
}
});
The main differences between the two plugins are the attributes used for each approach.
jQuery Validation
Simply use the following attributes:
Set required if required
Set type for proper formatting (email, etc.)
Set other attributes such as size (min length, etc.)
Here's the form...
<form id="commentForm">
<label for="form-name">Name (required, at least 2 characters)</label>
<input id="form-name" type="text" name="form-name" class="form-control" minlength="2" required>
<input type="submit" value="Submit">
</form>
jQuery Validation Unobtrusive
The following data attributes are needed:
data-msg-required="This is required."
data-rule-required="true/false"
Here's the form...
<form id="commentForm">
<label for="form-x-name">Name (required, at least 2 characters)</label>
<input id="form-x-name" type="text" name="name" minlength="2" class="form-control" data-msg-required="Name is required." data-rule-required="true">
<input type="submit" value="Submit">
</form>
Based on either of these examples, if the form fields that are required have been filled, and they meet the additional attribute criteria, then a message will pop up notifying that all form fields are validated. Otherwise, there will be text near the offending form fields that indicates the error.
References:
- jQuery Validation: https://jqueryvalidation.org/documentation/
jQuery Validation Unobtrusive Native is a collection of ASP.Net MVC HTML helper extensions.
These make use of jQuery Validation's native support for validation driven by HTML 5 data attributes.
Microsoft shipped jquery.validate.unobtrusive.js back with MVC 3.
It provided a way to apply data model validations to the client side using a combination of jQuery Validation and HTML 5 data attributes
(that's the "unobtrusive" part).
Related
I have an Angular 4 form, but with the data tracked in an injected service (for reasons outside the scope of this question).
Each input looks something like...
<input name="..." [ngModel]='getVal(...)' (ngModelChange)='setVal(...)'>
...because there's extra functionality in those getters/setters.
That's working great, but I would also like to use the built-in validation. If I give my form a template reference variable...
<form id="..." #myForm="ngForm">
and look at the value of myForm, it's not tracking any of those inputs. I get that, I mean, I'm specifically telling it to track them elsewhere.
But how can I take advantage of the built in HTML5 validation? i.e. required and pattern
You can use validation like this in your html. This is template based validation as per your requirement.
Submit button will not be active till all the fields are validated.
<form (ngSubmit)="submitFunc()">
<input name="name" [ngModel]='getVal(...)' (ngModelChange)='setVal(...)'
required pattern=""> //required pattern here
<button [disabled]="!myForm.form.valid" type="submit">Submit Form </button>
</form>
You have to add required in your input field and specify pattern with a regular exression.
Excuse me for this simple question. I have aJSP in which I have several forms, each of which consist of multiple text boxes which take different types of text (eg. Date, Name, Balance). How to make the user fill the fields and then only submit to the server? Is it possible to use only one js function?
Note: this answer does not use any JSP nor JavaScript, because in HTML5 this is no longer necessary.
You could use HTML5's required attribute on the inputs, and then let the user know the inputs are not correctly filled in via the :invalid CSS pseudo-class. It would look something like this:
HTML:
<form id="myForm" action="#">
<label>Date: <input type="date" name="date" required></label>
<br>
<label>Name: <input type="text" name="firstname" required></label>
<input type="text" name="lastname" required>
<br>
<label>Balance: <input type="number" name="balance" required></label>
<br>
<button>Submit</button>
</form>
CSS:
#myForm input:valid {
background:#AFA;
}
#myForm input:invalid {
background:#FAA;
}
Demo.
Extra info
For a complete list of input types (such as those listed above, but also ones like email or checkbox) see MDN or this interactive page with demos
For more information on cross-browser compatibility of :valid and :invalid, see MDN on :valid and :invalid
Notes
These specific input types will also restrict or simplify the input for users. The number inputs will restrict input to numbers only (it will prevent the submission of the form otherwise), and the date inputs will clarify to the user how the date should be entered. Both will also simplify entering information to these inputs
Note that not all of these are supported by older browsers, which will often default to the plain text input. See caniuse and MDN's list for the full details on browser support.
Never rely on client-side verification only. It's very easy to modify forms on the client's side, which could lead to XSS vulnurabilities. Always verify proper input on the server too.
This question already has answers here:
Required attribute HTML5
(7 answers)
Closed 9 years ago.
I use required for a 1st check before submitting a form.
<form action="myform.php">
Foo: <input type="text" name="someField" required="required">
<input type="submit" value="submit">
<input type="submit" value="ignore">
</form>
Problem is, that I have an "ignore" button, which submits the form as well and the backend logic then sets a correct state in a DB. In this case (ignore) the validation is not desired (because there is no need to fill in field "Foo").
What's the best way to handle the 2 scenarios?
I am aware that I could give up "required" and do the validation somewhere else (backend / JavaScript). I am looking for a way to keep the "required".
I could use some Js onclick for the ignore button scenario and remove the attribute just before sending the form ( https://stackoverflow.com/a/13951500/356726 ).
But actually I am looking for something smarter ....
--- Edit ---
Yes, duplicate of Required attribute HTML5
No JavaScript, no second form needed, and the validation can stay:
For exactly this use case the HTML5 spec has designed the formnovalidate attribute for submit elements (like <input type=submit>), as one of the attributes for form submission:
The formnovalidate attribute can be used to make submit buttons that do not trigger the constraint validation.
So simply put
<form action="myform.php">
Foo: <input type="text" name="someField" required>
<input type="submit" value="submit">
<input type="submit" value="ignore" formnovalidate>
</form>
Your #2 is a common approach. Something like:
$('input[value="ignore"]').click(function() {
$(this).siblings('input[type="text"]').removeAttr('required');
});
Might have to use mousedown to beat submit.
If you don't want to use Javascript, you could make them separate forms and have all the inputs set to hidden for the ignore form.
Not the best option, but it is an alternative.
You should use approach #1 on the following grounds: The main reasons for using required instead of JavaScript validation is that it is simpler and it works even when JavaScript is disabled. Here the simplicity does not apply, since the use of required makes things more difficult. And the latter reason does not apply either: with JavaScript disabled and the browser supporting required, the “ignore” button does not work unless some data is entered in the textfield.
Another alternative is the one mentioned on #MattKenefick’s answer. It might even result in simpler structure and logic. If the form is really as simple as in the example, it is straightforward to split it to two forms:
<form action="myform.php">
Foo: <input type="text" name="someField" required="required">
<input type="submit" value="submit">
</form>
<form action="myform.php">
<input type="submit" value="ignore">
</form>
I have a long long long form. It has about 200 fields. Now, about 50 fields need to be validated through JavaScript / jQuery. How can I easily validate them without a huge amount of code. I want to avoid doing this:
field1 = document.getElementById("field1").value;
if (field1 == '') {
alert ("Please enter a value for Field1");
return false
}
Is there an easier way? Thanks a lot.
Use the jquery Form validation plugin and assign the correct classes to the fields.
It's as simple as class="required" in most cases!
If you just want to check if the field is empty or not you could do something like this using jQuery:
HTML:
<form>
<input class="validate" type="text" />
<input type="text" />
<input class="validate" type="text" />
<input type="text" />
<input class="validate" type="text" />
</form>
SCRIPT:
$('.validate').each(function() { //this will get every input marked with class "validate"
if ($(this).val() == '')
return false;
});
Using JQuery validate plugin can be much help. You can control the way plugin works from your HTML code and even not write any javascript! If you need more complex validatio, you can extend it by adding specific validation functions. It allows you to localize the application as well.
This page gives a good example on how to use the plugin: http://jquery.bassistance.de/validate/demo/milk/ (click the "Show script used on this page" link).
Here is a rudimentary fiddle, that you can use to validate your form, Just add a span after each of the fields that you need to validate.
http://jsfiddle.net/refhat/h2S6G/35/
I thought about this too, but the plugin can be a bit difficult to
use. Do you know if it allows to display an alert box when an error is
found, instead of the actual displaying on the page? That's a bit too
much for this form. Thanks a lot
Here's a validator I wrote that uses a pop-up style alert box for error messages. Is that the sort of thing you are after?
http://validator.codeplex.com/
Do you want default error messages like for required validator? Regarding jquery validate plugin was it the syntax it offers to place validation information in the method call you found difficult since for a large form having validation information located separately from the text boxes makes it harder to go through and verify all fields have the right validators and messages?
How can I instruct jQuery Validation plug-in to turn off validation based on class attributes and just work based on json rules?
This is conflicting with my jQuery templating system.
First, in your JQuery ready function set the class to 'ignore' or 'require' for each element:
$("#name").attr("class", "required");
$("#email").attr("class", "ignore");
Second, set validate function to ignore the 'ignore' class:
$("#form1").validate({ignore: ".ignore"});
This will require the name but ignore the email.
Looking at the source of jquery.validate.js, there is a variable called classRuleSettings, which stores the validation types based on class names. Set it to a 0 length array and you shold be good.
Try this():
<form>
<input type="text" class="required"/>
<input type="Submit"/>
</form>
<script type="text/javascript">
$.validator.classRuleSettings = []; //I am not sure about any side effects because of this
$("form").validate();
</script>
You can use ignore option
$("form").validate({ignore:".ignore"});
<input type="text" id="fName" class="required ignore"/> <!--fname won't be "required"-->