jQuery checkbox validation issue - javascript

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. "

Related

JavaScript native form abilities [duplicate]

I want to know if there is any way to programmatically show a HTML validation error, using a JavaScript function.
This is useful for scenarios where email duplication has to be checked. For example, a person enters an email, presses the Submit button, and then has to be notified that this email is already registered or something.
I know there are other ways of showing such an error, but I wanted to display it in the same way as how the validation error messages are shown (e.g. invalid email, empty field, etc.).
JSFiddle: http://jsfiddle.net/ahmadka/tjXG3/
HTML Form:
<form>
<input type="email" id="email" placeholder="Enter your email here..." required>
<button type="submit">Submit</button>
</form>
<button id="triggerMsg" onclick="triggerCustomMsg()">Trigger Custom Message</button>
JavaScript:
function triggerCustomMsg()
{
document.getElementById("email").setCustomValidity("This email is already used");
}
The above code sets the custom message, but its not automatically shown. It's only shown when the person presses the submit button or something.
You can now use the HTMLFormElement.reportValidity() method, at the moment it's implemented in most browsers except Internet Explorer (see Browser compatibility at MDN). It reports validity errors without triggering the submit event and they are shown in the same way.
var applicationForm = document.getElementById("applicationForm");
if (applicationForm.checkValidity()) {
applicationForm.submit();
} else {
applicationForm.reportValidity();
}
reportValidity() method will trigger HTML5 validation message.
This question was asked over a year ago, but it's a good question that I recently encountered as well...
My solution was to use JavaScript to create an attribute (I went with "data-invalid") on the <label> of each <input>, <select> and <textarea> containing the validationMessage.
Then some CSS...
label:after {
content: attr(data-invalid);
...
}
... displays the error message.
Limitations
This only works provided each element has a label. It will not work if you put the attribute on the element itself, because <input> elements cannot have :after pseudo elements.
Demo
http://jsfiddle.net/u4ca6kvm/2/
As mentoned by #Diego you can use form.reportValidity();
To support IE and Safari include this polyfill, it just works:
if (!HTMLFormElement.prototype.reportValidity) {
HTMLFormElement.prototype.reportValidity = function() {
if (this.checkValidity()) return true;
var btn = document.createElement('button');
this.appendChild(btn);
btn.click();
this.removeChild(btn);
return false;
}
}

Why are custom validation messages causing my HTML form elements to stay invalid?

I've implemented a custom validation message on my input for the pattern validation rule while leaving the default message for required as is. However, when I do so, once the input becomes invalid, it never becomes valid again, even though I am meeting the pattern criteria.
document.addEventListener("DOMContentLoaded", function () {
const txtUsername = document.getElementById("UserName");
txtUsername.oninvalid = function (e)
{
const input = e.target;
if (input.validity.patternMismatch)
{
input.setCustomValidity("Usernames cannot contain the # symbol");
}
}
})
<form onsubmit="event.preventDefault(); alert('Form submitted');" action="post">
<!--pattern regex prohibits use of the # symbol-->
<input id="UserName" type="text" pattern="^((?!#).)*$" required />
<button type="submit">Submit</button>
</form>
JSFiddle demo
When I remove my custom oninvalid event handler, this issue does not occur. What am I doing wrong?
One additional question, though not essential to me resolving this issue: why does Chrome's built in validation pop-up text animate in so slowly and choppy, almost as if there's some sort of performance bottleneck? My machine is powerful and has no issues with any other type of graphical processing.
First of all, per MDN:
It's vital to set the message to an empty string if there are no errors. As long as the error message is not empty, the form will not pass validation and will not be submitted.
This agrees with that the HTML standard says:
Suffering from a custom error
When a control's custom validity error message (as set by the element's setCustomValidity() method or ElementInternals's setValidity() method) is not the empty string.
An element satisfies its constraints if it is not suffering from any of the above validity states.
Your sample does not clear the custom error if the form field is determined to be valid. As such, once the field is determined invalid, it stays so for the remainder of the session.
Moreover, you modify custom error only after the field has already been determined invalid. This means the form will still not be submitted even if you clear the message in the same handler.
A better way to accomplish your goal would be to monitor the field in the change event handler for the field and set the custom message there:
document.getElementById('UserName').addEventListener('change', function (ev) {
const input = ev.target;
if (input.validity.patternMismatch) {
input.setCustomValidity("Usernames cannot contain the # symbol");
} else {
input.setCustomValidity("");
}
}, false);
<form onsubmit="event.preventDefault(); alert('Form submitted');" action="post">
<!--pattern regex prohibits use of the # symbol-->
<input id="UserName" type="text" pattern="^((?!#).)*$" required />
<button type="submit">Submit</button>
</form>

