JavaScript -- not validating for blank fields - javascript

I have the following JavaScript function that is not supposed to allow blank fields to be sent to my back end code, but it's doing it anyway. Even if one or both of my fields is empty, this code is sending 2 blank values. (It works just fine if they're both filled in.) It's also not making my error messages appear. Can anyone help me? Here is my JavaScript.
function submitForm() {
var allValid = true;
var name = $("#name").val();
var comment = $("#comment").val();
if (name == null || name.length == 0) {
allValid = false;
$("#nameReq").css("visibility", "block");
} else {
$("#nameReq").css("visibility", "hidden");
}
if (comment == null || comment.length == 0) {
allValid = false;
$("#commentReq").css("display", "block");
} else {
$("#commentReq").css("display", "hidden");
}
if (allValid) {
clearForm();
$.ajax({
type : "post",
url : "writeComment",
data : "name=" + name + "&comment=" + comment,
success : function(response) {
},
error : function(error) {
}
});
document.getElementById('submit').disabled = true;
}
}
function clearForm() {
$("commentForm").reset();
}
Here is my form.
<form:form id="commentForm" method="post">
<table>
<tr>
<td>Name:<span style="display: none" id="nameReq">
<font style="font-weight: bold; color: red; visibility: hidden;">
<c:out value='Name required' /></font></span><br />
<input type="text" id="name" maxlength="30" /></td>
</tr>
<tr>
<td>Comment:<span style="display: none" id="commentReq">
<font style="font-weight: bold; color: red; visibility: hidden;">
<c:out value='Comment required' /></font></span><br />
<textarea id="comment" rows="20" cols="125" /></textarea></td>
</tr>
<tr>
<td><input id="submit" type="submit" value="Submit comment" onClick="submitForm()" /></td>
<td> </td>
</tr>
</table>
</form:form>

Your form will submit regardless of the action in your onclick function because the input button type is submit. If you'd like to only submit using your AJAX call, change the input to type="button".
Even if you'd like to submit without the ajax call, you can still use type="button" and submit the form using $('#commentForm').submit();

Your textarea is both self-terminating and has a closing tag. When I tried to run this, that confused it to the point that the onClick of the button was not run.

Related

issue with form validation including input file

I'm having this very simple form to enter user name and choose a file to upload. User name is required but file is not. It's styled and has a function to check file type and size before submitting the form. If you choose a wrong file the function will work and the submit button will be disabled. If you don't choose a file the user name validation won't work. If you click in the text input then blur it will go red but the form will submit.
JSFIDDLE
HTML
<form method="post" class="contact" onsubmit="return validate();" enctype="multipart/form-data">
<table cellspacing="30">
<tr>
<td>
<label id="userlabel">user name</label>
<input type="text" id="user" name="username" onblur="checkUser()"></td>
</tr>
<tr>
<td>
<div id="FileUpload">
<input type="file" size="4" id="BrowserHidden"
onchange="getElementById('FileField').value = getElementById('BrowserHidden').value;" name="pic" />
<div id="BrowserVisible"><input type="text" id="FileField" /></div>
</div>
</td>
</tr>
<tr>
<td><input type="submit" name="send" id="save" value="send" /></td>
</tr>
</table>
</form>
JS
function checkUser(){
var userlen = $("#user").val().length;
if(userlen<4){
$("#userlabel").css("color","rgb(224, 19, 19)");
return false;
}
else{
$("#userlabel").css("color","#000");
return true;
}
}
$("#BrowserHidden").change(function (e) {
var file = this.files[0];
var name = file.name;
var extension = name.substr((name.lastIndexOf('.') + 1));
var str = 'doc,docx,pdf';
if (str.indexOf(extension) > -1) {
console.log('y');
size = file.size;
console.log(size);
if (size > 10000000) {
alert('file size is larger than 10 MB');
$("#save").attr("disabled", "disabled");
return false;
}
else {
$("#save").removeAttr("disabled");
return true;
}
}
else {
alert('file type is not allowed');
$("#save").attr("disabled", "disabled");
return false;
}
});
function validate(){
$.each($('form :input'),function(){
$(this).blur().change();
});
if(!checkUser() ){
return false;
}
else{
return true;
}
}
This is how you can make it working:
change your submit button to normal one and add onclick attribute to it
remove onsubmit attribute from your form tag
change your validate() function to submit form if checkUser() returns true
That's it!
Fiddle
Hope that worked for you!

