onclick="validateForm();return false"? - javascript

I came across some code involving a submit button, whose onclick attribute is: onclick="validateForm();return false". For example:
<!DOCTYPE html>
<html>
<head>
<title>form</title>
<script>
function validateForm() {
var name = document.forms["myForm"]["fname"].value;
if (name.trim() == "") {
document.getElementById("demo").innerHTML = "Name must be filled out!";
}
else
document.myForm.submit();
}
</script>
</head>
<body>
<div id="demo" style="color:red"></div><br>
<form name="myForm" action="formHandler.jsp" method="post" target="_blank">
Name: <input type="text" name="fname"> <br>
<input type="submit" value="Submit" onclick="validateForm();return false">
</form>
</body>
</html>
I don't see any difference even if I remove return false in the above example. The return false does not stop the form from submitting as long as the text field is entered. So, what's the purpose of using "return false" immediately after the form is submitted by document.myForm.submit()?

It’s for when the form isn’t submitted by document.myForm.submit(), i.e. in the error case. A better way to write it would probably be to have validateForm control the return value:
function validateForm() {
var name = document.forms["myForm"]["fname"].value;
if (name.trim() == "") {
document.getElementById("demo").innerHTML = "Name must be filled out!";
// Error; cancel the form submission
return false;
}
// Just let the browser continue submitting; no need to .submit()
return true;
}
and
<form name="myForm" action="formHandler.jsp" method="post" target="_blank"
onsubmit="return validateForm()">
Name: <input type="text" name="fname"> <br>
<input type="submit" value="Submit">
</form>

Check Working example :
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.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
<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>

Related

Html Form Unable to Validate Inputs using JavaScript

I am creating an application. The HTML file is like the following:
<!DOCTYPE html>
<html>
<body style="background-color: #ccc">
<script type="javascript">
function validateform(){
alert("Hello");
var firstnameErr="";
var valid = true;
var name = document.myform.fname.value;
var types = /^[a-zA-Z]+$/;
if (fname==null || fname=="") {
firstnameErr = "required";
valid = false;
} else if (!fname.value.match(types)) {
firstnameErr = "format error";
valid = false;
}
return valid;
}
</script>
<form name="myform" method="post" onsubmit="return validateform()" action="/Project/ViewList.php">
Firstname : <input type="text" name="fname" placeholder="First name" maxlength="20">
<span class="error">*
<script type="javascript">
document.write(firstnameErr);
</script>
</span>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
When I click on the submit button, it straightaway redirects to "ViewList.php" without seeming to run validatefom(). I added the alert() to check whether the function is executing or not. I want my form to submit only when it meets the validation requirements, not when valid is false.
Besides Typo errors, The main problem that I found is your script is not get executed and your validateform() method is not available. It happened because your script tag type attribute is not correct <script type="javascript">
To make it work you need to change it to this
<script type="text/javascript">
And please change your validation method validateform() as it has too may typo.
What is wrong with the code is that the OP is validating the old-fashioned way with an HTML5 form. Prior to HTML5, you had to use JavaScript for front-end validation; now things are much simpler and easier, too. Of course, the OP would replace the value of the action in the following example with the desired URL.
Note: there were errors in the OP's code, but if you get rid of the JavaScript and code the HTML making sure to add the following to the text input:
required pattern="[a-zA-Z]+"
then the form validates. In other words, you don't have to work so hard when you use HTML5 for form validation :)
<form id="myform" name="myform" method="POST" action="https://www.example.com">
<label for="fname">Firstname</label>: <input name="fname" placeholder="First name" maxlength="20" required pattern="[a-zA-Z]+">
<input type="submit" name="submit" value="Submit">
</form>
For those who prefer to do things the old-fashioned way, see this revision of the OP's code. Note: it uses a minimum of variables, employs short-cuts for less verbosity, and is organized with functions. Also, it is kind to the user's hands, too.
The way you have done you will never be able to use document.write to output anything, use this, working for me:
<!DOCTYPE html>
<script>
function validateform(){
alert("Hello");
var valid = true;
var fname = document.myform.fname.value;
var types = /^[a-zA-Z]+$/;
if (fname==null || fname=="") {
firstnameErr = 'required';
valid = false;
} else if (!fname.match(types)) {
firstnameErr = 'format error';
valid = false;
}
document.getElementById('msg').innerHTML = firstnameErr;
return valid;
}
</script>
<form name="myform" method="post" onsubmit="return validateform()" action="/Project/ViewList.php">
Firstname : <input type="text" name="fname" placeholder="First name" maxlength="20">
<span class="error">* <label id='msg'></label> </span>
<input type="submit" name="submit" value="Submit">
</form>
</body>
It looks you have a series of typo in your code,
try this
<!DOCTYPE html>
<html>
<body style="background-color: #ccc">
<script>
function validateform() {
var firstnameErr = "";
var valid = true;
var name = document.myform.fname.value;
var types = /^[a-zA-Z]+$/;
if (name == null || name == "") {
firstnameErr = "required";
valid = false;
} else if (!name.match(types)) {
firstnameErr = "format error";
valid = false;
}
return valid;
}
</script>
<form name="myform" method="post" onsubmit="return validateform()" action="/Project/ViewList.php">
Firstname : <input type="text" name="fname" placeholder="First name" maxlength="20">
<span class="error">*
<script>
document.write(firstnameErr);
</script>
</span>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>