Is checkbox validation with validate.js library broken?

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"
}
}
});
});

jquery validation how to hide error message only from specified hidden field

I got form with many fields and one is hidden... on validation
i use code below to set highlight messages
jQuery('.validatedForm').validate({
errorElement: "label",
errorClass: 'profile-error',
highlight: function(element) {
$(element).css("border-color","#d44");
if($('#checkedhour').val() == "") {
$('.table tbody td').css("border","solid 1px #d44");
}
},
unhighlight: function(element) {
$(element).css("border-color","#DFD7CA");
},
});
the problem is that error also appear on the field which is hidden...this hidden field...
What should i do to make error message only of hidden field does not appear but keep validation of this field?
<form>
<input type="text" required name="field1" />
<input type="hidden" required name="field2" />
<button type="submit">send</button>
</form>
When the both fields are empty the errors messages will appear after both fields as label elements.. i just want the label appear only after not hidden fields.
"Otherwise i still will be happiest when somebody find solution to make this via jquery validation plugin."
To control how messages are placed, use the plugin's errorPlacement option. Within a conditional checking if the element is hidden, you can eliminate its message.
errorPlacement: function(error, element) {
if ($(element).is(":hidden")) {
return false; // no message shown
} else {
error.insertAfter(element); // default message placement
}
}
Proof of Concept demo: http://jsfiddle.net/o5pns06x/
I find simple solution that make me happy. :-)
Even when we can't do this thru the jQuery.validate() i just forgot we can still use CSS!
Each created error element, in this case 'label' (as i set via errorElement), have also own attribute "for" which value based on "name" attribute from input field which is validated. So we can simple add to CSS requirment
<style type="text/css">
label[for=field2].profile-error {display: none !important;}
</style>
Now, only an error label with specified value of "for" attribute will not appear.
Otherwise i still will be happiest when somebody find solution to make this via jquery validation plugin. :))

Custom form validation function on element with html 5

