The form is not submitted once submitted with invalid input? - javascript

I have a javascript function like this:
function validateInput() {
var search_text = document.getElementById('search_text').value;
var size = document.getElementById('size').value;
var submitButton = document.getElementById('sb_search');
document.getElementById('sb_search').disabled=false;
var filter = /^[\x20-\x7E]*$/;
if (filter.test(search_text) && search_text.length>0){
return true;
}
else{
submitButton.setAttribute('disabled');
}
}
Once I press the submit button without value and without satisfying the regex the button is not submitted after that.

you are disabling the submit button when the input is zero or not as per the regex !
also you are not returning true which is holding it from submition !

put a return false in the else condition.
instead of document.getElementById('sb_search').disabled=false; try
document.getElementById('sb_search').removeAttribute('disabled')

Put return false in else statement
function validateInput() {
var search_text = document.getElementById('search_text').value;
var size = document.getElementById('size').value;
var submitButton = document.getElementById('sb_search');
document.getElementById('sb_search').disabled=false;
var filter = /^[\x20-\x7E]*$/;
if (filter.test(search_text) && search_text.length>0){
return true;
}
else{
submitButton.setAttribute('disabled');
return false;
}
}

That's because search_text.length == 0 and thus you fall into the else and disable the submit button

Related

Conditional jQuery validation based on custom attribute

I'd like to enable/disable buttons on key up change conditionally based on a custom data attribute that matches between an input and a button. I've solved it with just one input, but it seems that when I add another one in the mix, the buttons don't seem to enable.
Furthermore, I have a hunch that it's because of .each() but I can't put my finger on it.
Here's the CodePen I've tried and failed on
var validation = $('[data-validation]');
var validate;
validation.on("change keyup", function (e) {
let validated = true;
validation.each(function () {
let value = this.value;
validate = $(this).data('validation');
if (value && value.trim() != "") {
validated = false;
} else {
validated = true;
return false;
}
});
if (validated) {
$('[data-validator=' + validate + ']').prop("disabled", true);
} else {
$('[data-validator=' + validate + ']').prop("disabled", false);
}
});
The key here is to only run your validation code for the input that was changed. As opposed to what you have, which is to run for all inputs.
To get the input that actually changed, you can utilize the .target property of the event object passed to the event handler.
Alternatively, if you remove the validation.each() entirely, it also works. That is because jQuery sets the value of this to be the DOM element (not a jQuery-wrapped element) that actually triggered the event.
var validation = $("[data-validation]");
var validate;
validation.on("change keyup", function (e) {
let validated = true;
let value = this.value;
validate = $(this).data("validation");
if (value && value.trim() != "") {
validated = false;
} else {
validated = true;
return false;
}
if (validated) {
$("[data-validator=" + validate + "]").prop("disabled", true);
} else {
$("[data-validator=" + validate + "]").prop("disabled", false);
}
});

Disable carriage return in onload javascript

I have a web form that uses a check box function. Users are bypassing the consent checkbox, however, as you can just hit a hard return after entering your creds. Trying to get something that will restrict the carriage return bypassing the check box...
function consentCheckBoxChecked() {
debugger;
var submitBtn = document.getElementById("submitButton");
var checkBox = document.getElementById("consentCheckBox");
if (checkBox.checked === true) {
submitBtn.classList.remove("is-disabled");
} else {
submitBtn.classList.add("is-disabled");
}
}
I think you should try something like this, in addition to applying required classes
<body onload="OnLoadEvent();">
</body>
Javascript:
function OnLoadEvent() {
document.getElementById("submitButton").Enabled = false;
}
function consentCheckBoxChecked()
{
var submitBtn = document.getElementById("submitButton");
var checkBox = document.getElementById("consentCheckBox");
if (checkBox.checked) {
submitBtn.Enabled = true;
} else {
submitBtn.Enabled = false;
}
}

Wait for the return of the loop on form submit

I have the code below, the form is needed to be validated before it can submit the form.
But the problem is, the form continues to submit without validating.
<form action='#' method='post' onsubmit='return validate();'>
function validate()
{
$('form').find(':input:not(:submit,:hidden), select, textarea').each(function(e)
{
$(this).removeClass('redBox');
var rq = $(this).attr('requiredz');
if(rq != undefined)
{
if($(this).val().trim() == '')
{
$(this).addClass('redBox');
$("#errorMsg").html('Red boxes cannont be left empty!');
return false;
}
}
});
});
How to handle the return of a loop?
Dont submit the form once encountered return false on the loop.
try this:
function validate()
{
var passes = true;
$('form').find(':input:not(:submit,:hidden), select, textarea').each(function(e)
{
$(this).removeClass('redBox');
var rq = $(this).attr('requiredz');
if(rq != undefined)
{
if($(this).val().trim() == '')
{
$(this).addClass('redBox');
$("#errorMsg").html('Red boxes cannont be left empty!');
passes = false;
}
}
});
return passes;
});
Do not use return.
$('#my-form').on('submit', function(event){
if (validate() === false) {
event.preventDefault(); // like return false;
}
});
For more information see jQuery submit docs.
Each function has it's own returned value, the default returned value is an undefined value. You should check the length of the invalid elements after the each loop and return a proper value, since you are using jQuery I'd suggest:
$('form').on('submit', function (event)
{
var $invalid = $(this)
.find(':input:not(:submit,:hidden), select, textarea')
.removeClass('redBox')
.addClass(function () {
return this.getAttribute('requiredz')
&& $.trim(this.value) === ''
? 'redBox'
: null;
}).filter('.redBox');
if ($invalid.length)
{
$("#errorMsg").html('Red boxes cannont be left empty!');
return false;
}
});

