I have strange problem. I'm trying validate my form by function in JavaScript in this way:
<input type="submit" onclick="return validate();" name="valideButton" value="Something" />
And the validate function:
function validate() {
alert("Some alert!");
var someValidateInputName = document.forms["formName"]["someValidateInputName"].value;
alert(someValidateInputName);
if (someValidateInputName == "0") {
alert("Wrong value: " + document.forms["formName"]["someValidateInputName"].value);
return false;
}
return true;
}
When I use alert(document.forms["formName"]["someValidateInputName"].value) inside my form there's everything allright, but when I'm calling function validate(); I have an alert with Some alert, but I don't have alert with someValidateInputName. It seems like a function return true when I try to check someValidateInputName and I don't know why...
The script with function is in the same file above the html code.
I validate form on the other my pages in the same way and there was no problem.
alert("Some alert!); should be alert("Some alert!"); the way it is now it tries to alert everything untill the next " meaning it tries to alert half your function.
Ok, I solve the problem.
It was a stupid mistake... and I think that nobody could not help me without more information.
I skip this, because I forget that this can be so important.
My form was closed in foreach loop and many input has name="someValidateInputName", so my outside function doesn't know which input I want to validate. I don't look at the problem in this way, because for me it was strange that function always return true when only I try read the input value.
If somebody forget about this like me, here is the solve:
We need to adding an indexes to name of form and name of input like this:
<input type="submit" onclick="return validate();" name="valideButton <?php echo $j; ?>" value="Something" />
In the same way we have to add index to name of form.
And I send my Index to read the right value via $_POST. I increment $j too.
<input type="hidden" value="<?php echo $j++; ?>" name="Index" />
At the end my validation() look like this:
function validate(index) {
alert("Some alert!");
var someValidateInputName = document.forms["formName"+index]["someValidateInputName"+index].value;
alert(someValidateInputName);
if (someValidateInputName == "0") {
alert("Wrong value: " + document.forms["formName"+index]["someValidateInputName"+index].value);
return false;
}
return true;
}
If you could place the form out of the foreach you don't be need to an index to form.
Thanks for the trying help!
Cheers
Related
I am designing an e-shop that allows profile registration. I need to have both Javascript & PHP validation for the registration form. (so when any of the fields are empty, I need to get a pop-up message that lets me know which specific field is empty + display on the screen beside the required field a visual message to advise the user where they need to correct the issue)
so far it is not working because my JS validation form activates onsubmit and my PHP is on action. I realize onsubmit activates before action and thus not allowing 'action' to go through.
I tried changing it from 'action' to 'onclick', but onsubmit also activates first and does not allow the PHP to work.
Here's my code for the form (I only included the first name portion so it won't get too long)
<form method="post" onclick="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" name="myForm" onsubmit="return validateForm()" style="border:1px solid #ccc">
<label><b>First Name</b></label>
<input type="text" name="firstName" placeholder="">
<?php echo $fnameErr;?>
<button type="submit" class="signupbtn" name="submit">Submit</button>
Here's my PHP code:
<?php
$fnameErr = "";
$fname = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstName"])) {
$fnameErr = "Name is required";
}
else {
$fname = test_input($_POST["firstName"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
I know the PHP code works, because if I delete the JS validation, it works as intended. I appreciate the help.
Please let me know if I need to add any extra information. Also, this hasn't been my first stop. I've been googling and trying to figure out how to fix this issue for hours to no avail...
This is the JS function being called (which also works as intended) this is also the shortened version to include only the name, the rest works the same, more if statements:
function validateForm() {
"use strict";
var fn = document.forms.myForm.firstName.value;
var ln = document.forms.myForm.lastName.value;
var em = document.forms.myForm.email.value;
var phone = document.forms.myForm.phone.value;
var pass = document.forms.myForm.psw.value;
var pass2 = document.forms.myForm.psw2.value;
if (fn === "") {
window.alert("First name must be filled out");
return false;
}
}
<input type="text" name="firstName" required>
You don't need any JavaScript.
Furthermore:
<form action="" method="post">
You don't need to specify the action if you're posting back to the current page. Using $_SERVER['PHP_SELF'] is potentially a vulnerability if you're not careful, and also breaks "pretty URLs" if you have them.
As said by #Niet The Dark Absol you can use the required but if you insist you can add e.preventdefault to prevent form from submitting in case of errors. We can elaborate properly if we can have a glimpse at your Javascript function.
You should change your onsubmit part and remove the onclick. Also your form is not valid as there is no action.
document.getElementById('myForm').addEventListener('submit',validateForm);
function validateForm(e) {
"use strict";
console.log(document.forms.myForm.firstName.value);
var fn = document.forms.myForm.firstName.value;
if (fn === "") {
window.alert("First name must be filled out");
e.preventDefault();
return false;
}
}
<form action="https://stackoverflow.com/" method="post" id="myForm">
<input type="text" name="firstName" >
<input type="submit">
</form>
There was a couple mistakes... But mainly what cause your problem is that onsubmit="return validateForm()". I also added e.preventDefault() it is to prevent the form submission if there is an error.
In javascript, I´m supposed to create a function that checks if a textfield within a form is empty. If it is and the user clicks submit, the user will not be allowed to proceed. I found what I considered a suitable solution to this on w3schools (http://www.w3schools.com/js/js_validation.asp). I´ve checked more times than I can remember and everything seems to be in order, but it´s not working!! Instead, when the submit button is clicked, the website calls a different function I have in javascript which it is not supposed to do...
HTML code
Other code
<p>
<form method="post" name="form" action="" onsubmit="return validateName()">
<label for="fullName">Namn: </label><input id="fullName" class="text" name="namn" type="text"> </input>
</p>
<p>
<label for="epost">Epost: </label><input id="epost" class="text" name="epost" type="email"> </input>
</p>
<p>
<input id="submit" type="submit" value="Skicka"> </input>
</p>
</form>
Other code
Javascript code
function validateName() {
var a = document.forms["form"]["namn"].value;
if (a == null || a == "") {
alert("Name required");
return false;
} else {
return true;
}
}
Clicking the submit button should call this function above (validateName), but instead it calls this function:
function alert() {
return confirm("Do you really wish to leave this website?");
}
I´ve looked through my code multiple times and can´t find anything that seems to be out of place. Can any of you find anything wrong? And maybe suggest a solution that solves my problem so my function will work properly?
I would be very grateful if someone could help me resolve this matter!
alert is a predefined function that you are using correctly once and incorrectly the second time. Simply change the name of YOUR alert function to something else, or just use confirm as it was intended and leave out the function alert part
Correct:
alert("Name required");
Incorrect:
function alert() {
return confirm("Do you really wish to leave this website?");
}
one solution is to do this:
function confirm_leaving(){
return confirm("Do you really wish to leave this website?");
}
That's because you are calling the alert function within your validateName function.
function validateName() {
var a = document.forms["form"]["namn"].value;
if (a == null || a == "") {
alert("Name required"); //<- remove this
return false;
} else {
return true;
}
}
Well i think you may put this code instead of this : function validateName() {
To correct this just put a this command :
function validateName(this) {
I can't get a form to validate no matter what I try, so I have dumbed it down alot to see if I could get ANYTHING to work, and still when I submit the form the javascript does not validate, and simply sends me to the next page no matter what. You guys see anything wrong??
HTML
<form id="myform" action="/" method="post" onsubmit="return Validate()">
<input id="form_name" type="text" name="name" placeholder="Name" />
<div id="error">Name too short</div>
<input type="submit" id="submit" name="submit" value="Enter" />
JAVASCRIPT IN HEAD
<script language="JavaScript" type="text/javascript">
function Validate() {
if (form.name.value == "") {
$('#error').show();
return false ;
}
return true ;
}
</script>
And in the CSS I have the display for the #error div set to none.
Ultimately I want to check that the user entered at least 4 characters in the text input field, if they didnt then I don't want the form submitted but rather show the error message. But for now I'm just checking to see if its empty to see if I can get anything to work. Any ideas?
First of all remove language from the script tag, it's deprecated.
Then you should not load your script in the head section. Instead put it where body ends to ensure that the HTML has loaded.
Also in your validate function you don't seem to actually target the correct ID's.
Use this:
function Validate() {
if ($('#form_name').val() === '') {
$('#error').show();
return false ;
}
return true ;
}
Replace your javascript for this
function Validate() {
// Use form_name instead of form.name
if (form_name.value == "") {
// This line will break if you do not have jquery.
$('#error').show();
return false ;
}
return true ;
}
Define IDs for tags and use jQuery to get those tags and check their values. For example, if the name tag had id="form_name" you could do something like this:
if ($("#form_name").val() == ""))
$('#error').show();
On the other hand, I recommend you to check jQuery Validate plug-in which is great for validating forms:
http://jqueryvalidation.org/
Instead of
if (form.name.value == "") {
use:
var nameField=document.getElementById("form_name");
if (nameField.value == "") {
Let me know if this works.
This question already has answers here:
prevent form from POSTing until javascript code is satisfied
(4 answers)
Closed 9 years ago.
Is there a way that I can use javascript to prevent a form from runing a php script. For example something like this:
<form action="somePage.php" method="POST>
<input type= "text" class= "field" name = "blah">
<input type="submit" value="Send" >
</form>
I know how to validate what's in that text box using javascript, but I want to prevent the somePage.php to run if the text box is empty. I haven't really tried anything cause I just don't know how to do it.
Hope you guys understand my problem.
Thanks
You can attach function to submit event of the form:
document.getElementById('form-id').addEventListener("submit", function(e){
var field1 = getElementById('field1').value;
if(field1=='' || field1 == null){
e.preventDefault();
alert('Pls fill the required fields.');
return;
}
return true;
});
OR
Below solution uses inline js:
If you want to run your js function before submitting the form to php script, you can use onsubmit attribute of the form,
<form id="form-id" action="somePage.php" method="POST" onsubmit="return formSubmit();">
<input type= "text" class= "field" id="field1" name = "blah">
<input type="submit" value="Send" >
</form>
In formSubmit function you can check the value of the input, if its empty or not, and if empty, then you can just return false;
var formSubmit = function(){
var field1 = getElementById('field1').value;
if(field1=='' || field1 == null)
return false;
else
return true;
}
You simply need to return false for your submit event by grabbing the form (I used querySelector because you have no IDs or classes), and adding a submit listening event to return false.
var x = document.querySelector("[method='POST']");
x.addEventListener("submit",function() {
return false;
});
Use this code to prevent form from submitting:
var first_form = document.getElementsByTagName('form')[0];
first_form.addEventListener('submit', function (e) {
e.preventDefault(); //This actually prevent browser default behaviour
alert('Don\'t submit');
//Do your stuff here
}, false);
Better read docs
you could in your somePage.php have this be a clause somewhere new the beggin:
if(empty($_POST['blah'])){
die();
}
or the inverse of
if(!empty($_POST['blah'])){
//do what this php is supposed to
}
else{
//display error
}
this will prevent your php from running if that field is not filled out.
Personally I return them to the same page setting some error on the page.
<html>
<head>
</head>
<body>
<form class="form-horizontal cmxform" id="validateForm" method="get" action="../../course_controller" autocomplete="off">
<input type="text" id="course_name" name="course_name" placeholder="Enter Course Name..." class="row-fluid" required onkeyup="javaScript:validate_course_name();">
<label id="course_name_info" style="color:rgba(255,255,255,0.6);font-size:13px">
</label>
<button type="submit" name="user_action" value="add" class="btn btn-primary" onClick="javaScript:validate();" >Save</button>
<button type="reset" class="btn btn-secondary">Cancel</button>
</form>
<script type="text/javascript">
/**** Specific JS for this page ****/
//Validation things
function validate_course_name(){
var TCode = document.getElementById('course_name').value;
if( /[^a-zA-Z1-9 _-]/.test( TCode ) ) {
course_name_info.innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
return false;
}
else
{
course_name_info.innerHTML=" ";
return true;
}
}
function validate(){
validate_course_name();
}
</script>
</body>
</html>
So this the code ...I am applying alpha numeric validation on one field but even if i give invalid input like some other characters the form is getting submitted where am i doing it wrong?
i am very new to this web so any help will be appreciated:)
There are several issues here. First, you are never returning the result, so even if the function results in false, it is not returned to the form so the form goes on its merry way. To fix, you can add an onsubmit to the form tag, or even better attach an onsubmit event to the form.
onsubmit="return validate();"
Second, you only need the one function, calling a function from another function is not necessary here, and results in an additional level of difficulty since you will need to return the result to the wrapper function, which will then need to return that result to the form.
//Validation things
function validate() {
var TCode = document.getElementById('course_name').value;
if (/[^a-zA-Z1-9 _-]/.test(TCode)) {
course_name_info.innerHTML = "Please Enter Only Alphanumeric or _,-,' ' ";
return false;
} else {
course_name_info.innerHTML = " ";
return true;
}
}
Here is a working fiddle of your example: http://jsfiddle.net/duffmaster33/nCKhH/
Your validate() function should return the result of the validation. Currently the result of validate_course_name is discarded. In other words, it should look something like this
function validate(){
return validate_course_name();
}
Also you might want to move the validation to
<form onsubmit="return validate()" ...
You need to wrap course_name_info with a getElementById
document.getElementById('course_name_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
and then change the style of the label so the font isn't white on white background.
Hope that fixes it.