Javascript form validation, what is missing? - javascript

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.

Related

Javascript form validation return false error

I'm trying to do a form and while the alert is popping up it is still submitting. How do I get it to stop submitting??
function validate() {
var first = document.register.first.value;
if (first == "") {
alert("please enter your name");
first.focus();
return false;
}
return (true);
}
<body>
<form name="register" action="testform.php" onsubmit="return(validate());">
<input type="text" name="first" />
<button type="submit" />Submit
</form>
</body>
You added the parenthesis on return() then return(validate()) which we use () when calling the function so it might be considering return a custom function which returns undefined and when returned the undefined it ignores and continue the execution.
How ever the validate is called but it's response is not returned to the form.
Fixed version:
<head>
<script>
function validate(e) {
var first = document.register.first.value;
console.log(document.register.first)
if( first == "" ) {
alert( "please enter your name" ) ;
return false;
}
return(true);
}
</script>
</head>
<body>
<form name="register" action="testform.php" onsubmit="return validate()">
<input type="text" name="first" />
<button type="submit" >sbmit</button>
</form>
</body>
You are better of using the required attribute on the front end of things. It will 'force' the user to input text into the input field before it is able to submit. Please note that I put quotation marks around the word 'force', because one can just edit the HTML and circumvent the HTML required attribute. Therefore make absolutely sure that you are validating user input on the PHP side as well.
Many tutorials and examples exist for PHP Form Validation, such as this one from W3Schools and this one from Medium.
<form name="register" action="testform.php">
<input type="text" name="first" required/>
<input type="submit" value="Submit"/>
</form>
You have several bugs in your code.
<button> element is not self-closing
you are calling focus on value of the input instead of the input element which throws exception
function validate() {
var input = document.register.first;
var text = input.value;
if( text == "" ) {
alert( "please enter your name" ) ;
input.focus();
return false;
}
return true;
}
I think the issue is with the button's type="submit". Try changing it to type="button", with an onclick function that submits your form if validate() returns true.
edit: Arjan makes a good point, and you should use required. But this answers why the form was submitting.

Form validation for textfield not working?

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

Check if textbox contains text, if it does then send

I have this email form, with "Sender, "Subject" and "Message".
But i haven't linked it to make sure they have written something, so if someone press the "Send" button without typing anyting, i get a blank email. So i want it to abort the email sending if the textbox is empty, and send it if it contains any text.
code for the send button:
<input type="submit" name="submit" value="Submit" class="submit-button" />
ID for the textbox is: textbox_text
You can use jquery to validate the form like this-
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post">
Sender
<input type="text">
<br/>Subject
<input type="text">
<br/>Message
<input type="text" id="txtMessage">
<br/>
<input type="submit" value="Send" name="btnSend">
</form>
<script type="text/javascript">
$(document).ready(function() {
$("input[name=btnSend]").click(function() {
var msg = $("#txtMessage").val();
if (msg == "") {
alert("Please enter the message");
return false;
}
});
});
</script>
Java Script function
<script type="text/javascript">
function IsEmpty()
{
if(document.forms['frm'].textbox_text.value == "")
{
alert('Message body is empty');
return false;
}
return true;
}
</script>
HTML
<form name="frm">
<input type="submit" name="submit" onclick="return IsEmpty();" value="Submit" class="submit-button" />
</form>
EDIT Check textbox2 in if condition
if(document.forms['frm'].textbox1.value == "" && document.forms['frm'].textbox2.value == "")
I dont know this is your exact answer but it will helps you to validate:
$('#checkSubmit').click(function(){
var chec=$("#textContent").val();
if(chec=="")
alert("Please add your content");
else
alert("successfully submitted");
});
check out this fiddle:
http://jsfiddle.net/0t3oovoa/
You need to check that on server side (with php) and you can also check it on client side(Javascript).
Client side test is good if you want the user to get fast response, but you still need to check it on server side because javascript on your website can ALWAYS be changed by user.
You could also just add "required" on your input elements.
for server side check with php:
<?php
//Check if variables exist
if(isset($_POST['sender']) && isset($_POST['subject']) && isset($_POST['message'])){
//Check if sender value is empty
if(empty($_POST['sender'])){
//If empty, go back to form.Display error with $_GET['error'] in your form page
header('location: backToFormPage.php?error=send');
}
//...
}
//Variables doesn't exist
else{
//Redirect to page or other action
}
?>
You can achieve it two ways:
1. Client Side( Which i recommend) use the form validation to validate the form data if it is empty tell them to fill it. You chose the submit button to trigger validation that is not recommended instead validation is triggered on form submission or on change of input elements(for real-time validation). Anyways below is an example for validation using the click event on submit button.
var validateTextBox = function(textBox) {
var val = textBox.value;
if(val=="") { // Check for empty textbox
return false;
}
return true;
}
documnet.querySelector('#SubmitButton').onclick(function () {
var textbox = document.querySelector("#SubjectORMessage").value;
if(validateTextBox(textbox)){
// Do something to let page know that form is valid
} else {
// Let the user know that he has done something wrong
alert("Please fill the content");
}
})
2. Server Side if unfortunately empty data is send to the server, then use server side validation (Server side validation requires a little more thing to do at more than one place, i.e., html, php/python/perl)