once a Boolean variable false don't return true in other cases

I've got the following code
$(function(){
var isValid = function(test_obj, element){
if(!test_obj.val().length > 0){
element.addClass('has-error');
return false;
}else{
element.removeClass('has-error');
return true;
}
};
$('#rta_parties_form').submit(function(event){
var formSubmit;
formSubmit = isValid($('#rta_cl_fn'), $('#div_cl_fn'));
formSubmit = isValid($('#rta_cl_ln'), $('#div_cl_ln'));
formSubmit = isValid($('#rta_cl_ph'), $('#div_cl_ph'));
formSubmit = isValid($('#rta_cl_mob'), $('#div_cl_mob'));
if(!formSubmit){
event.preventDefault();
}else{
alert('formSubmit successfully');
}
});
});
As you can see I'm using formSubmit = isValidToggle($('#rta_cl_fn'), $('#div_cl_fn')); on four different occasions. My issue: let's say in first 3 instances, it returns false but on the fourth instance, it returns true, then it will submit the form successfully?
Is there any way to check if any of those instances return false or set all the instances to false so form should not be submitted?
I know I can use nested if statements, but then, what is the point of using a function? I wanted to avoid using multiple if statements in my code. That's why I wrote the function; otherwise, I could have just used the function code in my actual code and set formSubmit to false.
Any ideas?
You can use this, more maintainable
var tmp = [$('#div_cl_fn'), $('#div_cl_ln'), $('#div_cl_ph'), $('#div_cl_mob')];
var i = -1;
while (++i < tmp.length)
{
if (!isValidToggle($('#rta_cl_mob'), tmp[i]))
{
event.preventDefault();
break;
}
}
If you want to add something to check, just add an entry into the array
Or
for (var i in toCheck = [$('#div_cl_fn'),
$('#div_cl_ln'),
$('#div_cl_ph'),
$('#div_cl_mob')])
{
if (!isValidToggle($('#rta_cl_mob'), toCheck[i]))
{
event.preventDefault();
break;
}
}
You should use it like
formSubmit = isValidToggle($('#rta_cl_fn'), $('#div_cl_fn'));
formSubmit = formSubmit && isValidToggle($('#rta_cl_ln'), $('#div_cl_ln'));
formSubmit = formSubmit && isValidToggle($('#rta_cl_ph'), $('#div_cl_ph'));
formSubmit = formSubmit && isValidToggle($('#rta_cl_mob'), $('#div_cl_mob'));
You can do the following
var formSubmit1, formSubmit2, formSubmit3, formSubmit4;
formSubmit1 = isValidToggle($('#rta_cl_fn'), $('#div_cl_fn'));
formSubmit2 = isValidToggle($('#rta_cl_ln'), $('#div_cl_ln'));
formSubmit3 = isValidToggle($('#rta_cl_ph'), $('#div_cl_ph'));
formSubmit4 = isValidToggle($('#rta_cl_mob'), $('#div_cl_mob'));
if(!formSubmit1 || !formSubmit2 || !formSubmit3 || !formSubmit4){
event.preventDefault();
}else{
alert('formSubmit successfully');
}
Try this...
You can do it in single line...
formSubmit = isValidToggle($('#rta_cl_fn'), $('#div_cl_fn')) && isValidToggle($('#rta_cl_ln'), $('#div_cl_ln')) && isValidToggle($('#rta_cl_ph'), $('#div_cl_ph')) && isValidToggle($('#rta_cl_mob'), $('#div_cl_mob'))
in this, it will check first one condition and if it is true then It will check further condition otherwise it will take you out.
All validation will be executed.
$(function(){
var formValid,
isValid = function(test_obj, element){
if(!test_obj.val().length > 0){
element.addClass('has-error');
}else{
element.removeClass('has-error');
formValid = true;
}
};
$('#rta_parties_form').submit(function(event){
var formSubmit;
formValid = false;
isValidToggle($('#rta_cl_fn'), $('#div_cl_fn'));
isValidToggle($('#rta_cl_ln'), $('#div_cl_ln'));
isValidToggle($('#rta_cl_ph'), $('#div_cl_ph'));
isValidToggle($('#rta_cl_mob'), $('#div_cl_mob'));
if(!formValid){
event.preventDefault();
}else{
alert('formSubmit successfully');
}
});
});
Thank you very much everyone but I got what I wanted I'm putting this code here for if anyone else wants to get use of the code in future...
$(function(){
//below is one way using function
var isValid = function(test_obj, element){
if(!test_obj.val().length > 0){
element.addClass('has-error');
return false;
}else{
element.removeClass('has-error');
return true;
}
};
$('#rta_parties_form').submit(function(event){
var formSubmit = [];
formSubmit[0] = isValid($('#rta_cl_fn'), $('#div_cl_fn'));
formSubmit[1] = isValid($('#rta_cl_ln'), $('#div_cl_ln'));
formSubmit[2] = isValid($('#rta_cl_ph'), $('#div_cl_ph'));
formSubmit[3] = isValid($('#rta_cl_mob'), $('#div_cl_mob'));
var validForm = true;
for (var i = 0; i < formSubmit.length; i++) {
if(formSubmit[i] == false){
validForm = false;
}
};
if(!validForm){
event.preventDefault();
}else{
alert('formSubmit successfully');
}
});
});
This works fine for me, thanks to everyone one more time for your help..

jquery - validation plugin

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

Categories