How do I remove jQuery validation from a form? - javascript

I'm using the jQuery validation plugin to validate a form, and I'd like to remove the validation and submit the form if a certain link is clicked.
I am submitting form with javascript like jQuery('form#listing').submit(), so I must remove the validation rules/function with javascript.
The problem is that I can't figure out how to do this. I've tried things like jQuery('form#listing').validate({}); and jQuery('form#listing').validate = null, but with no luck.

Trigger the DOM submit method to skip the validation:
$("#listing")[0].submit();

You can remove events of nodes with unbind:
jQuery('form#listing').unbind('submit'); // remove all submit handlers of the form
What you are probably looking for is that the validation plugin can also unassign itself from the submit event:
jQuery('form#listing').validate({
onsubmit : false
});
For both of these you should be able to follow up with a call to .submit() to submit the form:
jQuery('form#listing').unbind('submit').submit();

var form = $('#my_form_id').get(0);
$.removeData(form,'validator');
Is really working.

You can also use the public "rules" function in this way:
$('input, select, textarea').each(function() {
$(this).rules('remove');
});
That's what I'm using ;)

You can add a css class of cancel to an element (button, input) so that it skips the validation

I have found none of the other ways helpful if you wanted to toggle on/off your forms validation (e.g. different validation for payment types...)
What I have had to do (this is not an nice fix but it does work)
Set up your validation:
jQuery('#form').validate();
Disabling the form:
jQuery('#form').validate().currentForm = '';
Enabling the form again:
jQuery('#form').validate().currentForm = jQuery('#form')[0];

This seems to work for me now:
var form = $('#my_form_id').get(0);
$(form).removeData('validate');

$("#formName").validate().settings.ignore = "*";
Refer : https://github.com/jzaefferer/jquery-validation/issues/725

