I have this JavaScript code in the head portion of a php file:
<script language="JavaScript" type="text/javascript">
function validateFirstName(field)
{
if (field == "")
{
return "Please enter a first name.\n";
}
else if (/[^a-zA-Z]/.test(field))
{
return "Invalid first name.\n";
}
return "";
}
function validateLastName(field)
{
if (field == "")
{
return "Please enter a last name.\n";
}
else if (/[^a-zA-Z]/.test(field))
{
return "Invalid last name.\n";
}
return "";
}
//more functions eliminated
function validate(form)
{
fail = validateFirstName(form.firstname.value);
fail += validateLastName(form.lastname.value);
//and so forth
if (fail == "")
{
return true;
}
else
{
alert(fail);
return false;
}
}
</script>
And the form:
<form action="StudentSignUpPageAddingData.php" method="post" onsubmit="return validate(this)">
<p id="p3">First Name: <input id="roundedcorners" type="text" name="firstname"><br></p>
<p id="p3">Last Name: <input id="roundedcorners" type="text" name="lastname"><br></p>
//and so forth
<input id="i1" type="submit" value="Done!">
</form>
When I run it, though, the program skips to the code in StudentSignUpPageAddingData.php. I'm new to PHP and JavaScript, so I'm wondering if there's a problem with the onsubmit call. Should I also consider pasting the JavaScript code in a separate file and simply referencing it in the PHP file?
Got it, it turns out JavaScript was disabled for some reason on my computer. Here's a quick link to figure out how to quickly enable JavaScript:
http://activatejavascript.org/en/instructions/safari
Related
I made a HTML form and assigned two inputs into it, One for username and one for mobile number. I then made a function in Java Script and made two variables a and b for username and mobile number but on submitting the form the function seem to work only for one of the inputs , can someone provide a solution to this ?
I am expecting the messages assigned for username and mobile number to appear in the span tag on submittion of the form
i am providing the HTML and Java Script code below
<form onSubmit="return valid()">
HOME
<p><input type="text" id="user_name" value=""><span id="msg"></span></p>
Mobile
<p><input type="text" id="mobile" value=""><span id="msg"></span></p>
<p><input type="submit" value="submit"></p>
JavaScript Document
function valid()
{
var correct_way = /^[A-Za-z]+$/;
var a=document.getElementById("user_name").value;
if(a=="")
{
document.getElementById("msg").innerHTML=" please insert value";
return false;
}
if(a.length<3)
{
document.getElementById("msg").innerHTML=" username cannot be less than 3 charachters";
return false;
}
if(a.length>15)
{
document.getElementById("msg").innerHTML=" username cannot be greater than 15 charachters";
return false;
}
if(a==correct_way)
{
true;
}
else
{
document.getElementById("msg").innerHTML=" username should be only charachter";
return false;
}
var b=document.getElementById("mobile").value;
if(b=="")
{
document.getElementById("msg").innerHTML=" please enter mobile number";
return false;
}
if(isNaN(b))
{
document.getElementById("msg").innerHTML=" only numbers are allowed";
return false;
}
if(b.length<10)
{
document.getElementById("msg").innerHTML=" mobile number must be 10 digit";
return false;
}
if(b.length>10)
{
document.getElementById("msg").innerHTML=" mobile number must be 10 digit";
return false;
}
}
function valid()
{
var correct_way = /^[A-Za-z]+$/;
var a=document.getElementById("user_name").value;
if(a=="")
{
document.getElementById("user_name").nextSibling.innerHTML=" please insert value";
return false;
}
if(a.length<3)
{
document.getElementById("user_name").nextSibling.innerHTML=" username cannot be less than 3 charachters";
return false;
}
if(a.length>15)
{
document.getElementById("user_name").nextSibling.innerHTML=" username cannot be greater than 15 charachters";
return false;
}
if(!correct_way.test(a)){
document.getElementById("user_name").nextSibling.innerHTML=" username should be only charachter";
return false;
}
var b=document.getElementById("mobile").value;
if(b=="")
{
document.getElementById("mobile").nextSibling.innerHTML=" please enter mobile number";
return false;
}
if(isNaN(b))
{
document.getElementById("mobile").nextSibling.innerHTML=" only numbers are allowed";
return false;
}
if(b.length<10)
{
document.getElementById("mobile").nextSibling.innerHTML=" mobile number must be 10 digit";
return false;
}
if(b.length>10)
{
document.getElementById("mobile").nextSibling.innerHTML=" mobile number must be 10 digit";
return false;
}
}
<form onSubmit="return valid()">
HOME
<p><input type="text" name="user_name" id="user_name" value=""><span class="user_name"></span></p>
Mobile
<p><input type="text" name="mobile" id="mobile" value=""><span class="mobile"></span></p>
<p><input type="submit" value="submit"></p>
Maybe bec you are not returning any true statements with the b part. You have only error messages
If you can use HTML 5 form validation please do because it will do a lot of this stuff for you and is natively supported by modern browsers.
If not, I'm not exactly sure what you are trying to do but a few things I can see is you will return true before validating the second variable so put a return true at the end of the function and only return false when validation fails. Second once you return true the form will submit so your page is going to reload and unless you use your server side code to populate the span tags you won't see anything in them because the page was reloaded. The only other thing is to make sure your js doesn't get cached if you are loading it from a js file. Please let me know some more specifics on what is happening and I will be able to help more.
Maybe missing the return in front of true also but then everything after this statement would be unreachable.
if(a==correct_way)
{
true;
}
else
{
document.getElementById("msg").innerHTML=" username should be only charachter";
return false;
}
I'm trying to submit a HTML form, only when all the fields do not return false in the Javascript code.
My HTML looks like this, for simplicity I have just kept the name and email
<form method="post" action="RegistrationServlet" class="iform"
onsubmit="return sendForm();">
<ul><li><label for="YourName">*Your Name <span id="regNameErr"></span></label>
<input class="itext" type="text" name="YourName" id="YourName" /></li>
<li><br /><label for="YourEmail">*Your Email <span id="regEmailErr"></span></label>
<input class="itext" type="text" name="YourEmail" id="YourEmail" /></li>
<li><input type="submit" value="Submit" class="ibutton" name="SendaMessage"
id="SendaMessage" value="Send a Message!" readonly="readonly" /></li></ul></form>
The Javascript looks like this, again for simplicity I am just checking 2 fields:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript">
window.sendForm = function() {
if (($("#YourName").val() == "") || ($("#YourName").val().length > 55)) {
$("#YourName").addClass("required");
window.scroll(0, 190);
$("#regNameErr").text("required");
return false;
}
if ($("#YourEmail").val() == "") {
$("#YourEmail").addClass("required");
window.scroll(0, 190);
$("#regEmailErr").text("required");
return false;
}
if (!isEmailValid($("#YourEmail").val())) {
$("#YourEmail").addClass("required");
window.scroll(0, 190);
$("#regEmailErr").text("required");
return false;
}
$("#SendaMessage").val("Please Wait...");
return true;
}
Why is the sendForm() function not repeatedly being called to check that all fields are correct before submitting. Any ideas?
Also I understand that I can add a bounty after 2 days but I am not seeing any button on the editor.
Can you help?
sendForm is called only once per submit - this how it works, and there is no reason to call it multiple times.
If you want to have all your fields checked on submit - you should not return after each check. Instead you should postpone this action until the all fields are verified, and introduce some flag to remember results:
function() {
var formValid = true;
if (($("#YourName").val() == "") || ($("#YourName").val().length > 55)) {
...
formValid = false;
}
if ($("#YourEmail").val() == "") {
...
formValid = false;
}
if (!isEmailValid($("#YourEmail").val())) {
...
formValid = false;
}
if (!formValid) {
return false;
}
$("#SendaMessage").val("Please Wait...");
return true;
}
Side note. Have you considered any jQuery validation plugins for this? Might save you some implementation and maintenance efforts.
When i post form only the title validation is working, the other two fields are not validated.
HTML
<form name="qaform" class="nice" method="POST" onsubmit="validateForm()" action="/ask/ask-question/">
<input type="hidden" id="id_selected_tags" name="tags">
<p>
<label for="id_title" class="inline-block">Title</label>
<input type="text" class="input-text inline-block" id="id_title" name="question_title">
</p>
<span id="error_title"></span>
<textarea id="id_question" name="question_description" class="full-width"></textarea>
<span id="error_body"></span>
<p>
<label for="id_tags" class="inline-block">Tags</label>
<input type="text" id="id_newstagbox" name="question_tags"/>
</p>
<span id="error_tags"></span>
<button class="btn btn-success" type="submit">Post your question</button>
</form>
JS
function validateForm()
{
//title validation
if (document.qaform.question_title.value == "") {
document.getElementById('error_title').innerHTML="*Please add a title*";
return false;
}
//body validation
if (document.qaform.question_description.value == "") {
document.getElementById('error_body').innerHTML="*Please add a description*";
return false;
}
//tag validation
if (document.qaform.question_tags.value == "") {
document.getElementById('error_tags').innerHTML="*Please add a description*";
return false;
}
}
After submitting the forms post successfully if title is present.
The stackoverflow form validation forced me to do this, its constantly saying me to add more text because my question contains mostly code.I know its good to provide more information about question but there are times when you can ask a question in few words without being too broad and then you have to rant about it to pass the FORM VALIDATION.
Just remove return false.modify it like below
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
var y=document.forms["myForm"]["farea"].value;
var z=document.forms["myForm"]["ftag"].value;
if (x==null || x=="")
{
document.getElementById('ern').innerHTML="*Please add a title*";
}
if (y==null || y=="")
{
document.getElementById('era').innerHTML="*Please add a desxription*";
}
if (z==null || z=="")
{
document.getElementById('ert').innerHTML="*Please add a tag*";
}
}
</script>
I prefer using jQuery:
$('#form').submit(function(e) {
var validated = true;
e.preventDefault();
//title validation
if ($('#id_title').val() == "") {
$('#error_title').html("*Please add a title*");
validated = false;
}
//body validation
if ($('#id_question').val() == "") {
$('#error_body').html("*Please add a description*");
validated = false;
}
//tag validation
if ($('#id_newstagbox').val() == "") {
$('#error_tags').html("*Please add a description*");
validated = false;
}
if(validated) {
$(this).unbind('submit').submit();
}
});
You just remove your return false inside each condition,
check this jsfiddle how it works if you remove return false line.
Note:Return false will stop your execution there
Remove the "return false" in the if clauses. This stops your function and the other if clauses wouldn´t get called.
just add 'return' keyword before validateform()
like this
<form name="qaform" class="nice" method="POST" onsubmit="return validateForm()" action="/ask/ask-question/">
Try making these 5 small changes to your validateForm method -
function validateForm() {
var valid = true; // 1
//title validation
if (document.qaform.question_title.value == "") {
document.getElementById('error_title').innerHTML="*Please add a title*";
valid = false; // 2
}
//body validation
if (document.qaform.question_description.value == "") {
document.getElementById('error_body').innerHTML="*Please add a description*";
valid = false; // 3
}
//tag validation
if (document.qaform.question_tags.value == "") {
document.getElementById('error_tags').innerHTML="*Please add a description*";
valid = false; // 4
}
return valid; // 5
}
i think the reason why it only validates the first one, is because you return false to exit the validate function, if you do the return false after all the if loops i think it will do what you want.
i have used the following code for javascript validation, that return true or false depending on the condition
javascript block
function fnval()
{
if(document.field.value == "")
{
alert("Invalid value");
return false;
}else{
return true;
}
}
Here is my HTML:
<Input type=submit name="sub" onClick="return fnval()">
Thus the js block checks if the field value is entered or not. If not it throws an alert message and return false, and hence the form does not get submitted.
But in case the value is not empty it returns a true, and still the form does not get submitted.
I have seen some queries asked by people where return false results in submission of the form. But this is exactly opposite.. and am not able to find a solution as of now.
Can anyone please help me on this?
Try getElementsByName:
function fnval()
{
if(document.getElementsByName('field')[0].value == "")
{
alert("Invalid value");
return false;
}else{
return true;
}
}
getElementsByName doesn't have IE support though. Perhaps:
function fnval()
{
if(findInput('field')[0].value == "")
{
alert("Invalid value");
return false;
}else{
return true;
}
}
function findInput(name) {
var elements = document.getElementsByTagName('input'),
length = elements.length,
i = 0,
results = [];
for(i; i<length; i++) {
if (elements[i].name === name) {
results.push(elements[i]);
}
}
return results;
}
You need to add the form name and the form value. Something like:
if ( document.formName.fieldName.value == "" )
For instance, with this kind of HTML:
<form method="post" onsubmit="">
Password: <input name="password" type="text" /><br />
</form>
The js:
if (document.form.password.value == "") {
//empty
}
i suggest using onsubmit in the form, <form ... onsubmit="return fnval()">,
try adding that and placing return false at the base of your function.
no matter what you do in js. but if you have filled action tag of form element element , the form will submit.
Syntax error:
type="submit"
not
type=submit
I hope I can explain this right I have two input fields that require a price to be entered into them in order for donation to go through and submit.
The problem that I am having is that I would like the validation process check to see if one of the two fields has a value if so then proceed to submit. If both fields are empty then alert.
This is what I have in place now after adding some of the input i received earlier today:
function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{
alert(alerttxt); return false;
}
else
{
return true;
}
}
}
function validate_form(thisform)
{
with (thisform)
{
if (validate_required(billing_name_first,"You must enter your first name to donate")==false)
{billing_name_first.focus();return false;}
else if (validate_required(billing_name_last,"You must enter your last name to donate")==false)
{billing_name_last.focus();return false;}
else if (validate_required(billing_address_street1,"You must enter your billing street address to donate")==false)
{billing_address_street1.focus();return false;}
else if (validate_required(billing_address_city,"You must enter your billing address city to donate")==false)
{billing_address_city.focus();return false;}
else if (validate_required(billing_address_state,"You must enter your billing address state to donate")==false)
{billing_address_state.focus();return false;}
else if (validate_required(billing_address_zip,"You must enter your billing address zip code to donate")==false)
{billing_address_zip.focus();return false;}
else if (validate_required(billing_address_country,"You must enter your billing address country to donate")==false)
{billing_address_country.focus();return false;}
else if (validate_required(donor_email,"You must enter your email address to donate")==false)
{donor_email.focus();return false;}
else if (validate_required(card_number,"You must enter your credit card number to donate")==false)
{card_number.focus();return false;}
else if (validate_required(card_cvv,"You must enter your credit card security code to donate")==false)
{card_cvv.focus();return false;}
else if (validate_required(input1,"Need to enter a donation amount to continue")==false && validate_required(input2, "Need to enter a donation amount to continue")==false)
{
input1.focus();
return false;
}
}
}
This works fine... other than the fact that I get a message that reads error undefined... which i click ok about 2 times then I get the correct alert and instead of allowing me to correct the problem in IE7 and IE8 the form just processes.
Thanks guys any help would do
Matt
If I am understanding correctly, you only want to do the alert if both of the inputs are empty. If that's the case here's a refactoring of your code that will handle that.
function validate_required(field)
{
with (field)
{
if (value==null||value=="")
{
return false;
}
else
{
return true;
}
}
}
function validate_form(thisform)
{
with (thisform)
{
if (validate_required(input1)==false && validate_required(input2)==false)
{
alert('Need a donation to continue');
input1.focus();
return false;
}
}
}
take the alert() out of your assessment function- you're trying to do too much at once. a function to determine if input is valid or not should do only that one thing.
determine the state of your inputs first and then do something like
var field1Pass = validate_required(input1);
var field2Pass = validate_required(input2);
if ( !(field1Pass && field2Pass) ) {
alert("Need a donation amount to continue");
// TODO: logic to determine which field to focus on
return false;
}
var msg = "Need a donation amount to continue";
function validate_required(value) {
if(isNaN(value) || value == null || value == "") {
return false;
}
return true;
}
function validate_form(thisform) {
var i1 = validate_required($(thisform.input1).val());
var i2 = validate_required($(thisform.input2).val());
if(!(i1 && i2)) {
alert(msg);
thisform.input2.focus();
return false;
}
}
Look at the jQuery validation plugin. With the plugin it would just be a matter setting up the rules properly. You could get fancier and replace the default messages if you want. Check out the examples.
<script type="text/javascript">
$(function() {
$('form').validate({
'input1': {
required: {
depends: function() { $('#input2').val() == '' }
}
}
});
});
</script>
This sets it up so that input1 is required if input2 is empty, which should be sufficient since if input1 has a value, you don't need input2 and if neither has a value, then it will show your message for input1.
<input type="text" name="input1" />
<input type="text" name="input2" />
Here's my take, with refocusing on the first field that failed:
<body>
<form action="#" onsubmit="return validate(this);">
<input type="text" name="val0" /><br />
<input type="text" name="val1" /><br />
<input type="submit" />
</form>
<script type="text/javascript">
function validate(form) {
var val0Elem = form.val0, val1Elem=form.val1, elementToFocus;
// check fields and save where it went wrong
if (!numeric(val0Elem.value)) {elementToFocus=val0Elem;}
else if (!numeric(val1Elem.value)) {elementToFocus=val1Elem;}
// if there is an element to focus now, some validation failed
if (elementToFocus) {
alert('Enter numbers in both fields, please.')
// using select() instead of focus to help user
// get rid of his crap entry :)
elementToFocus.select();
// ..and fail!
return false;
}
// Helper function, "if a string is numeric":
// 1: it is not 'falsy' (null, undefined or empty)
// 2: it is longer than 0 too (so that '0' can be accepted)
// 3: it passes check for numericality using the builtin function isNaN
function numeric(s) {return (s && s.length>0 && !isNaN(s));}
}
</script>
</body>