HTML form validation issue - javascript

<script type="text/javascript">
function check(n,mail,msg)
{
if(name.toLowerCase()== "")
{
alert("Please Enter your name.");
document.getElementById("Name").select();
document.getElementById("Name").focus();
return false;
}
else if(lname.toLowerCase()== "")
{
alert("Please Enter your email.")
document.getElementById("email").select();
document.getElementById("email").focus();
return false;
}
else if(ph == "")
{
alert("Please Enter your Contact Number.")
document.getElementById("message").focus();
return false;
}
return true;
}
=========================================================
<form method="post" name="contact_form" action="contact-form-handler.php">
<p> Your Name:
<input type="text" name="name"></p>
<p>Email Address:
<input type="text" name="email"></p>
<p>Message:
<textarea name="message"></textarea></p>
=========================================================
<input type="button" value="submit" onclick="return check(document.getElementById('name').value,document.getElementById('email').value,document.getElementById('message').value)" />
=========================================================
i am having issues with the HTML validation as when i clicked the button, there is no validation performed.

Instead .. add the validation on the form as below:
<form method="post" name="contact_form" action="contact-form-handler.php"
onsubmit="return validateForm()">
This works 100% times

try this instead for your button:
<input type="button" value="submit" onclick="function(){ check(document.getElementById('name').value,document.getElementById('email').value,document.getElementById('message').value)}" />

<form method="post" name="contact_form" action="contact-form-handler.php">
<p> Your Name:
<input type="text" id="name" name="name"></p>
<p>Email Address:
<input type="text" id="email" name="email"></p>
<p>Message:
<textarea id="message" name="message"></textarea></p>
Use this html markups. It has ids which you have missed.
You are using document.getElementById("name"). But the input field doesn't have id "name". Same for other fields.

Related

JavaScript form validation (check for all letters only)

I'm trying to create one function that will check that a field is not blank, contains only letters and spaces. Validating that the field contains letters and spaces only does not appear to work as anything that's put in the field will return the alert message.
I'm trying to say:
If the name field is NOT letters and spaces then display this alert "...". Else return true.
function validateForm() {
var x = document.forms["newsletterForm"]["name"].value;
if (x==null || x=="") {
alert("Name must not be blank");
return false;
}
else if (x!==/^[A-Za-z ]+$/) {
alert("Name contains invalid characters (letters and spaces only!)")
return false;
}
else {
return true;
}
<form name="newsletterForm" action="#" onsubmit="return validateForm()" method="post">
<label for="name">Name*: </label><br>
<input type="text" name="name" placeholder="Fill in your name"1> <br><br>
<label for="email">E-mail*: </label><br>
<input type="text" name="email" placeholder="Fill in your e-mail address"><br><br>
<label for="comments">Comments (optional): </label> <br>
<textarea rows="5" cols="20" name="comments" placeholder="Leave us a message"></textarea><br>
<input type="submit" value="Submit">
</form>
missing } at end of script and missing ; at else if
and use regex for check only letter and space
function validateForm() {
var regex = new RegExp("^[a-zA-Z ]+$");
var x = document.forms["newsletterForm"]["name"].value;
if (x == null || x == "") {
alert("Name must not be blank");
return false;
} else if (!regex.test(x)) {
alert("Name contains invalid characters (letters and spaces only!)");
return false;
} else {
return true;
}
}
<form name="newsletterForm" action="#" onsubmit="return validateForm()" method="post">
<label for="name">Name*: </label><br>
<input type="text" name="name" placeholder="Fill in your name"> <br><br>
<label for="email">E-mail*: </label><br>
<input type="text" name="email" placeholder="Fill in your e-mail address"><br><br>
<label for="comments">Comments (optional): </label> <br>
<textarea rows="5" cols="20" name="comments" placeholder="Leave us a message"></textarea><br>
<input type="submit" value="Submit">
</form>
Hi You can use regex for that
var regexExp = /^[a-zA-Z\s]*$/;
function validateForm() {
var x = document.forms["newsletterForm"]["name"].value;
alert(x)
if (x==null || x=="") {
alert("Name must not be blank");
return false;
}
else if (!regexExp.test(x)) {
alert("Name contains invalid characters (letters and spaces only!)")
return false;
}
}
<form name="newsletterForm" action="#" onsubmit="return validateForm()" method="post">
<label for="name">Name*: </label><br>
<input type="text" name="name" placeholder="Fill in your name"1> <br><br>
<label for="email">E-mail*: </label><br>
<input type="text" name="email" placeholder="Fill in your e-mail address"><br><br>
<label for="comments">Comments (optional): </label> <br>
<textarea rows="5" cols="20" name="comments" placeholder="Leave us a message"></textarea><br>
<input type="submit" value="Submit">
</form>
I'm thinking that the problem is your use of !==. !== would be looking for an absolute match between x and your regular expression object - that is, is x that regular expression object; not does it match that expression.
What about this:
else if (! /^[A-Za-z ]+$/.test(x))
use typeof
try
if(x == null || typeof x !== 'string')
{
//code here
}
An empty string isn't a valid value to check against.

