I need to add client-side form validation to an HTML5 form. I don't want to hack my own solution and I'm not using Angular.
Since I'm using HTML5, the pattern and required attributes combined cover basic validation.
However, where custom validation is needed, for example, requiring a specific combination of checkboxes are ticked - I need something more.
A quick web search took me to The 10 Best JavaScript Libraries for Form Validation and Formatting.
I tested out Validate.js and hit a problem when validating checkboxes. Validate.js binds to specific form elements by name, e.g.
var validator = new FormValidator('example_form', [{
name: 'req',
rules: 'required'
});
The corresponding HTML form:
<form name="example_form">
<input name="req" />
</form>
I decided to apply this to a group of checkboxes AND implement my own custom rule (documented on Validate.js):
<form name="example_form">
<input type="checkbox" name="test" value="a">
<input type="checkbox" name="test" value="b">
<input type="checkbox" name="test" value="c">
</form>
Firstly, the Validator configuration object adding my custom rule:
var validator = new FormValidator('example_form', [{
name: 'test',
rules: 'callback_my_rule'
});
...notice the required rule (provided out-of-the-box) is gone, and has been replaced by my own rule callback_my_rule. Next I defined my_rule (as per the documentation, the callback_ prefix is dropped):
validator.registerCallback('my_rule', function(value) {
var atLeastOne = ($('[name="test"]:checked').length > 0);
return atLeastOne;
});
A return value of False means validation failed, whereas True is valid.
The problem is, if no checkboxes are ticked, my custom validation function, my_rule, is never called. Only when I tick a checkbox is the function called. It seems a unintuitive to only call custom validation functions when a checkbox is ticked.
The Validate.js documentation provides an example form with a checkbox, however, the checkbox validation function is omitted from the sample code:
However, the example form does validate the checkbox, digging around the source of Validate.js documentation, I see the checkbox uses the out-of-the-box required rule:
Questions
Has anyone got Validate.js working with checkboxes and custom
validation functions?
Is there a better library for custom form
validation?
I have tested Jquery Validation Plugin and works like a charm with checkbox!
DEMO LINK http://jsfiddle.net/K6Wvk/
$(document).ready(function () {
$('#formid').validate({ // initialize the plugin
rules: {
'inputname': {
required: true,
maxlength: 2
}
},
messages: {
'inputname': {
required: "You must check at least 1 box",
maxlength: "Check no more than {0} boxes"
}
}
});
});
Related
I have a site that is being built in ASPX. Unfortunately, because of this fact, I cannot actually use the <form> tag to wrap my inputs, and as far as I can see, jQuery Validation Plugin only supports validating inputs within a <form>. Is there any way to validate these inputs, using the specified rules, on keyup without having them wrapped in a <form> tag?
$(function() {
$('.form-container').validate({
rules: {
useremail: {
required: true,
email: true
},
userstate: {
required: true,
maxlength: 2
}
},
messages: {
useremail: 'Please enter a valid email',
userstate: 'Please enter your state',
}
});
$('.form-container input').on('keyup', function() {
$(this).validate();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.18.0/jquery.validate.min.js"></script>
<div class="form-container">
<input type="text" name="useremail" placeholder="Email" />
<input type="text" name="userstate" placeholder="State" maxlength="2" />
</div>
You cannot have nested forms, which is invalid HTML, and you must attach .validate() to a form container. There are no workarounds.
You're also using .validate() all wrong. Since this is the primary initialization method of the plugin, wrapping it within a keyup handler is not correct. Plus the plugin already uses the keyup event to trigger validation.
And no, you cannot put form input elements within a div and then target that div attached to .validate(). It will be ignored. You can only target form elements attached to .validate().
Furthermore, since you're using ASP, you can leverage its built-in Unobtrusive Validation plugin, which automatically constructs and calls the .validate() method based upon your data attributes. Just remember that if you follow this route, you cannot call .validate() yourself. The plugin only allows one call, and once initialized, all subsequent calls to .validate() are ignored.
What is the "Angular" recommended way to validate conditions that involve multiple fields on a form? Most or all of the validation examples that I have seen talk about custom validation directives that attach to a single textbox,select,etc. What about conditions that involve multiple fields on a form?
For example, I want to have an "empty" form validator: This will prevent submits on forms that have no required fields and all fields are empty.
Another example is, say I have a master/child one-to-many relationship on a page and the child relationship is a table of child records. What if I need to validate that at least one child record should exist IF 2 or 3 fields meet certain conditions?
One thought that I have is to built validation directives that attach to <form> tags as elements. Something like <form name="xxx" validate-not-empty > This directive will then set the $invalid property of the form, on submit. But I am concerned that this maybe is not the angular away to go as I have not seen this on any code samples I have seen. So I am looking for any alternatives to achieve this.
What is wrong with having your "not-empty" directive placed on each of your input field? (following this way of doing: http://angularjs.io/how-to-create-a-custom-input-validator-with-angularjs/)
Then you can just check anywhere if the form is valid, for example to disable the send button:
<button ng-disabled="!form.$valid">Send</button>
For it to work you must have all input with its ng-model.
I didn't quiet understand your master/child problem. It you could give an example...
I've used the basic validation, based on input type (email, tel, etc.) and the "required" attribute. But, more complex validation is typically handled through custom directives. Although, there may very well be a library that I'm not aware of that provides a common set.
As a basic example:
<form name="contactForm">
<input type="text" name="ContactName" ng-model="contact.name" required>
<button type="button" ng-click="submitForm(contactForm)" />
</form>
Then, in your controller:
$scope.submitForm = function (form) {
if (form.$valid) {
...
}
}
This W3Schools page describes Angular's validation fairly well.
AngularJS Form Validation
Toward the bottom of the article, they mention that custom validation requires a bit more effort. But, they provide examples.
To create your own validation function is a bit more tricky. You have
to add a new directive to your application, and deal with the
validation inside a function with certain specified arguments.
<form name="myForm">
<input name="myInput" ng-model="myInput" required my-directive>
</form>
<script>
var app = angular.module('myApp', []);
app.directive('myDirective', function() {
return {
require: 'ngModel',
link: function(scope, element, attr, mCtrl) {
function myValidation(value) {
if (value.indexOf("e") > -1) {
mCtrl.$setValidity('charE', true);
} else {
mCtrl.$setValidity('charE', false);
}
return value;
}
mCtrl.$parsers.push(myValidation);
}
};
});
</script>
Hope this helps.
I am designing a form with bootstrap UI. i want to make my input, select option fields required. But my code not working.
Here following markup and code details on jsfiddle.
http://jsfiddle.net/g28vvw77/
Is that possible by writing a function here,
$('#paynow').click(function(){
}
I tried to used validator.js but it does not work, may be for ajax issue. Anyone can review my code and give solution to make field validation or just required warning.
I just want to implement this type of feature, http://jsfiddle.net/5WMff/
please use this syntax to validate your form
$("#f").validate({
rules: {
field01: {
required: true
},
field02:{
required: true,
},
field03: {
required: true
},
field04: {
required: true,
},
field05: {
required: true
}
},
submitHandler: function(form) {
form.submit();
}
});
here is f is your form id and field0* will be the name of your input fields that you want to be required.
I would add the required tag to your input and select elements that are actually required.
Your code looks like it's processing correctly, however you aren't validating anything with your JS or with HTML5.
EDIT:
You have a rogue </form> tag. It's closing the form before the buttons are introduced.
If you remove line 226 of your JSFiddle example, it should fix the problem.
Using this jQuery validation plugin.
http://www.benjaminkeen.com/software/rsv/jquery/index.php
I want to validate a checkbox group with JS, but when i use the statement:
rules.push("required,accomodationtype[],Please check all that apply");
or
rules.push("required,accomodationtype\[\],Please check all that apply");
for this kind of checkbox group:
<INPUT type="checkbox" name="accomodationtype[]" id="accomodationtype_0" value="hotel1">Hotel1<BR>
<INPUT type="checkbox" name="accomodationtype[]" id="accomodationtype_1" value="hotel2">Hotel2<BR>
<INPUT type="checkbox" name="accomodationtype[]" id="accomodationtype_2" value="hotel3">Hotel3<BR>
<INPUT type="checkbox" name="accomodationtype[]" id="accomodationtype_5" value="other"> Other (please specify)<BR>
<INPUT type="text" name="accomodationtypeother" id="accomodationtypeother">
It doesn't validate and it immediately posts the form. I am not sure if I am doing something wrong.
Update
I have custom error handler. Tried Alper's suggestion getting this error message: errorInfo[i][0].focus is not a function
function errorHandler3(f, errorInfo)
{
for (var i=0; i<errorInfo.length; i++)
{
// errorInfo[i][0] contains the form field node that just failed the validation, e.g.
errorInfo[i][0].focus();
// errorInfo[i][1] contains the error string to display for this failed field, e.g.
$.notifyBar({
cls: "error",
html: errorInfo[i][1]
});
}
if (errorInfo.length == 0) tcrform_submit();
return false;
}
I'm not sure that this will help, this post is dealing with radiobuttons but perhaps the same rules apply
Validation of radio button group using jQuery validation plugin
there's not enough information for this issue.
Please attach the entire code (js, html), so that we can debug for you.
and for my first glance, I think there must be an "js error" occurred in your code. so I suggest that you should install firebug and make it open focusing "console" tab. then you will see the error message for the senario: "It doesn't validate and it immediately posts the form. "
By default, Zend_Form creates a hidden input field for each checkbox input in the form. These inputs share the same name.
<input type="hidden" name="zend-cb" value="">
<input type="checkbox" name="zend-cb" id="zend-cb" value="1">
I want to require the checkbox, so I set up the following rule in my jquery plugin validator (http://bassistance.de/jquery-plugins/):
'zend-cb': {
required: true
}
Unfortunately, the Jquery Validation plugin always validates the hidden field instead of the checkbox. Is there a way I can have it validate the checkbox instead? I realize I could change my Zend Decorator to omit the hidden field, but I'd like to find a pure javascript solution.
Solution
Two steps are needed to get around this problem.
1) Add ignore: "input[type=hidden]" as an option to the validate method.
$('#myForm').validate( {
ignore: "input[type=hidden]",
rules: { ... }
}
2) Open jquery.validate.js and update the findByName method to use the ignore filter. Bug report filed by adamnfish on the jquery plugin site.
findByName does not honour ignore settings
findByName: function( name ) {
// select by name and filter by form for performance over form.find("[name=...]")
var form = this.currentForm;
return $(document.getElementsByName(name)).not(this.settings.ignore).map(function(index, element) {
return element.form == form && element.name == name && element || null;
});
},
You can use the ignore option of the validation plugin.
$("#yorform").validate({
...
ignore: "input[type=hidden]"
})
This should for example stop the plugin from validating any hidden inputs
Check the documentation for more info