Form validation does not happen - javascript

My form has some fields that are mandatory and I have marked them with class="required". I am writing the below jquery to validate this form, but it doesn't happen. I think either I am messing with calling the two functions or I am not getting the proper element through $(this).
<script type="text/javascript">
function validatemyForm() {
$('.required').each(function() {
if($(this).val() == "" || $(this).replace(/\s/g, '').length == 0)
{
$(this).insertAfter('<span>This is a Required Filed</span>');
return false;
}
else {
$(this).remove();
}
})
return true;
}
</script>
I am calling the form, from the onsubmit event handler <form id="myform" onsubmit ="return validatemyForm();">. Am I incorrectly using each and this of jQuery?

A number of things:
You can use replace on a String, whilst you use it on a jQuery object. There is no $(this).replace. If you want to check for whitespace, you need the value, i.e. $(this).val().replace.
You use $(this).insertAfter which means that the input element is inserted after the span. $(this).remove simply removes the input element which isn't what you're after either I think.
You return false in the each(), but this doesn't return that value in the validatemyForm function. In that function, you always return true.
I changed it to this to get it working: http://jsfiddle.net/DaDQT/6/.

Your function validatemyForm always returns true. The return false you have in there is inside the function passed to each. validatemyFormdoes not stop at this point.
The following should work as you expect it (untested code):
<script type="text/javascript">
function validatemyForm() {
var ok = true;
$('.required').each(function() {
if($(this).val() == "" || $(this).val().replace(/\s/g, '').length == 0)
{
$(this).insertAfter('<span>This is a Required Field</span>');
ok = false;
}
else {
$(this).remove();
}
})
return ok;
}
</script>

Related

my function to validate a checkbox in a form not working with jquery