After file type validation using JS for an HTML Form, control should stay on the same page if invalid

I have an html form where for file types I want only pdf, docx and doc files. I am successfully able to validate, but on click of OK button, I do not want to post the form if it is invalid. Currently, it is going to connection.php. It should only go to connection.php when I have passed the validation successfully.
<form method="POST" action="connection.php" enctype="multipart/form-data" onsubmit="function()">
<input type="text" id="name" name="bookname" placeholder="Book Name" required/>
<textarea cols="25" rows="4" name="bookdesc" placeholder="Book Description" required></textarea>
<input type="text" id="password" name="bookauthor" placeholder="Book Author"/ required>
<input type="file" name="bookfile" id="bookfile" required/>
</form>
<script>
$(document).ready(function () {
$('input[type=file]').change(function () {
var val = $(this).val().toLowerCase();
var regex = new RegExp("(.*?)\.(docx|doc|pdf)$");
if(!(regex.test(val))) {
$(this).val('');
alert('Please select correct file format');
} }); });
</script>
Use onsubmit event:
<form method="POST" action="connection.php" enctype="multipart/form-data" onsubmit="return validate()">
<input type="text" id="name" name="bookname" placeholder="Book Name" required/>
<textarea cols="25" rows="4" name="bookdesc" placeholder="Book Description" required></textarea>
<input type="text" id="password" name="bookauthor" placeholder="Book Author"/ required>
<input type="file" name="bookfile" id="bookfile" required/>
<input type="submit" value="Upload book">
</form>
<script>
function validate() {
var val = document.getElementById('bookfile').value.toLowerCase();
var regex = new RegExp("(.*?)\.(docx|doc|pdf)$");
if(!(regex.test(val))) {
document.getElementById('bookfile').value = '';
alert('Please select correct file format');
return false;
}
return true;
}
</script>
<form method="POST" action="connection.php" enctype="multipart/form-data" id="myform">
<input type="text" id="name" name="bookname" placeholder="Book Name" required/>
<textarea cols="25" rows="4" name="bookdesc" placeholder="Book Description" required></textarea>
<input type="text" id="password" name="bookauthor" placeholder="Book Author"/ required>
<input type="file" name="bookfile" id="bookfile" required/>
</form>
<script>
var isValid = false;
$(document).ready(function () {
$('input[type=file]').change(function () {
var val = $(this).val().toLowerCase();
var regex = new RegExp("(.*?)\.(docx|doc|pdf)$");
isValid = !!(regex.test(val));
if(!isValid) {
$(this).val('');
alert('Please select correct file format');
} }); });
$("#myform").submit(function(e) {
if (!isValid) {
e.preventDefault();
}
});
</script>
I have added an id to your form. Using this id as a selector I have created a submit handler for the form. This handler checks whether isValid is false and if so, calls e.preventDefault(), which prevents the form from submitting. If isValid was true, then e.preventDefault() will not be called, therefore the form submits. isValid is initialized with false and is evaluated on input[type=file] change.

Validation fails when multiple <form> tags are present in the same HTML document

