I make a simple validation plugin, that return false if input fail validation, the problem is this plugin only works with one input at a time. I want it to work with all input at the same time.
the code
$.fn.validate = function(options){
var defaults = {
required:true,
minChar:0,
maxChar:0
},
o = $.extend({},defaults, options);
this.each(function(){
var $this=$(this);
var val = $this.val();
if(o.required==true && val==''){
return false;
}else if(o.minChar>0 && val.length < o.minChar ){
return false;
}else if(o.maxChar>0 && val.length >o.maxChar ){
return false;
}
else{return true;}
});
}
call
if(!$('#name').validate()){
$('.name_inline_error').text('require name');
return false;// return false to stop ajax form submiting
}
if(!$('#email').validate()){
$('.email_inline_error').text('require email');
return false;// return false to stop ajax form submiting
}
What the code will do is, if two inputs are empty, the plugin will only tell the name input error, only when the name input was validated, the form will tell the email input error. While, I want to see two errors at the same time.
When you return, you are skipping the rest of your function. Try something like this:
valid = true;
if(!$('#name').validate()){
$('.name_inline_error').text('require name');
valid = false;
}
if(!$('#email').validate()){
$('.email_inline_error').text('require email');
valid = false;
}
return valid;
(+1 to Matt Ball's comment, however -- rolling your own on this one is going to take a long time.)
Related
Before posting this question I tried StackOverflow but did not find the answer.
So, the question is, I have an array with some values(suppose 4,6,7,8,10 etc). I used the .each function of jquery to prompt the alert message. but my code gives me an alert message, focus to the desired input box and submit the form and does not "return false".
I want it to return false after focusing.
$(document).on('keypress','#create_invoice',function(){
$.each(newArr, function( i, l ){
//alert( "Index #" + i + ": " + l );
if($.trim($('#item_name'+l).val()).length == 0)
{
alert("Please Enter Item Name");
$('#item_name'+l).focus();
// return false; //if use this not work and submit form
}
//return false; //if use this not work and submit form
});
//return false; if i use this then submit() not work
$('#invoice_form').submit();
});
The return false works, but I think what you want is to stop the form from submitting if you returned false. That behavior can be done with this;
First put an e in the function argument then use e.preventDefault();.
What's next is make a variable that would be a boolean which would determine if you can allow the form to submit. In the code below, I used var allowSubmit.
Try the code below.
$(document).on('keypress', '#create_invoice', function(e) {
e.preventDefault();
// boolean variable
var allowSubmit = true;
$.each(newArr, function(i, l) {
if ($.trim($('#item_name' + l).val()).length == 0) {
alert("Please Enter Item Name");
$('#item_name' + l).focus();
// set the variable to false
allowSubmit = false;
return false;
}
});
// check if we could submit the form
if (allowSubmit) {
$('#invoice_form').submit();
}
});
I'm having an issue with my validation process. I'm not using a standard "submit" button, rather I have <span class="button" id="print">Print</span> and jQuery listens for a click. This is the validation code I have when that "button" is clicked:
var validation = "";
function validate() {
$("#servDetails").find("input").each(function () {
if ($(this).prop("required") && $(this).val() == "") {
validation = false;
}
else {
validation = true;
}
});
$("#checklist").find("input[required]").each(function () {
if ($(this).prop("required") && $(this).val() == "") {
validation = false;
}
else {
validation = true;
}
});
}
$("#print").on("click", function() {
validate();
if (validation == false) {
alert("Please fill out all required inputs!");
return false;
}
else {
window.print();
}
});
If I click the button without filling anything out (all items blank), I get my alert as expected.
If I fill out all of the required elements, it pulls up the print dialouge as expected.
However, if I leave some of the boxes blank while others are correctly filled, it still goes to print instead of giving me the alert like I need. Any thoughts?
The code have to be rewritten, or better replace it with any validation plug-in.
But in your case, I suppose, you just forgot to return, in case you found some not filled field. So if you have any filled input it override your validation variable.
The simplest solution is to remove
else {validation = true;} code blocks, and add
validation = true;
at the beggining of the function.
I am validating a form that's working fine but i don't know why the form not submit after all validations.
Here is validation code:
$('#coupon_options').submit(function(e){
e.preventDefault();
var name = $('input[name="coupon_name"]'),
code = $('input[name="coupon_code"]'),
value = $('input[name="coupon_value"]'),
valid = $('input[name="coupon_valid"]'),
status = true;
if( $.trim(name.val()) == "" ){
name.css('border-color', '#ff0000');
status = false;
} else { name.removeAttr('style'); }
if( $.trim(code.val()) == "" ){
code.css('border-color', '#ff0000');
status = false;
} else { code.removeAttr('style'); }
if( $.trim(value.val()) == "" ){
value.css('border-color', '#ff0000');
status = false;
} else { value.removeAttr('style'); }
if( $.trim(valid.val()) == "" ){
valid.css('border-color', '#ff0000');
status = false;
} else { valid.removeAttr('style'); }
if( status == true ){ return status; }
else { return false; }
});
As i know to stop the refresh after submit event i have used the return false but i am not sure return true works here or not?
I don't want to use Ajax, just want to submit after validation.
Is there something wrong in this code??
remove:
e.preventDefault();
it stopping the default action to occur even you return true;.
For example:
Prevent a submit button from submitting a form
Prevent a link from following the URL
e.preventDefault(); is the issue, but you should note that it's never a good sign when you have multiple functions that basically perform the same action for different elements, you can simplify your code to this:
$('#coupon_options').submit(function(e){
var status = true;
$('input[name="coupon_name"],input[name="coupon_code"],input[name="coupon_value"],input[name="coupon_valid"]').each(function(){
if($.trim($(this).val()) == ""){
$(this).css('border-color', '#ff0000');
status = false;
} else {
$(this).removeAttr('style');
}
});
return status;
});
And you could even use $('input[name^="coupon_"]') to select all inputs that start with that prefix.
I am trying to validate input on an HTML form. I am trying to use one script to validate various forms that have several similar elements. All in all there are about 15 different fields but I am only putting 3. Below works on the form that has all of the elements but fails on any form that does not have a specific field.
if (form.name.value == ""){ // Check if blank
alert( "\nEnter a name." );
form.name.focus();
return false; // Stop the form processing.
}
else if ( !/^\w{10}$/.test( form.phone.value )) { // Check for phone
form.name.style.border=""
alert( "\nEnter a valid phone number!" );
form.phone.focus();
return false; // Stop the form processing.
}
else{
return true; // Submit!
Since this only works if all are present what i want to do is validate only if it exists. I have tried nesting the validation under a statement that should check for the element before trying to validate it and if the element doesn't exist it should move on to the next.
if (document.forms[0].name){ //does field exist?
if (form.name.value === ""){
alert( "\nEnter a name." );
form.name.focus();
return false; // Stop the form processing.
}
else{
return true; //field ok move on.
}
}
else if (document.forms[0].phone){
if ( !/^\w{10}$/.test( form.phone.value )) { user
form.name.style.border=""
alert( "\nEnter a valid phone number!" );
form.phone.focus();
return false; // Stop the form processing.
}
else{
return true; //field ok move on.
}
}
else{
return true; // Submit!
}
Any help help would be appreciated!
At present you are checking that (document.forms[0].name) is available and then if this is dead it check if (document.forms[0].phone) is true and then...... and then if none are true it resorts to the 'else' and returns are true. The use of if else means that you only bother with anything after if this part has failed.
You could try.
if (document.forms[0].name) {
if ( !/^\w{10}$/.test( form.phone.value )) { user
form.name.style.border=""
alert( "\nEnter a valid phone number!" );
form.phone.focus();
return false; // Stop the form processing.
}
}
if (document.forms[0].blah) {
do stuff...
if fail
return false;
}
return true;
As the function is going to return as true anyway, you don't need to state return true anywhere else (also this will stop the process as it has returned and stopped). The only reason to stop the process if things have gone wrong.. hence return false;
If you just need to validate a form, you don't need to write javascript nowadays. You can use html5 forms. Even if you have to support browser without this feature, you can put the webshims lib at your page to enable it.
I have many forms generated dynamically via PHP. I'm trying to verify that all the fields on the one form that's going to be submitted are filled. I'm just starting to JQuery, so I'm sorry if the answer is stupidly easy.
I tried this:
$('.myform').submit(function(){
var flag = true;
$('.myform input').each(function() {
if($(this).val() === ''){
flag = false;
return false;
}
});
return flag;
});
But when in the second form, it goes and checks the first one (which should be empty because you're not filling that one...)
Thanks in advance!
$('.myform').submit(function(){
var flag = true;
// use $(this) below which is the form has submit event fired.
$(this).find('input').each(function() {
if($(this).val() === ''){
flag = false;
return false;
}
});
return flag;
});
Or you could simplify your code by:
$('.myform').submit(function() {
return $(this).find('input').filter(function() {
return $.trim($(this).val()) !== '';
}).length == 0;
});