How to validate input using external javascript? - 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>

Related

onclick="validateForm();return false"?

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>

Jquery: On form submit validate then allow default operation to continue

Wondering, is there a way to make a form execute default operation after preventingDefault and validating form fields.
$('#form').submit(function (e) {
e.preventDefault();
var isValid = true;
var name = $('#name').val();
if (empty(name)) {
isValid = false;
}
$(this).submit() // This will cause a stack overflow :)
});
After I complete the form validation I want to proceed as normal,
I thought of using onClick on the submit button, but users can trigger submit by hitting on the enter key, which I want to allow. Reason why I want to do this is so that the server can perform its operations like redirecting.
I am writing you a small example.
$(document).ready(function(){
$("#control_form").on("keyup", function(event){
post_control();
});
});
var post_control = function(){
var user_name = $("#user_name").val();
if ( user_name==null || user_name=="" || user_name.length < 4 )
$('.error').html("Username can not be less than 4 characters!");
else
{
$('.error').empty();
$('#control_form').removeAttr('onsubmit');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div id="users_form">
<form name="form" id="control_form" action="post_form" method="post" onsubmit="return false;">
<label>User Name:</label>
<input type="text" id="user_name" name="user_name">
<input type="submit" value="Save">
</form>
<div class="error"></div>
</div>
Instead of using preventDefault, you can return true at the end of the function.
If you want to prevent the submission, you can return false.
Here's an example using your code. If you try to submit the form with an empty field, it won't submit. If you fill the field, it will:
$("#form").submit(function() {
var name = $("#name").val();
if (!name) {
$(".form-group").addClass("has-danger");
alert("Field is blank. Submit will be prevented.");
return false; // no submission
}
alert("Field is filled. The form will submit.");
return true; // form submits
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='form'>
<div class="form-group">
<label class="form-control-label" for="name">Name</label>
<input type="text" class="form-control" id="name">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
CodePen Demo
check this it works.I tested it.
$(document).ready(function(){
$('#form1').submit(function (e) {
if($('#name').val() == ''){
alert('Name is empty');
return false;
}
$(this).submit();
});
});

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 custom validation not working

Here is my code :
<script type="text/javascript">
function submitform() {
if(document.getElementById('name').value=='') {
alert('Please enter a name');
return false;
}
}
</script>
<form action="mail.php" method="post" onsubmit="submitform();">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit">
</form>
as expected, the form when submitted should call the submitform function, and if the name field is blank, it should return false and give an alert.
But, it just goes through.
Any explainations?
You need to call the function with return, so that the false value prevents default action (form submission)
<form action="mail.php" method="post" onsubmit="return submitform();">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit">
</form>
You need to stop a little.
You can use onSubmit, but it's best to delete your input submit and put a button.
Then on button click you can do what you want and eventually submit the form
Form:
<form action="mail.php" method="post" id="mailForm">
<input type="text" id="name" name="name" placeholder="name">
<button id="submitMailForm">Submit</button>
JS:
$( document ).on( "click", "#submitMailForm", function(e) {
//My control Here
//If all ok
$("#mailForm").submit();
});
You can use jquery instead of javascript for this kind of validation is will be very easy to implement.
<form action="mail.php" method="post">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit" id="submit">
</form>
<script>
$(document).ready(function(){
$("#submit").click(fucntion(e){
if($("#name").val() == ""){
alert("Name is empty");
e.preventDefault();
}
});
});
</script>
And dont forget to add jquery library before the script tag.
You need to change your onSubmit attribute as follows
onsubmit="return submitform();"
So your html look like this
<form action="mail.php" method="post" onsubmit="return submitform();">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit">
</form>
To cancel submission, the listener needs to return true or false. Also, if the function validates the fields, far better to name it for what it does rather than when it does it so call it something like "validateForm".
Also, giving a control a name of "name" masks the form's own name property. While that doesn't matter here, in general it's not a good idea to give any form control a name that is the same as a standard property of a form (e.g. "submit" or "reset").
So you might end up with something like:
<script>
function validateForm(form) {
if (form.personName.value == '') {
alert('Please enter a name');
return false;
}
}
</script>
<form ... onsubmit="return validateForm(this);">
<input type="text" name="personName">
<input type="submit">
</form>
<script type="text/javascript">
function submitform(event) {
if(document.getElementById('name').value=='') {
alert('Please enter a name');
event.preventDefault();
return false;
}
}
</script>
<form action="mail.php" method="post" onsubmit="submitform(event);">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit">
</form>
You need to prevent default of submit. In JS return false does not stop the propagation of the "submit" function (with frameworks can be different).
I suggest you to read:
event.preventDefault() vs. return falseenter link description here
just try this script
function submitform() {
var x = document.forms["fname"].value;
x = x.trim(); // Remove white spaces
if (x==null || x=="") {
alert("First name must be filled out");
return false;
}
}

Forward page request using JavaScript functions return values?

Here is the related part of code:
<form id="frmDemo" name="frmDemo" action="temp.jsp" method="post" >
<div>
<hr/><a name="d2"></a>
<h2>CMS Sign In Page</h2>
<p>Passing parameters to the Web Service:</p>
<label>Your username: </label><input type="text" name="username" id="username" value="elthefar" />
<label>Your password: </label><input type="password" name="password" id="password" value="workandwork" />
<input type="button" value="Sign In" onclick="var r = SignIn(); if (r == 0) document.forms[0].action = 'temp2.jsp'; return true;" />
I want my form to forward to temp2.jsp if SignIn return 0, otherwise to temp.jsp. but the above code doesn't forward to any page.
You can add a onsubmit event to you form like this:
<form id="frmDemo" name="frmDemo" action="temp.jsp" method="post" onsubmit="return myfunction();">
and then use a simple submit button in your form.
<input type='submit' value='Sign In' />
in this case, when you click on submit button, the function will fire and in that function you can do what ever you want to do like this:
<script language='javascript'>
function myfunction(){
var r = SignIn();
if(r == 0)
document.forms[0].action = 'temp2.jsp';
return true;
}
</script>
Did you mean to use input type="submit"? Or call document.forms[0].submit();?
Change your form to this
<form id="frmDemo" name="frmDemo" method="post">
And change button to submit
<input type="submit" name="Submit" onClick="Validate()" value="Submit" />
And use your javaScript
<script language='javascript'>
function Validate(){
var r = SignIn(); // assuming, you have some implementation for SignIn() method
var frm = document.getElementById("frmDemo") || null;
if(frm) {
if(r != 0)
{
frm.action = 'temp.jsp';
}else{
frm.action = 'temp2.jsp';
}
}
}
</script>

Categories