Prevent action attribute from running php script with javascript [duplicate]

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.

jquery, alert when trying to submit empty field in form

I'm sure I must have missed something really obvious, but can't for the life of me see what it is.
I have the below javascript, that (in theory) looks at the form when I click submit, and tells me if I have left the 'RefNo' field blank (in the final form there will be various fields to check, so I have used class='required' to identify them all). But so far, when I click submit, nothing happens (except the form is submitted with the missing data).
I've tried various options that I have found on the internet, and this seemed the most promising.
If anyone can see what I have done wrong it would be really appreciated.
<html>
<head>
<script language="JavaScript" src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
function submitForm()
{
$("#Form1").submit(function()
{
$('.required input').each(function()
{
if ($(this).val() == '')
{
$(this).addClass('highlight');
}
}
);
if ($('.required input').hasClass('highlight'))
{
alert("Please fill in a Ref Number and try again");
return false;
}
}
);
}
</script>
</head>
<body>
<form method="POST" action="test9.php" name="Form1" ID="Form1">
<input TYPE="text" ID="RefNo" NAME="RefNo" VALUE="" size="25px" class="required"></input>
</br>
<p>
<input type="submit" Name="submit" id="submitButton" value="Report History" onClick='submitForm()'></input>
</p>
</form>
</body>
Your selectors should be $('input.required'), not $('.required input').
First, I think you should use Jquery validation plugin.
Ohterwise, this code should work :
-add a onsubmit="return submitForm()" in your Form tag
<form method="POST" action="test9.php" name="Form1" ID="Form1" onsubmit="return submitForm();">
-get rid of the onclick on the submit button
-and here is the submitForm function :
function submitForm() {
var valid = true;
$('input[class="required"]').each(function() {
if ($(this).val() === '') {
alert("One field is empty and try again");
valid = false;
}
});
return valid;
}
But I really recommend jquery.validate.js
Your selector appears to be a bit off:
It should be $('.required')
The way you have it tries to select an input nested inside a Required class.
Instead of doing it on form submit, remove the submit input type from the button and just have it be a regular button.
With that in mind, your javascript should be:
<script>
$('#submitButton').click(function () {
$('input.required').each(function() {
if ($(this).val() == '') {
$(this).addClass('highlight');
}
});
if ($('.highlight').length > 0) {
alert("Please fill in a Ref Number and try again");
return false;
}
else {
$('#Form1').submit();
}
});
</script>
Otherwise, the way that you're doing it, you would have to cancel the event until you run your check for missing data, and then submit the form anyway. This way keeps you from having to cancel the action, as older IE browsers do that differently than the other browsers, and even newer versions of IE. So it makes your code more readable.
The selector should be either $('input.required') or $('#RefNo').
$('#RefNo') is more faster since it uses native getElementById method.

Categories