I implemented some custom validation logic with JQuery and Unobtrusive validation with help of the following post:
Manually set unobtrusive validation error on a textbox
To save you time reading through that post here is the simple javascript that forces a validation message to be displayed if something fails:
On my textbox .blur():
var errorArray = {};
errorArray["Slug"] = 'Some error message for the Slug text box';
$('#SomeFormId').validate().showErrors(errorArray);
Works great.
My problem is while the failed validation message is displayed, when submit is clicked the form submits just fine.
How can I implement custom validation with code above and prevent the form from being submitted when the message is displayed ? I tired doing something like $('#SomeFormId').valid = false; but it didn't work.
Thank you.
Using $('#SomeFormId') will not work because when you do:
$('#SomeFormId').valid = false;
and then when you access it in your form submit handler again using (what I assume):
var form = $('#SomeFormId'); // or $(this)
if (form.valid) {
//
}
You're essentially creating two different objects, even though they're referring to the same DOM element. So setting valid = true in one will not update it in the second.
The code you gave is very barebones though, so I'm assuming that your validation is separate from your submit handler (since it's in blur anyway), so what you can do is utilize something like .data() or a flag (just make sure that it's in context).
// on blur
$('#SomeFormId').data('isvalid', false); // invalid
// on submit
var isvalid = $('#SomeFormId').data('isvalid');
if (!isvalid) {
// invalid form
ev.preventDefault();
}
EDIT
The jQuery Event object
When you bind a function as an event handler in jQuery, one of the things that jQuery does silently for you is it "creates" a normalized Event object for you. This will contain information about the event you can use in the handler, and also allows you to control the behavior of the event in some ways.
// setting a submit event on my form
// | whatever you put here
// V is the event object.
$('#SomeFormId').on('submit', function (ev) {
// preventing the default action
// : in a form, this prevents the submit
ev.preventDefault();
});
To check if the form is valid, you can use something like this:
var form = $("#SomeFormId");
form.submit(function(event) {
if(form.valid() == false) event.preventDefault();
}
Edited to add a bit more to it, this will take care of your submission/prevention, now you just add in your validation calls.
Related
I have a form defined in HTML which can be submitted with a submit button.
I also have a jquery handler in which there is a logger on a non existing object.
$("#myform").submit(function() {
console.log(nosuchobject);
return false;
});
With the logger in place, the form is submitted and the browser changes page. But without the logger, the form is not submitted.
My guess is that when there is an error in the logger the returned value is not false. But is it true ? And how come an error allows for a form to be submitted anyway ?
In your logger code you have print a variable instead of string. just update you code with following
$("#myform").submit(function() {
console.log('nosuchobject');
return false;
});
Use preventDefault for preventing form submition:
$("#myform").submit(function(e) {
e.preventDefault();
});
if you get a js error in the submit function the code after the error won't be executed what means that it does not return a false. You can prevent the form submission at the start of your function like this:
$("#myform").submit(function(event) {
event.preventDefault();
// it does not matter if there is an error now.
console.log(nosuchobject);
});
You should still write your code so it runs without errors.
I am creating a Polymer application in which search button has several inputs from input boxes. And from that collection of that input boxes search button should perform search operation considering all inputs.
following is the image for scenario -
{ iron-form } is one of the option for that but I want something new and with ease.
Please help me.
I don't have your HTML, so I'm just going to be using elements which I think you will have within your document.
Test this out:
Pure JavaScript:
var form = document.getElementsByTagName("form")[0];
form.onsubmit = function(){ // on form submit
var input = document.querySelectorAll("input");
for(var i = 0; i < input.length; i++){ // loop through each input on the page
alert(input[i].value); // will alert the value of the input
}
return false; // stop form from posting
}
jQuery:
$("form").submit(function(){ // on form submit
$("input").each(function(){ // foreach input
var value = $(this).val(); // grab its value
alert(value); // output its value
});
return false; // prevent form from posting
});
So when the form submits, it will iterate through each input, and output each value through an alert.
Hope this helps! :-)
Since you tagged this with the Polymer tag there is also a Polymer iron-form specific way to handle this. #Caelan is correct but this will not work with Polymer elements (or custom elements). Examples of these elements are paper-input andpaper-checkbox. See Paper Elements for a list of all customized inputs.
<iron-form></iron-form comes with a property method serialize and validate which you can use to collect all inputs (including custom elements) in one function call.
See iron-form.serialize documentation
var form = document.querySelector('iron-form')
form.onsubmit = function(event) {
event.preventDefault();
var data = form.serialize()
// Do something with data
// return false; // could use instead of event.preventDefault()
}
See preventDefault vs return false thread on stack overflow both will work in your case since you do not care about bubbling events.
to be more specific, when we submit our empty form which should have information in it should submit an alert saying "please enter a value" it does this but then after selecting okay on the alert it still sends the email on submit. I want it that if there's an error they must fulfill the requirements of the form before the email on submit can be sent. the code is:
this checks to see if there's any values in the fields
function notEmpty(elem, helperMsg) {
if (elem.value.length >= 2) {
return true;
alert(helperMsg);
elem.focus();
return false;
}
return true;
}
the start of the form:
<form method="get" onsubmit="notEmpty();" action="http://www.censoredgaming.co.uk/cgi-bin/mailer.pl">
the submit button:
<input type="submit" name='Submit' value="Send" onClick='notEmpty();'>
any insight to our problem is most welcome!
There are several reasons this will fail.
The first one you will encounter is, because you don't pass any arguments when you call notEmpty, the variable elem will be undefined. When you try to access a property (value) on it, an exception will be thrown and the function will stop.
Let's take this from the top.
First, we'll use a more modern method to apply the event handlers.
Provide a means to identify the form you want to deal with. An id attribute is a good general choice (but use a more meaningful name then I am):
<form id="myForm"
method="get"
action="http://www.censoredgaming.co.uk/cgi-bin/mailer.pl">
Next, get a reference to the form in the DOM and add an event listener to it:
document.getElementById('myForm').addEventListener('submit', notEmpty);
Note that you have to do this after the form has been added to the DOM. The easiest way to achieve this is to place your <script> after the </form> (just before </body> is a popular place). You can also use an event handler that fires when the DOM is ready or the document has loaded.
Old versions of Internet Explorer don't support addEventListerner, if you want to support them see the MDN documentation which has a compatibility routine.
Next, update the notEmpty function. Since it is an event handler, it will get one argument - an event object. It will also be called in the context of the element to which is is bound (the form).
function notEmpty(event) {
var aForm = this;
}
You want to check that some element has a value of a certain length, but there is no sign of such an element in your question. Let's work with this example:
<label> Some data <input name="example"></label>
You can reference the element through the form's elements collection:
function notEmpty(event) {
var aForm = this;
var input = aForm.elements.example;
}
Now you can add your test:
function notEmpty(event) {
var aForm = this;
var input = aForm.elements.example;
if (input.length >= 2) {
} else {
}
}
If you don't want the form to submit, then prevent the default action on the event:
function notEmpty(event) {
var aForm = this;
var input = aForm.elements.example;
if (input.length >= 2) {
// At least two characters, all is well
} else {
alert("An error");
input.focus();
event.preventDefault();
}
}
Your first return true should be removed :P
I have a javascript method for validating a form. But under a certain condition, control should stop the script and allow the user to save a form.
Will 'return' keyword work here?
if(matchSearch==null)
{
alert('Mismatch in Subsidiary and Year. Stopping script to allow form submission.');
return;
}
The idea is, if matchSearch == null, script should stop and user should be allowed to save the form.
If you're saying that you have a function that has been assigned as an onsubmit handler, i.e., the function is called when the user tries to submit, then return; as in your example will stop execution of the function and allow the submission to continue.
Any return statement will exit from the current function. The value that you return might matter depending on how the submit handler was assigned: return false; from an inline onsubmit="" attribute will prevent the form from being submitted. Your return; statement without a value implicitly returns undefined which won't prevent submission.
If you want to check form fields before the the form is submitted, the (submit) handler function that does the check should return false. That way the submit is cancelled, and the form stays on the screen, retaining the values a user already typed. Something like:
function checkValues(){
//check values
if (/*return value of the check is wrong*/){
// save form functionality
return false
}
// check ok
return true;
}
yourform.onsubmit = checkValues;
See this jsfiddle for a very basic example
Alternatively you can also program a 'listener' function that checks the contents of every form field periodically. You can find an example in this jsfiddle. It is designed to show a submit button only if all fields have valid values.
Using return false; will stop the execution of the script.
I'm trying to use html5 validation and ajax.
The method checkValidity doesn't solve my problem, because it doesn't show the message error in the UI.
I need to launch the browser validation (and show error messages) using js. To do it I found that I have to submit the form and prevent the event. i.e:
$('form#x').submit(function(e){
e.preventDefault();
// ajax code
});
This works ok and the ajax code is only executed if the all the form fileds are valid. However, I realized that once the form is valid, the ajax code is executed as many times as the submit button was clicked. WTF?
I could solve that issue by using a global flag:
flah = 0;
$form.submit(function(e){
e.preventDefault();
if(flag) return;
flag = 1;
//send x ajax
// in ajax callback >> flag = 0
});
Is there any other way to launch the validation without submit?
Is the event-trigger problem a browser bug or is it a problem in my code?
Thanks
try this:
$('form#x').submit(function(e){
e.preventDefault();
if(!this.checkValidity()){
return false;
}
// ajax code
});