For a custom image selection tool I would like to create form validation based on html 5 form validation.
For example my form consists of the following elements:
<form class="cms-form" action="">
<table width="800">
<tr>
<td width="30%">Name:</td>
<td><input type="text" name="name" class="cms-input-text" maxlength="127" /></td>
</tr>
<tr>
<td>Image:</td>
<td><textarea name="icon" class="cms-input-file" data-file-resource="images" data-options="{"min":1,"max":3}">/location-to-image.png</textarea></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Next"/></td>
</tr>
</table>
</form>
I have a Javascript that changes the textarea (.cms-input-file) into some html to add images and hides the original textarea.
It looks something like this:
<textarea name="icon" class="cms-input-file" data-file-resource="images" data-options="{"min":1,"max":3}" style="display: none;">/location-to-image.png</textarea>
<ul class="cms-input-file-list">
<li class="cms-input-file-item" data-image="/location-to-image.png">
<img src="/location-to-thumb.png" alt="" class="cms-input-file-item-thumbnail"/>
<span class="cms-input-file-item-title">location to image</span>
</li>
<li class="cms-input-file-add">Add</li>
</ul>
Since I have allot of existing forms using html5 form validation I would like to validate this element using the default form validation within html5 supported browsers, but using a hopefully existing event.
I'm looking for something like this:
$('.cms-input-file').on('customValidateFunction', function () {
var options = $(this).data('options');
if($(this).find('> li.cms-input-file-item').length < options.min)
{
return [false, 'Add more images.'];
}
if($(this).find('> li.cms-input-file-item').length > options.max)
{
return [false, 'Remove some images.'];
}
return true;
});
Does anyone know if something like this is possible using default html 5 events or how would I go about adding this event to the submit event? To actually trigger the default browser validation look and feel.
-- edit --
So far I have made an attempt to get this result using a div element which hides the original element. But now I need to add a pattern to the element to match according to my options. Is this possible?
Current progress: http://jsfiddle.net/jeffreydev/YyEVu/
If I understand correctly what you need, I think you can achieve what you are trying to do using the pattern attribute of any input element.
I've created a very simple form in jsfiddle illustrating this.
The idea is that you update the value of your input with whatever data you have in your model when adding or removing images. The example, just adds one letter f per icon. Then, you can create a regex to match the expected valid results. In the example, pattern="f{1,3}" means that to be valid, the content can be "f", "ff", or "fff" but nothing else, which means that it'll only accept from one to three files to be sent.
You would be using just default html5 form validation, but you may need a bit of tweaking to get it working.
However, if you try this way, you should keep a couple of things in mind:
As explained in the specs, the patttern is compiled as a JavaScript regular expression with the global, ignoreCase, and multiline flags disabled
Setting the disabled property of your input so that the user can't change it would take it out of the form, and thus it won't be validated
Applying certain styles as *display:none" to the input element can cause errors when the validation fails and the browser tries to gain focus on the element.
I hope you this helps
You can install a submit handler on the <form>, and dispatch a custom event from there.
That will look something like this:
$('form.cms-form').on('submit', function(evt) {
var frm = $(this);
var allElements = $(this.elements);
$('#errors').empty();
var errors = [];
var arg = {
reportValidationError : function( msg ) {
errors.push(msg);
},
form : this
};
console.log("all elements: ", allElements);
allElements.trigger('customValidate', [ arg ]);
if( errors.length !== 0 ) {
showValidationErrors(errors);
return false;
}
return true;
});
Then, you can "hook" the customValidate event, and install your own logic...
$('textarea[name=icon]').on('customValidate', function(evt, reporter) {
var options = $(this).data('options');
// ... your validation here ...
// for example:
var txt = $(this).val();
if( txt.length < options.min || txt.length > options.max ) {
reporter.reportValidationError('error: "icon" min/max exceeded!');
}
})
Here's an example at jsFiddle.
Edit
You can style the error reporting, and tweak the code, to look and behave however you want it to. Here's an example.
A very good jquery plugin to validate your forms is Mike Alsup one's.
You will find it here: http://jquery.malsup.com/form/
It is documented, ajax compatible.
It can do serialization for one field or for all fields inside the form, so it is a big advantage regarding your problem you could need to handle fields validation and error logic with your forms.
You could add the blockUI plugin of the same author to enhance user's experience, and don't have to manage double submission of the form when javascript is enabled.
http://jquery.malsup.com/block/
Answer from 2022: Yes, it is possible without jQuery etc.
Most browsers support Constraint Validation API (even IE 11 according to "caniuse")
The recommended practice is to listen to input/submit events and then set validity flags on the input-box.
<form>
<input type="text" required id="answer">
<input type="submit">
</form>
Validation JS:
const nameInput = document.querySelector("#answer");
const form = document.querySelector("form");
function validate(e) {
if (nameInput.value == "42") { //correct!
nameInput.setCustomValidity(""); // empty means "no error"
}
else {
nameInput.setCustomValidity("Wrong answer!"); //show error text
e.preventDefault(); //prevent form submit
}
}
nameInput.addEventListener("input", validate);
form.addEventListener("submit", validate);
The input event fires even when the value is changed programmatically
P.S. Codepen to play with: https://codepen.io/jitbit/pen/XWYZjXO

Categories