How to validate input using external javascript?

Im doing app based on phonegap. Im trying t validate my input with external javascript file. But getting error validateForm is not defined at HTMLFormElement.onclick. What's wrong with my code?
HTML
<div data-role="page" id="page1">
<div data-role="header">
Back
<h2>Add New</h2>
</div>
<!-- main -->
<div data-role="main" class="ui-content">
<form name="myform" onclick="return validateForm()" method="post">
Name : <input type="text" name="myname" id="my_name" placeholder="Enter Your Name" >
<button type="button" id="but_submit">Submit</button>
</form>
</div>
<!-- footer -->
<div data-role="footer">
<h2>mine</h2>
</div>
</div>
Code from external javascript
function validateForm(){
var x = document.forms["myform"]["myname"].value;
if (x==null || x==""){
alert("enter name");
return false;
} else{
return true;
}
}
Use onsubmit, and by passing this from the event handler, you can use it instead for document.forms[....]
HTML
<form name="myform" onsubmit="return validateForm(this)" method="post">
Script
function validateForm(theform){
var x = theform["myname"].value;
if (x==null || x==""){
alert("enter name");
return false;
} else{
return true;
}
}
And by using event listeners it can be even more maintainable (and unobtrusive)
HTML
<form name="myform" method="post">
Script
window.addEventListener('load', function() { /* fires when page been loaded */
document.querySelector('[name="myform"]').addEventListener('submit', function(e) {
var x = e.target["myname"].value;
if (x==null || x==""){
alert("enter name");
return false;
} else{
return true;
}
});
});
You should use the onchange event because onclick triggers before having a chance to actually write something in the input.
This way you can deal with the validation after the value has changed and not wait for the form to be submitted.
Or if you want to validate just before submit you can use the onsubmit event like LGSon suggested.
function validateForm() {
var x = document.forms["myform"]["myname"].value;
if (x == null || x == "") {
alert("enter name");
return false;
} else {
console.log(true, x);
return true;
}
}
<form name="myform" onchange="return validateForm()" method="post">
Name : <input type="text" name="myname" id="my_name" placeholder="Enter Your Name">
<button type="button" id="but_submit">Submit</button>
</form>
Use below html code:
<form name="myform" onsubmit="return validateForm()" method="post">
Name : <input type="text" name="myname" id="my_name" placeholder="Enter Your Name" >
<button type="button" id="but_submit">Submit</button>
</form>

Validate on submit button got issue