Javascript/jquery if statements aren't working

I've really been racking my few brain cells on this one- It seems simple enough but I can't get it to work-
$(function() {
function check() {
var myname = $("#myname").val();
var myemail = $("#myemail").val();
var password = $("#password").val();
var repeatpassword = $("#repeatpassword").val();
if (myname == "") {
$("#mynameresult").append("Please Enter Your Name");
return false;
}
if (myemail =="") {
$("#myemailresult").append("Please Enter Your Email");
return false;
}
if (password == "") {
$("#passwordresult").append("Please Enter a Password");
return false;
}
if (repeatpassword == "") {
$("#repeatpasswordresult").append("Please Repeat the Password");
return false;
}
return true;
}
});
My form looks like this-
<table class="registrationform">
<form method="post" onsubmit = "return check();" action="/ToDoneList/ToDoneList/usr/registrationparse.php" enctype="multipart/form-data" >
<tr><td>Username: </td><td><input class="focusfox" type="text" name="username" id="myname"></td><td id="mynameresult"></td></tr>
<tr><td>Email: </td><td><input type="text" name="email" id="myemail"></td><td id="myemailresult"></td></tr>
<tr><td>Password: </td><td><input type="password" name="password" id="password" /></td><td id="passwordresult"></td></tr>
<tr><td>Repeat the Password: </td><td><input type="password" name="repeatpassword" id="repeatpassword"/></td><td id="repeatpasswordresult"></td></tr>
<tr><td rowspan="2"><img id="captcha" src="/securimage/securimage_show.php" alt="CAPTCHA Image" /></td><td><input type="text" name="captcha_code" maxlength="6" title="Enter What you see on the Left If you are having trouble click the New Image Button"/></td></tr>
<tr><td><button type="button "onclick=\'document.getElementById("captcha").src = "/securimage/securimage_show.php?" + Math.random(); return false\'>New Image</button></td>
<tr><td class="regbutton" colspan="2"><input type="submit" value="Register" ></td></tr>
</form>
</table>
The problem is that this function won't catch when I submit the form with empty spaces. I think it must be a problem with my if statements because when I strip it down and have it save values to the variables and append those values to the variables with return being false outside of an if statement it does stop it from submitting.
Anyway, is there anything that you can see that is wrong here? Thanks in advance for the help!
You're defining your "check" function inside the "ready" callback. Therefore, it's not global, so you can't call it from your "submit" handler.
Attach your submit handler via jQuery instead:
$('form').submit( check );
Put that at the end (inside) the "ready" handler.
put your function check() outside the $(function(){ }) block !!

jQuery button validate part of a form at a time