Check term function not working to validate checkbox in HTML form with jQuery...
Here is my code, click the checkbox and click outside to trigger the validation:
function check_term() {
var term = $("#term").val()
if (term.checked = true) {
$("term_error_message").hide();
} else {
$("term_error_message").html("Please accept our terms and conditions");
$("term_error_message").show();
error_term = true;
}
console.log("error_term is " + error_term);
}
$("#term_error_message").hide()
var error_term = false;
$("#term").focusout(function() {
check_term()
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input id="term" type="checkbox"> I Accept the terms and conditions
</div>
<div id="term_error_message"></div>
In your if statement, you are assigning the value true to term.checked. You should use the === comparison operator instead of =.
Like this: if (term.checked === true) {
I don't know if that will solve all your problems, but it's a start.
Visit this link for more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Comparison
Consider the following.
function check_term() {
var term = $("#term");
if (term.prop("checked")) {
$("#term_error_message").hide();
} else {
$("#term_error_message").html("Please accept our terms and conditions");
$("#term_error_message").show();
}
return term.prop("checked");
}
var error_term = false;
$("#term_error_message").hide()
$("#term").blur(function() {
error_term = check_term();
});
Assigning the Value of #term would give you a String, not an Object. So, term.checked would be undefined. You will want to check the Property of a checkbox to see if it checked or not. .prop(), as a Getter will return true or false for the property checked.
You also need to use the proper Selector in your jQuery. I think you also mean the blur callback versus focusout.
You can also use .is() like so.
function check_term() {
if ($("#term").is(":checked")) {
$("#term_error_message").hide();
} else {
$("#term_error_message").html("Please accept our terms and conditions");
$("#term_error_message").show();
}
return $("#term").is(":checked");
}
This is also going to return true or false.

Check to make sure all fields are filled Jquery

I'm trying to make an easy validator in jquery for my input fields.
Currently i got the following:
function checkInputs(){
var isValid = true;
$('.input-required').each(function() {
if($(this).val() === ''){
isValid = false;
return false;
}
});
return isValid;
}
And then i got a button right that is this:
$('#confirm').click(function () {
alert(checkInputs());
});
But this always returns true even if the input is empty.
Also after this works am going to make to where if all inputs are filled in, a button will be enabled to click on.
edited it so it has a selector now, still getting always true.
Thanks in advance
Try use the filter attribute to get the inputs that has a required attribute.
$('input').filter('[required]')
Added code to check if inputs are filled and enable or disable button. Note if we use this, there aint much point of the $('#confirm').click(function()); function since this button will only be enabled when the inputs are filled.
function checkInputs() {
var isValid = true;
$('input').filter('[required]').each(function() {
if ($(this).val() === '') {
$('#confirm').prop('disabled', true)
isValid = false;
return false;
}
});
if(isValid) {$('#confirm').prop('disabled', false)}
return isValid;
}
$('#confirm').click(function() {
alert(checkInputs());
});
//Enable or disable button based on if inputs are filled or not
$('input').filter('[required]').on('keyup',function() {
checkInputs()
})
checkInputs()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input required>
<input required>
<input required>
<button id="confirm">check</button>
</form>
Try to target the element in this way:
$('input[required]')
This should do the trick.
if it is 0 then all input filled otherwise it will return 0 mean any one or more are empty input.
function checkInputs(){
var flag = 0;
$('input').each(function() {
if($(this).val() == ''){
return flag = 1;
}
});
return flag;
}
$('#confirm').click(function () {
alert(checkInputs());
});
Your selector is looking for a tagName <input-required></input-required> that obviously doesn't exist.
Add a dot prefix for class
Can also use filter() to simplify
function checkInputs(){
return !$('.input-required').filter(function() {
return !this.value;
}).length;
}
NOTE: Will not work on radios or checkbox if those are part of the collection of elements with that class and you would need to add conditional for type if that is the case
You forgot to put class symbol in jQuery:
function checkInputs() {
var isValid = true;
$('.input-required').each(function() {
if($(this).val() === ''){
isValid = false;
return false;
}
});
return isValid;
}
Try this..

page gets refreshed on submit click

i have multiple validation on my form.. when i enter wrong data and click on submit button its shows the error message for a second and page gets refreshed..This is only few functions.there are other functions also.. Individually, they work fine. but when i try to run all , it doesnt work.
javascript:
function req()
{
if (document.reg_indi_form.txt_fnm.value=="")
{
document.getElementById('i').innerHTML="*This field is required";
document.getElementById('i').style.color="red";
document.getElementById('i').style.fontSize="12px";
}
if (document.reg_indi_form.txt_lnm.value=="")
{
document.getElementById('i1').innerHTML="*This field is required";
document.getElementById('i1').style.color="red";
document.getElementById('i1').style.fontSize="12px";
}
return false;
}
function validateUname() {
submitFlag = true;
var len=document.reg_indi_form.txt_usrnm.value.length;
if(len<6){
submitFlag=false;
document.getElementById('i2').innerHTML="*enter atleast 6 char";
document.getElementById('i2').style.color="red";
}
return submitFlag;
}
function alls()
{
req();
validateUname();
}
html:
<form name="reg_indi_form" method="post" onSubmit="return alls()" enctype="multipart/form-data">
There is also php code in my file.
Change your function alls() to:
function alls()
{
return req() && validateUname(); // Your function must return false otherwise it will be considered as true
}
Whenever you are binding event & want to stop propagation, just return false ( which you are doing ) but your function alls() was not returning anything which will not stop event propagation further.
Your functions alls() has no return statement and therefore returns an undefined. The only return value that prevents the default action is false. Any other return value, including undefined, allows the default action to take place.
change your function alls() to look like this:
function alls() {
req();
return validateUname();
}
In function alls()
function alls()
{
return req() && validateUname(); // Equivalent to-- if(req() && validateUname()) {return true;} else{ return false;}
}

Check if input field is empty on fields with jQuery

I have a form with 5 fields all with the class 'required'
Im trying to ensure that on submit these fields arent empty, if they are, add a class, if not, return true - ive tried the following only with no luck, even if the fields are empty the form still submits.
$('.submit').click(function(){
if($('.required').val() == "") {
$('.required').addClass('error');
return false;
} else {
return true;
};
});
Try:
$('.submit').click(function(e){
if(!$('.required').val()) {
$('.required').addClass('error');
e.preventDefault();
} else {
return true;
};
});
Try this:
$('.submit').click(function() {
$('.required').removeClass('error').filter(function() {
return !$.trim(this.value).length;
}).addClass('error');
});
Class error is added to empty fields only and is removed otherwise.
http://jsfiddle.net/dfsq/2HxaF/
Another variation which can be useful for your task: additional validation on fields blur:
$('.submit').click(validate);
$(document).on('blur', '.required', function() {
validate($(this));
});
function validate($field) {
($field instanceof jQuery && $field || $('.required')).removeClass('error').filter(function() {
return !$.trim(this.value).length;
}).addClass('error');
}
http://jsfiddle.net/dfsq/2HxaF/1/
if($('.required') will return a collection of jQuery objects, while the call to .val() will only use the first element of that collection to perform your test.
try something like this (EDIT: don't need to do a loop or test, since filter expr will take care of that for you):
$('.submit').click(function(e) {
var ins = $('input.required[value=""]');
ins.addClass('error');
return false;
}
return true;
}
You should use filter to get the empty fields. The form submit is also better to use so that it will handle enter key presses too. If not then you will have to handle the enter key presses inside the form that will trigger the submit event of the form
$('yourform').submit(function(){
// empty will contain all elements that have empty value
var empty = $('.required').filter(function(){
return $.trim(this.value).length === 0;
});
if(empty.length){
empty.addClass('error');
return false;
}
});
A little late to the party but I think this is the best solution:
Replace ALL required fields that weren't filled:
http://jsfiddle.net/LREAh/
$('form').submit(function(){
if(!$('.required').val()) {
$('.required').attr('placeholder', 'You forgot this one');
return false;
} else {
return true;
};
});
Replace only the required field of the submitted form: http://jsfiddle.net/MGf9g/
$('form').submit(function(){
if(!$(this).find('.required').val()) {
$(this).find('.required').attr('placeholder', 'You forgot this one');
return false;
} else {
return true;
}
});
Of course you can change attr('placeholder', 'You forgot this one'); for addClass('error'); -- it was only for demonstration. You don't need the id="formX" on the html btw, I was just trying something else out and forgot to remove.

Stop redirect in JavaScript

I have a function which verifies if some fields have been filled out (if length > 0) before submitting. If it fails to submit, I don't want to redirect the client at all. Right now, I have the following:
function onSubmit()
{
if (verify()) //This function will throw alert statements automatically
{
document.getElementById('my_form').submit();
return void(0);
}
else
{
document.getElementById('my_form').action = null;
}
}
However, it doesn't matter if verify() returns true or not, I still redirect the client and wipe her inputted fields. How do I keep the client on the page if a required field is blank? (I don't want to lose her currently filled out form...)
Also, I can't use the slick JQuery libraries, since it's not supported on some older browsers. (I'm trying to capture the most general audience.)
This is how I would try to solve this:
document.getElementById('my_form').onsubmit = function( e ){
var event = e || window.event;
// function payload goes here.
event.returnValue = false;
if ( event.preventDefault ){ event.preventDefault(); }
return false;
}
Can be used with event delegation too.
return false to the form!
<form onsubmit="return onSubmit()">
function onSubmit()
{
if (verify()) //This function will throw alert statements automatically
{
return true;
}
else
{
return false;
}
}
to stop the form from submitting, return false from your onSubmit

Categories

Resources