I recently upgraded to 1.5.5 of Jörn's validator script and the removeValidator function has been deprecated.
...
jQuery.extend(
jQuery.fn,
{
removeValidator: function(){
this.unbind();
jQuery.removeData(this[0], 'validator');
}
...

For all the tags input of form:
$('#myform').validate().settings.ignore = '.valid';
$('input').addClass('valid');
It works for me.

in 2022
the answers above do not work now for me,
So I've written this js method, this would remove the jquery validation correctly
function RemoveJQVRule(rulename, inputname) {
$(`[name="${inputname}"]`).rules('remove', rulename);
$(`[name="${inputname}"]`).removeAttr(`data-val-${rulename}`);
// message span element
$(`#${inputname.replace(/\./img, '_')}-error`).html("");
$(`[data-valmsg-for="${inputname}"]`).html("");
}
Examples:
RemoveJQVRule('required', 'Shipper.Contact.NationalId');
RemoveJQVRule('maxlength-max', 'SomeInputName');
RemoveJQVRule('regex', 'SomeInputName');
Note:-
if it does not work you may need to edit it a little bit (the css selectors)
Thanks

Related

How to not validate form on reset()?

I'm using
$('#myform')[0].reset();
to clear HTML form fields when a clear button is clicked. I'm also using jquery.validate.js. So when the above runs, it triggers form validation. All form fields with any validation then display their error messages. How do I prevent this?
I have tried this but it didn't do anything:
$('#myform').removeAttr("nonvalidate");
From the question you linked, the answer is what you want... All you have to do is capture the reset event and call v.resetForm().
var v = $('form').validate(); //etc etc whatever you have here, the important part is saving "v"
$('form').on('reset',function () {
v.resetForm();
});
See it working here: http://jsfiddle.net/uuu8jerr/

How to prevent submitting form based on text in an html element?

I have a form in that I have User Id availability check. So if Id is already in DB it will show a message "Id is already in use". In that case I have to avoid submitting the form. For that my html is as follow,
<div>
<label><strong>Teacher Id:</strong></label>
<input type="text" name="teacherId" id="teacherId" placeholder="Enter Teacher Id" >
</div><span class="status" id="status"></span>
Here span will have the text about availability,
The value to span comes form jquery post call,
$.post('<%=request.getContextPath()%>/controller/TeacherIdCheckController',
{'teacherId':teacherId},
function(data)
{
$('.status').html(data);
});
}
This works fine, to prevent submitting I wrote javascript function as,
function checkTeacherId(){
alert(" in checkTecherId()");
var status=$("#status").text();
alert(status);
if(status=="Id in use try another")
preventDefault();
else
return true;
}
Everything works fine but this javascript function is not working fine so I cant able to prevent submit in case of Id already exist in DB. So please anyone help me in this.
Just because you need to pass the event in the function's arg:
function checkTeacherId(e){ // <---pass the event here
.....
if(status=="Id in use try another")
e.preventDefault(); // and stop it here using dot notation
else
return true;
}
As per your comment you can pass the event to your function in your onclick handler:
onclick="checkTeacherId(event);"
Fiddle
Okay! As #Sanjeev tried commenting on best approach for this work then as you are using jQuery then you can just do this as per best approach like Unobrusive Javascript (removing this inliner scripts just like above posted):
function checkTeacherId(e){ // <---pass the event here
.....
if(status=="Id in use try another")
e.preventDefault(); // and stop it here using dot notation
else
return true;
}
$(function(){
$('#yourformid').on('submit', function(e){
checkTeacherId(e);
});
});
Use this approach if you want to externalize your scripts as declare the function in global scope and put your event handler in doc ready with submit event.
Updated fiddle with unobtrusive way.
Solution as per best practice for form validation:
You have implemented form submit via Submit button and not through js like document.getElementById("myForm").submit();
I don't see any point in using onclick handler on submit button for validation, use the native onsubmit Event Attribute, else you will keep on breaking submit flow.
onsubmit is made for validating form and stopping form submission if validation fails.
This will work sure shot in all browsers and is the correct approach for form validation
Example:
<form action="demo_form.asp" onsubmit="return checkTeacherId()">
function checkTeacherId(){
var status=$("#status").text();
if(status==="Id in use try another"){
return false
}
else{
return true;
}
}

jQuery removeAttr('type') doesn't work

My problem is very simple
$('#button').removeAttr('type');
triggers an error on firebug
type property can't be changed
I have 2 questions:
How to get around this?
Is there a reference with a list of properties that can't be changed?
Thanks
EDIT
What I want to do is:
Prevent the button from submitting the form.
Note: my button is included as a html template, the form code is not accessible form me.
Something like:
include 'form.php';
include 'buttons.php';
where I have control only on buttons.php
You can't change an input's type in IE (<9?) after it has been inserted into the DOM. jQuery raises an error for all browsers because of this.
From source:
set: function( elem, value ) {
// We can't allow the type property to be changed (since it causes problems in IE)
if ( rtype.test( elem.nodeName ) && elem.parentNode ) {
jQuery.error( "type property can't be changed" );
There are no other cases I know about (or jQuery knows about) and how to get around this depends a lot on what you are trying to do in the first place. Consider creating a new element with different type and using that for example.
Edit: To prevent the button from submitting a form, you can use:
$("#button").click(function(e){
e.preventDefault();
});
Or (credit Tim Down):
$("#button").prop("disabled", true);
To prevent form from being submitted through any means, you can use:
$("#form").submit(function(e){
e.preventDefault();
});
you can replace it:
$('#button').replaceWith('<input type="text" value="text"/>');
or use event.preventDefault()
Since you just want to disable the submit button:
If you are using jQuery < 1.6
do this:
$("#button").attr("disabled", 'disabled');
If you are using jQuery 1.6+:
$("#button").prop("disabled", true);
See this question: .prop() vs .attr() for references why.

Submit Form for select option.onClick

How would I submit a form when the user clicks an option using jQuery? I found one similar question using the datepicker text input but I'm not that familiar with jQuery so I can't seem to convert it to work for a select item.
On click of an <option>:
$('option').click(function ()
{
$(this).closest('form').submit();
});
On change of a <select> (this is probably the one you want):
$('select').change(function ()
{
$(this).closest('form').submit();
});
As #Guffa commented:
The click event on options doesn't work in all browsers. Safari for example does't trigger it.
...so you definitely want the second one.
The click event on options doesn't work in all browsers. Use the change event of the select element.
Example:
$('select').change(function(){
this.form.submit();
});
Note that the submit event of the form is not triggered when you call the submit method to post the form.
A small correction of these answers:
$(document).ready(function() {
$('#some_link').click(function() {
$('#form_id').submit();
});
});
$('select').change(function() {
$('form').submit();
});
$('#option').click(function () {
// form validation and such then
$('form').submit();
})
This is the easiest way i can think of
UPDATE:
for specific form, you can use its name or id, it really depends on how your html looks like
$('form[name="formnamehere"]').submit();
I found the other answers helpful but to truly achieve what I needed of individual actions based on each option click this was exactly what I needed:
jquery: option plus class and click

Change form values after submit button pressed

[EDIT] After a lot of digging around, I found out that the problem was in how I integrated the CKEditor into my page. The simple and obvious way does work in this case, as laid out in the accepted answer.
Hi,
I need to change the values of a form, after the submit button has been pressed, but before the actual submission has taken place.
I've tried hooking into the "submit" event of the form, and changing the text field values there manually, but it looks like that doesn't actually change the values submitted.
Any ideas?
I'm curious about your statement that the submit handler didn't work for you. It does for me. I've used it for years to fill in hidden fields before sending forms in; should work for other form fields as well.
Example (live copy):
HTML:
<form id='theForm'
action='http://www.google.com/search'
method='GET' target='_new'>
<label>Search for:
<input type='text' name='q' id='txtSearch'></label>
<input type='submit' id='btnSearch' value='Search'>
JavaScript:
window.onload = function() {
document.getElementById('theForm').onsubmit = function() {
var txt = document.getElementById('txtSearch');
txt.value = "updated " + txt.value;
};
};​
Tested and working on IE6 and IE7 on Windows, and Chrome, Firefox, and Opera on Linux.
Update: Based on your comment below, you're using jQuery. Works fine using jQuery for everything as well:
$('#theForm').submit(function() {
var txt = $('#txtSearch');
txt.val("updated " + txt.val());
});
Live example Tested and working on the same set of browsers. This version uses a more open search rather than an id, and also still works.
You need to prevent the default submit action and then resubmit the form yourself manually:
$('form').submit(function(e) {
e.preventDefault();
// do your processing
this.submit(); // call the submit function on the element rather than
// the jQuery selection to avoid an infinite loop
});
Did you try adding function on click JavaScript event on the submit button and changing the values?
It may work because client script will execute first
You could use formData event.
The formdata event fires after the entry list representing the form's
data is constructed. This happens when the form is submitted, but can
also be triggered by the invocation of a FormData() constructor.
formElem.addEventListener('formdata', (e) => {
const formData = e.formData;
//no need change document.getElementById().value = "";
formData.set('field1', 'foo');
formData.set('field2', 'bar');
//updated formData
});

Categories