Sorry if I did not explain my problem clearly.
I have a form with multiple tables for users inputs.
I use next and back buttons to hide and show different tables in order to guide users.
Now the problem is:
How do I use next button to validate current active table inputs? For example, every time a user click next, it will check if all the fields are filled?
Here is a broken DEMO. Thanks for any comments!
HTML
<form method="post" id="form1" action=index.html>
<table>
<H4 align="center" id="id_tab">
| Chemical |
Crop |
Physical |
</H4>
</table><br>
<table class="tab tab_Chemical" border="0">
<tr>
<th><label for="id_wat_hl">Water Column Half life (days):</label></th>
<td><input type="text" name="wat_hl" id="id_wat_hl" /></td>
</tr>
</table>
<table class="tab tab_Crop" border="0" style="display:none">
<tr>
<th><label for="id_zero_height_ref">Zero Height Reference:</label></th>
<td><input type="text" name="zero_height_ref" id="id_zero_height_ref" /></td>
</tr>
</table>
<table class="tab tab_Physical" border="0" style="display:none">
<tr>
<th><label for="id_mas_tras_cof">Mass Transfer Coefficient (m/s):</label></th>
<td><input type="text" name="mas_tras_cof" id="id_mas_tras_cof" /></td>
</tr>
</table>
<table align="center">
<tr>
<td><input class="back" type="button" value="Back" /></td>
<td><input class="next" type="button" value="Next" /></td>
<td><input class="submit" type="submit" value="Submit" /></td>
</tr>
</table>
</form>
JS
$(document).ready(function() {
var tab_pool = ["tab_Chemical", "tab_Crop", "tab_Physical"];
var visible = $(".tab:visible").attr('class').split(" ")[1];
var curr_ind = $.inArray(visible, tab_pool);
$(".submit").hide();
$(".back").hide();
$('.next').click(function() {
if (curr_ind < 2) {
$(".tab:visible").hide();
curr_ind = curr_ind + 1;
$("." + tab_pool[curr_ind]).show();
$(".submit").hide();
$(".back").show();
}
if (curr_ind == 2) {
$(".submit").show();
$(".next").hide();
}
});
$('.back').click(function() {
if (curr_ind > 0) {
$(".tab:visible").hide();
curr_ind = curr_ind - 1;
$("." + tab_pool[curr_ind]).show();
$(".submit").hide();
$(".next").show();
}
if (curr_ind == 0) {
$(".back").hide();
}
});
$(".next").click(function() {
$(".tab tab_Chemical").validate({
rules: {
wat_hl: "required"
}
})
})
$(".next").click(function() {
$(".tab tab_Crop").validate({
rules: {
zero_height_ref: "required"
}
})
})
$(".next").click(function() {
$(".tab tab_Physical").validate({
rules: {
mas_tras_cof: "required"
}
})
})
});
Add validation using the form
var validator = $('form').validate({
ignore: 'input[type="button"],input[type="submit"]',
rules: {
wat_hl: {
required: true
},
zero_height_ref: {
required : true
},
mas_tras_cof: {
required: true
}
}
});
Then in the next handler
$('.next').click(function () {
var tab = $(".tab:visible");
var valid = true;
$('input', tab).each(function(i, v){
valid = validator.element(v) && valid;
});
if(!valid){
return;
}
if (curr_ind < 2) {
$(".tab:visible").hide();
curr_ind = curr_ind + 1;
$("." + tab_pool[curr_ind]).show();
$(".submit").hide();
$(".back").show();
}
if (curr_ind == 2) {
$(".submit").show();
$(".next").hide();
}
});
Demo: Fiddle
Explanation
var valid = true: a flag to keep the state of the tab through the iteration process
$('input', tab).each: Iterate through each inputs element in the current tab
validator.element(v) validate each element in the tab
valid = validator.element(v) && valid: update the state of the tab
What about this ?
var isOpenedTabValid = $(".tab:visible :input").valid();
I have an implementation to get this same result. I have added div elements with role="form" parameter. And then validates elements on each div as it is like a form while the main form is still wrapping around.
<form action="#" id="myForm" role="form" data-toggle="validator" method="post">
<div id="form-step-0" role="form" data-toggle="validator"><!-- Input elemets --></div>
<div id="form-step-1" role="form" data-toggle="validator"><!-- Input elemets --></div>
<div id="form-step-2" role="form" data-toggle="validator"><!-- Input elemets --></div>
</form>
And this jQuery code to check if there is any error in a particular div
var elmForm = $("#form-step-0");
elmForm.validator('validate');
The following code will check if there is any error input raised in a particular div
var elmErr = elmForm.children('.has-error');
if(elmErr && elmErr.length > 0){
// Error elements found, Form validation failed
return false;
}
And when you want to validate the whole form just use the normal code
var elmForm = $("#myForm");
elmForm.validator('validate');
var elmErr = elmForm.find('.has-error');
if(elmErr && elmErr.length > 0){
alert('Oops we still have error in the form');
return false;
}else{
alert('Great! we are ready to submit form');
elmForm.submit();
return false;
}
Here is the source file on GitHub
Here is a Demo implemeation
You are calling the validate method for each table every time the next button is clicked. Instead, you only want to call validate if the table is visible. Since you are already tracking which table should be visible with your curr_ind, I'd suggest using it to know which table to validate and only calling validate for the visible table.