Here is my code example
<form action="next2.php" method="post" name="next2" id="next2" onsubmit="return submitForm();">
Below is my function
<script type="text/javascript">
function submitForm()
{
var name = document.getElementById("name").value;
return false;
}
</script>
On press, the form still submit, but if i change
onsubmit="return false;"
then the form won't submit, how do I use the function to return false as i need do some if else validation
<script type="text/javascript">
function submitForm() {
return false;
}
</script>
<form
action="next2.php"
method="post"
name="next2"
id="next2"
onsubmit="return submitForm();"
>
submit is already a function for the form, you should call your JavaScript function something different, for instance submitForm as in the above.
just remove the semicolon in your function and place a alert in your function to make sure whether the function is called first.and then try to add validation
I like to make an invisible button for the actual submit which is only triggered after form validation:
function validate() {
var valid = true;
$.each($('input'), function(){
valid = valid && $(this).val().length > 0;
})
if (valid) {
$('#realSubmit').click();
} else {
alert('Please fill out all fields!');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="next2.php" method="post" name="next2" id="next2" onsubmit="return submit();">
<input type="text" placeholder="Enter Name" />
<input type="password" placeholder="Enter Password" />
<button type="button" onclick="validate()">Submit</button>
<button type="submit" id="realSubmit" style="display:none"></button>
</form>

Javascript form validation not empty or no whitespaces

I'm trying to validate a form I'm creating and can't seem to understand how this works. I'm trying to make sure the field isn't empty or contains no white-spaces I have validated it server side but not client side.
Could someone please show me the code like below to validate against being empty or having no white-spaces?
I see these below and this is what I thought they did:
x===null // means if field is empty
x==="" // on trying this means if the field is empty
x===" " // and this checks if there is 1 white space
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x===null || x===""|| x===" ") {
alert("First name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
You can do this using javascript trim() function.
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x.trim()==null || x.trim()==""|| x===" ") {
alert("First name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>

Simple JavaScript login form validation

Just a really simple login and redirect, but the script doesn't fire since I changed the button input type to 'submit' and the onClick event to onSubmit. All is does now is just add the username and password as a string to the url.
<form name="loginform">
<label>User name</label>
<input type="text" name="usr" placeholder="username">
<label>Password</label>
<input type="password" name="pword" placeholder="password">
<input type="submit" value="Login" onSubmit="validateForm();" />
</form>
<script>
function validateForm() {
var un = document.loginform.usr.value;
var pw = document.loginform.pword.value;
var username = "username";
var password = "password";
if ((un == username) && (pw == password)) {
window.location = "main.html";
return false;
}
else {
alert ("Login was unsuccessful, please check your username and password");
}
}
</script>
The input tag doesn't have onsubmit handler. Instead, you should put your onsubmit handler on actual form tag, like this: <form name="loginform" onsubmit="validateForm()" method="post"> Here are some useful links:
JavaScript Form Validation
Form onsubmit Event
For the form tag you can specify the request method, GET or POST. By default, the method is GET. One of the differences between them is that in case of GET method, the parameters are appended to the URL (just what you have shown), while in case of POST method there are not shown in URL.
You can read more about the differences here.
UPDATE:
You should return the function call and also you can specify the URL in action attribute of form tag. So here is the updated code:
<form name="loginform" onSubmit="return validateForm();" action="main.html" method="post">
<label>User name</label>
<input type="text" name="usr" placeholder="username">
<label>Password</label>
<input type="password" name="pword" placeholder="password">
<input type="submit" value="Login"/>
</form>
<script>
function validateForm() {
var un = document.loginform.usr.value;
var pw = document.loginform.pword.value;
var username = "username";
var password = "password";
if ((un == username) && (pw == password)) {
return true;
}
else {
alert ("Login was unsuccessful, please check your username and password");
return false;
}
}
</script>
You can do two things here either move the onSubmit attribute to the form tag, or change the onSubmit event to an onCLick event.
Option 1
<form name="loginform" onSubmit="return validateForm();">
Option 2
<input type="submit" value="Login" onClick="return validateForm();" />
<!DOCTYPE html>
<html>
<head>
<script>
function vali() {
var u=document.forms["myform"]["user"].value;
var p=document.forms["myform"]["pwd"].value;
if(u == p) {
alert("Welcome");
window.location="sec.html";
return false;
}
else
{
alert("Please Try again!");
return false;
}
}
</script>
</head>
<body>
<form method="post">
<fieldset style="width:35px;"> <legend>Login Here</legend>
<input type="text" name="user" placeholder="Username" required>
<br>
<input type="Password" name="pwd" placeholder="Password" required>
<br>
<input type="submit" name="submit" value="submit" onclick="return vali()">
</form>
</fieldset>
</html>
<form name="loginform" onsubmit="validateForm()">
instead of putting the onsubmit on the actual input button
Add a property to the form method="post".
Like this:
<form name="loginform" method="post">
function validate() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username == null || username == "") {
alert("Please enter the username.");
return false;
}
if (password == null || password == "") {
alert("Please enter the password.");
return false;
}
alert('Login successful');
}
<input type="text" name="username" id="username" />
<input type="password" name="password" id="password" />
<input type="button" value="Login" id="submit" onclick="validate();" />

Categories