I have multiple form tags in my html doc and want to validate them. However the validation function won't give any result. Tried
adding name field to the <form> the validation() does not return any result.
When I use validation with only one <form> the result is correct.
here are the two form tags:
<div id="pinfo">
<form>
<fieldset>
<legend>Personal Information</legend>
Name:
<input type="text" name="name" value="Enter name">
<br><br>
Email:
<input type="email" name="eamil" value="Enter email id">
<br><br>
Confirm email id:
<input type="text" name="cemail" value="">
<br><br>
Password:
<input type="password" name="pass" value="">
<br><br>
Confirm password:
<input type="password" name="cpass" value="">
<br><br>
</fieldset>
</form>
</div>
<div id="linfo">
<form>
<fieldset>
<legend>Location and Contact</legend>
Location:
State:
<!more code ahead>
<script>
function validateForm() {
var eid = document.forms["loginform"]["emailid"].value;
if (eid == null || eid == "") {
alert("Email id must be entered.");
return false;
}
var pwd = document.forms["loginform"]["password"].value;
if (pwd == null || pwd == ""){
alert("Please enter the password.");
return false;
}
var p = document.forms["locinfo"]["pno"].value;
if (p == null || p=="") {
alert("Please enter the phone no.");
return false;
}
</script>
Validating Form Fields Using JavaScript in FrontPage
There are some mistakes in your code.
You have not given form name as "loginform" which you are using in validation function.
And second thing you missed is "onsubmit" attribute on form element
Here is working code for you
function validateForm() {
console.log(document.forms["loginform"])
var eid = document.forms["loginform"]["eamil"].value;
if (eid == null || eid == "") {
alert("Email id must be entered.");
return false;
}
var pwd = document.forms["loginform"]["pass"].value;
if (pwd == null || pwd == "") {
alert("Please enter the password.");
return false;
}
/*var p = document.forms["locinfo"]["pno"].value;
if (p == null || p == "") {
alert("Please enter the phone no.");
return false;
}*/
}
<div id="pinfo">
<form method="post" name="loginform" action="/" onsubmit="return validateForm()">
<fieldset>
<legend>Personal Information</legend>
Name:
<input type="text" name="name" value="">
<br><br>
Email:
<input type="email" name="eamil" value="">
<br><br>
Confirm email id:
<input type="text" name="cemail" value="">
<br><br>
Password:
<input type="password" name="pass" value="">
<br><br>
Confirm password:
<input type="password" name="cpass" value="">
<br><br>
<input type="submit" name="submit" />
</fieldset>
</form>
</div>

JavaScript return false form validation not working

Can you help me, when the validation fails my script should unhide an error message in a p tag and return false but instead my form submits. Can you see where my problem is?
function validate() {
if (document.emailForm.EMAIL_ADDRESS_.value.length==0) {
$('#errorNoAddress').fadeIn();
return false;
}
if (document.emailForm.EMAIL_ADDRESS_.value.length>0) {
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var address = document.emailForm.email.value;
if(reg.test(address) == false) {
$('#errorInvalidAddress').fadeIn();
return false;
}
}
document.emailForm.submit();
return true;
}
<form id="emailForm" name="emailForm" action="http://domain.com/formhandler.php" method="post">
<p id="errorNoAddress" class="error">Please enter an e-mail address.</p>
<p id="errorInvalidAddress" class="error">Please enter a valid email address.</p>
<label for="EMAIL_ADDRESS_">E-mail</label>
<input type="hidden" id="QUICK_SIGN_UP" name="QUICK_SIGN_UP" value="" />
<input type="image" src="btn-submit.gif" value="Submit" onclick="validate();" />
</form>
try <input type="image" src="btn-submit.gif" value="Submit" onclick="return validate();" />

Form validation with Javascript function

I am trying to validate a form, to make sure that the user inputs a value into a textbox. Here's my Javascript:
var formValidation = function(a) {
if (document.getElementById(a).value == "") {
alert('Please fill out the ' + a + ' field');
return false;
}
else {
return true;
}
}
And here's the form:
<div id="cultdiv">
<form action="add.php" method="POST">
<span><input type="hidden" name="id" id="cultid"/>
<input type="text" onSubmit ="formValidation('culture')" name="name" id="culture"/>
<input type="hidden" name="type" value="culture" />
<input type="submit" value="add/update" /></span>
</form>
</div>
For some reason it doesn't stop the form from being submitted or give the alert message.
You forgot to return from your inline handler.
Also, <input>s don't have an onsubmit event; you probably meant to put that in the <form>.
slaks means something along these lines.
<script>
var formValidation = function() {
if (document.getElementById('culture').value == "") {
alert('Please fill out the culture field');
return false;
}
else {
return true;
}
}
<div id="cultdiv">
<form action="add.php" method="POST" onsubmit="return formValidation(this)">
<span><input type="hidden" name="id" id="cultid"/>
<input type="text" name="name" id="culture"/>
<input type="hidden" name="type" value="culture" />
<input type="submit" value="add/update" /></span>
</form>
</div>

Categories

Resources