Stopping action if requirements are not met

I want to check the validation of two text boxs if either one is empty. It showed show an error as an innerHTML and if they are both filled in. It will then continue to action. Here is my code:
function go()
{
var toCheck = document.getElementById('myAnchor');
if (toCheck != '') {
return true;
}
else
{
document.getElementById('myAnchor').innerHTML = 'Fred Flinstone';
}
}
this does set the innerHTML but still continues with the action. How can I stop it from continuing?
Thank you!
You should check the value of text box,
Change the code to
function go()
{
var toCheck = document.getElementById('myAnchor').value;
if (toCheck != '') {
return true;
}
else
{
document.getElementById('myAnchor').innerHTML = 'Fred Flinstone';
}
}
add the onsubmit on the form:
<form onsubmit="return true;">
...
</form>
if the return is false it will stop from submitting an opposite scenario if it's true. you could also call your functions on that attribute and do the same thing then if it doesn't fit the condition it will stop from submitting your form and do the other process you desire to happen.
Textfields use the value attribute.
document.getElementById('myAnchor').value = 'Fred Flinstone';
An empty textfield would have a value of "".
function go()
{
var toCheck = document.getElementById('myAnchor');
if (toCheck.value != "") {
return true;
}
else
{
toCheck.value = 'Fred Flinstone';
}
}
Here's a working example.
<!DOCTYPE html>
<html>
<body>
<form name="form" action="data.php">
<label style="float:left">
<font face="Comic Sans MS">* username &nbsp
</label></font>
<input type="text" id='textfield' name="name" size="40" style="float: left;">
<label id='myAnchor' style="display: inline; padding-left: 20px;"></label> <br/> <br/>
<label style="float:left"><font face="Comic Sans MS">* password &nbsp</label></font>
<input type="text" name="pwd" size="40" style="float: left;">
<label id="myAnchor2" style="display: inline; padding-left: 20px;">
</label> <br/> </p> <input type="button" value="LogIn" onClick="return go();"> </form>
</body>
<script>
function go()
{
var toCheck = document.getElementById('textfield');
if (toCheck.value != "") {
return true;
}
else
{
toCheck.value = 'Fred Flinstone';
}
}
</script>
</html>
In your question you said that
I want to check the validation of two text boxs
In that case you should be checking the value of textboxes, not the myAnchor.
I would change your html code like this:
<input type="text" name="name" id="name" size="40" style="float: left;">
<input type="text" name="pwd" id="pwd" size="40" style="float: left;">
<input type="submit" value="LogIn" onSubmit="go();">
adding id to the input boxes
then change the onClick event to onSubmit. that way you can perform javascript validation in the function, then submit the form if all goes well, otherwise display the error.
Then your script will be like...
function go() {
var name = document.getElementById('name').value,
pwd = document.getElementById('pwd').value;
if (name != '' && pwd != '') {
document.forms["form"].submit();
}
else {
document.getElementById('myAnchor').innerHTML = 'Fred Flinstone';
}
}

Are there any very Simple JQuery Validation?

