I am trying to use JavaScript to validate forms but if the form doesn't validate, I don't want the form to be sent to the "action" page.
The validator:
<script>
function formSubmit()
{
document.getElementById("signup_form").submit();
var x=document.forms["signup_form"]["tname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
</script>
The form itself:
<form action="some_file.php" method="post" id="signup_form" name="signup_form" onsubmit="return formSubmit()">
But all this does is if the tname field empty, it will return an alert but as soon as the user hits ok, the form then redirects to some_file.php. What have I missed here?
The submit button:
Signup
So what have I missed? How do I avoid this in the future?
You have the wrong execution of statememts. You are submitting the form before validating. Move this statement below the if statement
document.getElementById("signup_form").submit();
further to this. you are calling formSubmit() at two places, form tag and a tag doing it once is fine.
UPDATED CODE:
<html>
<head>
<title></title>
<script>
function formSubmit()
{
var x=document.forms["signup_form"]["tname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
document.getElementById("signup_form").submit();
}
</script>
</head>
<body>
<form action="some_file.php" method="post" id="signup_form" name="signup_form" onsubmit="return formSubmit()">
<input type="text" name="tname" />
Signup
</body>
</html>
DEMO
Try this:
function formSubmit()
{
var x=document.forms["signup_form"]["tname"].value;
if (x=="")
{
alert("First name must be filled out");
return false;
}
return true;
}
*Changes made to your code: *
- There is no need for formSubmit to try to submit the form! Just perform the validation checks and return true if you want the submission to proceed or false otherwise.
Also you do not need to check for the x == null case. If the textbox is empty, its value will be "".
What might be needed though is a check that x does not just contain spaces. If you do not care about supporting older browsers you can use the new Javascript trim function. If you care about backwards compatibility, either try one of the many javascript libraries that offer trim or the following:
function formSubmit()
{
var x=document.forms["signup_form"]["tname"].value.replace(/^\s+|\s+$/g, '');
if (x=="")
{
alert("First name must be filled out");
return false;
}
return true;
}
If I just wanted to avoid submitting spaces I would have left the var x= bit as it was and added the replace in the check making it if(x.replace(/\s/g, '') == ""). However, I also want to trim the input so that if the user enters " user1" or "user1 " the form will send "user1".
You can see the three different versions versions working here:
http://jsfiddle.net/9LPfb/2/
http://jsfiddle.net/9LPfb/3/
http://jsfiddle.net/9LPfb/6/
you have problem with your program flow .
do validation before the submitting form.
there is no use of validating after submitting, i think you have mistakenly made it.
just submit after validation.
try:
function formSubmit() {
var x=document.forms["signup_form"]["tname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
else {
return true;
}
}
You already had all the code. It was becos of wrong execution.
<script>
function formSubmit()
{
var x=document.forms["signup_form"]["tname"].value;
if (!x){
alert("First name must be filled out");
return false;
}
return true;
}
</script>
<form action="some_file.php" method="post" id="signup_form" name="signup_form">
Signup
in your function just remove this line
document.getElementById("signup_form").submit();
and add it after the if condition
or rewrite the function like the one below
function formSubmit()
{
var x=document.forms["signup_form"]["tname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}else
return true;
}
Contact Form
function empty() {
var x,y;
x = document.forms["ff"]"name"].value;
y = document.forms["ff"]["surname"].value;
if(x=="" ||x==null){
alert("Enter your name");
return false;
}else if(y==""){
alert("Enter your surname");
return false;
}else{
alert('Data is sending');
return true;
}
};
In the html:
<form method="POST" action="formdata.php" name="ff"onsubmit="return empty()">
<table>
<tr>
<td>Enter Your Name : <input type="text" name="name" maxlength="30" size="40" id="na" ></td>
</tr>
<tr>
<td>Enter Your Surname : <input type="text" name="surname" maxlength="30" size="40" id="sna"></td>
</tr>
<tr>
<td>
<input type="submit" name="formsubmit" value="submit" >
</td>
</tr>
</table>
</form>
Related
Okay so I know this is probably a headache for most of you but i'm having trouble figuring this out as javascript is not my strong suit.
I'm trying to basically get this one page to load if username and password is not blank but if it is blank I want it to alert to me (specifically window.alert()) that I have not inputted username and/or password.
I cannot seem to figure it out so here it is.
<button type="submit" id="enterButton" onclick="newPage()"><strong>Enter</strong></button>
there is my button where I put my function on
var username = getElementById("userName");
var password = getElementById("passWord");
function newPage() {
if(username.val().length==0 || password.val().length==0){
alert("please enter valid information");
return location.href = "newPage.html";
}
else{
location.href = "newPage.html";
}
}
and here is my failed attempt to initialize my idea.
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if (password==null || password==""){
alert("password can't be blank");
return false;
} else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
<html>
<body>
<body>
<form name="myform" method="post" action="http://www.javatpoint.com/javascriptpages/valid.jsp" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
</body>
</html>
Try to check first if you can get the value of your username. If you're using plain javascript, you should use document.getElementById("userName").value.
I've got the following simple test to validate the input on the form when it is submitted by clicking the "submit" link. Unfortunately, it doesn't validate the form.
<form id="testform" action = "?blah" onsubmit="return validateForm()">
<input type="text" name="testinput" >
Submit
</form>
<script>
function validateForm() {
var x = document.forms["testform"]["testinput"].value;
if (x == null || x == "") {
alert("Field must be filled out");
return false;
}
}
</script>
If I replace submitting with a button instead of a link then it validates the form properly. But how can I ensure it validates when I am using a link to submit as in the above example?
Try creating a function that triggers the validation when clicking on the link.
Example:
<form id="testform" action = "?blah" onsubmit="return validateForm()">
<input type="text" name="testinput" >
Submit
</form>
<script>
function validateForm() {
var x = document.forms["testform"]["testinput"].value;
if (x == null || x == "") {
alert("Field must be filled out");
return false;
}
}
function submitForm() {
if (validateForm()) {
document.getElementById('testform').submit();
}
}
</script>
Note: I would highly recommend decoupling your JavaScript from your HTML, but that's outside the scope of your question.
Here comes a jQuery style way of doing it.
<form id="testform" action = "?blah" onsubmit="return validateForm()">
<input type="text" name="testinput" />
Submit
</form>
<script type="text/javascript">
function validateForm() {
if ($.trim($("[name=testinput]").val()) == "") {
alert("Field must be filled out");
return false;
}
}
</script>
This works for me. It takes advantage of a variable and of an assigned method to testform:
<form id="testform" action = "?blah" onsubmit="return formValid">
<input type="text" name="testinput" >
Submit
</form>
<script>
var formValid = false;
document.getElementById('testform').onsubmit = function(){
console.log('submit');
formValid = validateForm();
};
function validateForm() {
var x = document.forms["testform"]["testinput"].value;
if (x == null || x == "") {
alert("Field must be filled out");
return false;
}
}
</script>
How can I check if a input field is empty in JavaScript when submitting the form?
html:
<input type="text" name="start_name" id="start_name">
Refer to http://www.w3schools.com/js/js_form_validation.asp
Have your form tag as
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
Next, have a javascript function
<script>
function validateForm()
{
var x=document.forms["myForm"]["start_name"].value;
if (x==null || x=="")
{
alert("Start name must be filled out");
return false;
}
}
</script>
var start_name = document.getElementById('start_name');
if( start_name.value.length > 0 ){
// Then there is something there.
}
Try.
<script type="text/javascript">
function checkme()
{
var inputVal = document.getElementById("start_name").value;
if(inputVal == "")
{
//code
}
}
</script>
<form action="" method="post" onSubmit = "checkme();">
<input type="text" name="start_name" id="start_name">
</form>
Just checking 'if (x==null || x=="")' is not enough to validate empty text box. Go for RegEx to check empty text box.
/^\s*[0-9a-zA-Z][0-9a-zA-Z ]*$/
Ensures that at least one character is not whitespace and is of one of the allowed characters.
Use /[a-z]/i as this regex will only match if there is at least one alphabetical character.
<form action="someActionUrl" onsubmit="return validate('first_name')">
<input id="first_name" name="first_name" />
</form>
<script>
function validate(inputId){
var val = document.getElementById(inputId).value;
if(val.length>0){
// do something
return true;
}
return false;
}
</script>
try this:
var x = document.getElementById("start_name");
if(x.value== "")
{
//your restriction code comes here
}
else
{
//go ahead!
}
Note: please check for syntax if its proper.i am writing the code here directly,haven't checked it on IDE.
I'm trying to validate my values for alphabets and numberic as well as checking from database. I have created a function of validation and declaring my onclick button with validation function.
Function:
<script>
function validate()
{
var StudentID= document.getElementById('StudentID').value;
var StudentName = document.getElementById('StudentName').value;
var StudentAdd = document.getElementById('StudentAdd').value;
if(StudentID.length ==0 || StudentName.length ==0)
{
alert("Please do not leave any blanks");
return false;
}
else
{
if(isNumeric(StudentID))
{ alert("correct") }
else { alert("Numbers only!"); return false;}
alert("Correct correct");
}
return true;
}
</script>
Sample Form:
<form id="Student" name="Student" method="post" action="nextpage.php">
<input name="StudentID" type="text" id="StudentID" value="<?php echo $StudentID?>"/>
<input name="StudentName" type="text" id="StudentName" value="<?php echo $StudentName?>"/>
<input name="StudentAdd" type="text" id="StudentAdd" value="<?php echo $StudentAdd?>"/>
<input type="submit" name="submit" value="Submit" onclick="return validate();"/>
</form>
I have already declared return validate function instead of calling my nextpage.php. But nothing popup for any alert. Kindly advise.
Thanks
Try including your scripts after the body tag to make sure it only references elements after it has already been loaded. Then put return true inside the else statement.
function validate()
{
var StudentID= document.getElementById('StudentID').value;
var StudentName = document.getElementById('StudentName').value;
var StudentAdd = document.getElementById('StudentAdd').value;
if(StudentID.length ==0 || StudentName.length ==0)
{
alert("Please do not leave any blanks");
return false;
}
else
{
if(isNumeric(StudentID))
{ alert("correct") }
else { alert("Numbers only!"); return false;}
alert("Correct correct");
return true;
}
}
Instead of the submit button's onclick, move the function to the form's onsubmit, like:
<form onsubmit="validate()" ...>
For the part of the 'if' statement that returns true you may run into some issues with the alerts() as the browser will be trying to submit the form, but over all it should work.
There is no isNumeric() function in JavaScript (I get Uncaught ReferenceError: isNumeric is not defined). You have to create it on your own: Validate decimal numbers in JavaScript - IsNumeric()
Please help me. The validation is not working:
<script type="text/javascript" src="javascript.js">
function validation()
{
var fname=document.forms["form1"]["fname"].value;
var lname=document.forms["form1"]["lname"].value;
var idnumber=document.forms["form1"]["idnumber"].value;
var email=document.forms["form1"]["email"].value;
var atpos=email.indexOf("#");
var dotpos=email.lastIndexOf(".");
var address=document.forms["form1"]["address"].value;
var phonenumber=document.forms["form1"]["phonenumber"].value;
if (fname==null || fname=="")
{
alert("Name should be entered correctly");
return false;
}
if (lname==null || lname=="")
{
alert("Name should be entered correctly");
return false;
}
if (isNaN(idnumber))
{
alert("Please enter a valid id number");
return false;
}
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Please enter a valid e-mail address");
return false;
}
if(address==null || address=="")
{
alert("Please insert your address");
return false;
}
if (isNaN(phonenumber))
{
alert("Please enter a valid phone number");
return false;
}
}
</script>
<form name="form1" action="validation.php" method="post" onsubmit=" return validation(this);return false">
Firstname:<input type="text" name="fname"><br/>
Lastname:<input type="text" name="lname"><br/>
Nation ID Number:<input type="text" name="idnumber" minlength="8"maxlength="8"><br/>
Email address: <input type="text" name="email"><br/>
Address:<input type="text" name="address"><br/>
Pnone number:<input type="text" name="phonenumber"><br/>
<input type="reset" name="reset" value="reset">
<input type="submit" name="submit" value="submit">
</form>
There are a number of issues with that code:
You really should not use the same <script> element for both calling src="javascript.js" and at the same time declare a function. Use separate elements, like this:
<script type="text/javascript" src="javascript.js"></script>
<script type="text/javascript">
function validation()
{
...
}
</script>
In the <form> element, there's a redundant ;return false. The form will take the value from return validation(this), anything after it will be ignored. Also, no need of ";" when using in-line javascript.
You are passing passing this as argument to the validation() function, but validation is expecting no argument. Should be:
function validation(oForm)
If you are already passing this, why not use it? this is a reference to the element itself, so it is, for the validation function, a reference to the form. So no need to name the form.
<form action="validation.php" method="post" onsubmit="return validation(this)">
And the references in function would be:
function validation(oForm)
{
var fname=oForm["fname"].value;
var lname=oForm["lname"].value;
}
Those changes alone could solve your problem. I'll check the code further to see if there is something else.
EDIT:
I've tested the validation now, and it works. The only required modification is removing the scr=validation.js from your <SCRIPT> tag. Use separate tags for that, as i suggested.
But i strongly suggest you consider the other issues I've mentioned.
Also, other suggestions regarding the validation itself:
For alphanumerical fields, no need to check for null, only "" is enough. You can simply use:
if (lname=="")
First Name and Last Name error messages are the same. That will confuse users.
Avoid testing phone numbers as numeric. Remember "(407) 234-5678" is a perfectly valid phone number, although it will fail your test. Unless you have a strong reason to treat it as numeric (automatic dialing?), leave it as an ordinary, text field.
In the National ID field: There is no minlength in HTML. Only maxlength
isNaN(idnumber) will return true if value is blank. And also if length<8. I assume it is a required field with a required length, so you should use:
if (isNaN(idnumber) || idnumber.length != 8)
{
alert("Please enter a valid id number");
return false;
}
For all your tests, consider trimming the values. Currently, input like " " (blanks only) WILL pass your test. Javascript has no built-in trim function, but it can be done with this:
function trim( texto ) {
return texto.replace(/^\s*|\s*$/g, "");
}
And used like this:
var fname=trim(oForm["fname"].value);
For clarity, use an explicit return true; in validation() after all tests successful.
Here is the suggested code after all changes:
<script type="text/javascript" scr="validation.js"></script>
<script type="text/javascript">
function validation(oForm)
{
var fname = trim(oForm["fname"].value);
var lname = trim(oForm["lname"].value);
var idnumber = trim(oForm["idnumber"].value);
var email = trim(oForm["email"].value);
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
var address = trim(oForm["address"].value);
var phonenumber = trim(oForm["phonenumber"].value);
if (fname=="")
{
alert("First name should be entered");
return false;
}
if (lname=="")
{
alert("Last name should be entered");
return false;
}
if (isNaN(idnumber) || idnumber.length != 8)
{
alert("Please enter a valid id number");
return false;
}
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Please enter a valid e-mail address");
return false;
}
if(address=="")
{
alert("Please insert your address");
return false;
}
if (isNaN(phonenumber))
{
alert("Please enter a valid phone number");
return false;
}
return true;
}
function trim( texto ) {
return texto.replace(/^\s*|\s*$/g, "");
}
</script>
<form name="form1" action="validation.php" method="post" onsubmit="return validation(this)">
Firstname:<input type="text" name="fname"><br/>
Lastname:<input type="text" name="lname"><br/>
Nation ID Number:<input type="text" name="idnumber" maxlength="8"><br/>
Email address: <input type="text" name="email"><br/>
Address:<input type="text" name="address"><br/>
Pnone number:<input type="text" name="phonenumber"><br/>
<input type="reset" name="reset" value="reset">
<input type="submit" name="submit" value="submit">
</form>