Hi I'm looking to add some simple validation to a form.
There are 2 textboxes which the user is expected to enter only numbers and it must be greater than zero. The jquery code is in it's own file (the form consists of html / jquery / php). The first number is for 'previous age' and the second number is for 'current age'. For example, if the user enters '0' in either textbox, an alert or message box should appear informing them that they need to enter a number greater than zero. Anything other than a number greater than zero entered into the textbox should result in the alert message.
As a side note, the .php file is used only for the calculation/math once the user has cleared the requirements of the form.
If someone could provide a clear and concise example, it would much appreciated. I've tried to find a suitable example via google searching, however nothing seemed to fit. Also I'm trying to avoid using a validator plugin, which seemed to be the go to answer when googling the question.
I have my reasons and will be more than happy to explain if needed.
Thank-you,
Charles
if you take away the aspect of your question, validation is fairly basic. All jquery would be used for is to make selecting specific dom elements easier
$(function() {
$('form').submit(function() {
return checkFormIsValid();
});
$('#field1').keyup(function() {
checkField(this.id);
});
$('#field2').keyup(function() {
checkField(this.id);
});
});
function checkFormIsValid()
{
return checkField('field1') && checkField('field2');
}
function checkField(fieldId)
{
var val = $('#'+fieldId).val();
// validation logic
if(isValid) {
return true;
} else {
alert(fieldId+ ' is not valid');
return false;
}
}
This basic validation will be triggered on each field, as well as when the user submits the form.
As Ben Rowe suggest you can use that code, but in checkField(fieldId) function you have to validate that input data should be integer only in that case you can use these codes to vaildate that.
Regex to validet input data
var isEmail_re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
function isEmail(s) {
return String(s).search(isEmail_re) != -1;
}
function isBlank(s) {
if (!s || s.length == 0) {
return true;
}
// checks for a non-white space character
// which I think [citation needed] is faster
// than removing all the whitespace and checking
// against an empty string
return !/[^\s]+/.test(s);
}
function SendContactForm() {
var isFormValid = true;
var isEmailOk = isEmail($('#cemail').val());
if (isEmailOk == false) {
$('#emEmail').css('color', 'red');
isFormValid = false;
}
else {
$('#emEmail').css('color', 'black');
}
var isNameOk = isBlank($('#cname').val());
if (isNameOk) {
$('#emName').css('color', 'red');
isFormValid = false;
//alert('!');
}
else {
$('#emName').css('color', 'black');
}
var isSubjectOk = isBlank($('#csubject').val());
if (isSubjectOk) {
$('#emSubject').css('color', 'red');
isFormValid = false;
}
else {
$('#emSubject').css('color', 'black');
}
var isMesageOk = isBlank($('#cmessage').val());
if (isMesageOk) {
$('#emMessage').css('color', 'red');
isFormValid = false;
}
else {
$('#emMessage').css('color', 'black');
}
if (isFormValid) {
$('#contactFormFields').hide("explode", 1000);
$.post("/Home/SendContactForm", { email: $('#cemail').val(),
name: $('#cname').val(),
subject: $('#csubject').val(),
message: $('#cmessage').val()
},
function (data) {
if (data.length > 0) {
// alert(data);
}
});
}
}
<div id="contactFormFields">
<table>
<tr>
<td style="width: 150px;">
E-Mail
</td>
<td>
<input id="cemail" type="text" value="E-mail" name="email" size="25" class="required email" /><em id="emEmail">*</em>
</td>
</tr>
<tr>
<td style="width: 150px;">
Name
</td>
<td>
<input id="cname" name="name" size="25" class="required" maxlength="100" /><em id="emName">*</em>
</td>
</tr>
<tr>
<td style="width: 150px;">
Subject
</td>
<td>
<input id="csubject" name="subject" size="25" class="required" maxlength="200" /><em id="emSubject">*</em>
</td>
</tr>
<tr>
<td style="width: 150px; vertical-align: top;">
Message
</td>
<td>
<textarea id="cmessage" maxlength="1000" name="comment" cols="27" rows="10" class="required"></textarea><em id="emMessage">*</em>
</td>
</tr>
<tr>
<td style="width: 150px;">
</td>
<td>
<input type="submit" value="Send" class="input-btn" onclick="SendContactForm();" style=" width:100px; color: Black;" />
</td>
</tr>
</table>
</div>
maybe your looking for a plug in to validate form fields?
you can give this a try: http://www.vanadiumjs.com/
just add its js file and your ready.
adding a required validation is as simple as adding css like this
<input class=":required" type="text">
to add an integer validation
<input class=":integer" type="text">
and so on. just follow the link for more info.

Categories

Resources