I have simple form with fields for First and Last name and a salutation. I have a javascript function that should validate if the fields or empty or exceed 25 characters. The function mostly works except on .focus(); the page just reloads. Not sure what I'm doing wrong, please advise. Thanks in advance.
function validate(){
//alert ("TEST!!!");
var first = document.getElementById('firstname').value;
if (first.length == 0 || first.length > 25){
alert ("Please enter your first name, no longer than 25 chracters.");
document.getElementById('firstname').focus();
return false;
}
var last = document.getElementById('lastname').value;
if (last.length == 0 || last.length > 25){
alert ("Please enter your last name, no longer than 25 characters.");
document.getElementsByName('lastname').focus();
return false;
}
var title = document.getElementById('title').value;
if (document.getElementById('title').selectedIndex == 0){
alert ("Please select your salutation");
document.getElementById('title').focus();
return false;
}
return true;
}
In the html the form is:
<form name="name" form id="name" method="post" onsubmit="validate();">
Salutation: <select name="title" select id="title">
<option selected="Please Select">Please select</option>
<option value="Mr.">Mr.</option>
<option value="Mrs.">Mrs.</option>
<option value="Miss">Miss</option>
</select><br><br>
First Name : <input type="text" input id="firstname" name="firstname">
Last Name : <input type="text" input id="lastname" name="lastname"><br><br>
<input type="submit" value="Submit"><br><br>
</form>
Change:
onsubmit="validate();">
to:
onsubmit="return validate();">
Related
This is my index.html file. It has JavaScript but when JavaScript validation works >Submit button doesn't perform any action. But when I remove JavaScript code it submits the data to the database.
I need to understand where my code has faults or mistakes and why this is happening. How to validate that the arrival date should be smaller than the departure date.
<!DOCTYPE html>
<head>
<title>Book Accomodations</title>
<link rel="stylesheet" href="style.css">
<script>
function validate(){
var x =document.forms["myform"]["fname"].value;
var y =document.forms["myform"]["lname"].value;
var email =document.forms["myform"]["email"].value;
var filter = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var getSelectedValue = document.querySelector( 'input[name="payment"]:checked');
if (x == "" || x == null) {
alert("First Name must be filled out");
return false;
} else if (y == "" || y == null) {
alert(" Last Name must be filled out");
return false;
}
else if (!email.match(filter)) {
alert(" Enter Proper Email ID");
return false;
}
else if(document.getElementById("country").value == "")
{
alert("Please select a country");
return false;
} else if(getSelectedValue == null) {
alert("Select Payment Mode")
return false;
}
return false;
}
</script>
</head>
<body>
<div class="form">
<form name ="myform" action="function.php" onsubmit="return validate();" id="form" method="POST" >
<label for="fname">First Name:</label>
<input type="text" id="fname" name="fname" /><br>
<label for="lname">Last Name:</label>
<input type="text" id="lname" name="lname" /><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" /><br>
<label for="arrival">Arrival Date:</label>
<input type="date" id="arrival " name="adate" ><br>
<label for="departure">Departure Date:</label>
<input type="date" id="departure " name="ddate" />
<br>
<label for="country">Choose a Country:</label>
<select id="country" name="country" form="myform" >
<option disabled selected value> -- select an option -- </option>
<option value="India">India</option>
<option value="U.S.A.">U.S.A.</option>
<option value="Nepal">Nepal</option>
<option value="Bangladesh">Bangladesh</option>
<option value="Germany">Germany</option>
<option value="Spain">Spain</option>
<option value="Italy">Italy</option>
<option value="Sri Lanka">Sri Lanka</option>
<option value="China">China</option>
</select>
<p>Payment Mode:</p>
<input type="radio" id="deb"
name="payment" value="Debit" />
<label for="deb">Debit Card</label>
<input type="radio" id="cred"
name="payment" value="Credit"/>
<label for="Credit">Credit Card</label>
<br>
<input type="submit" id="submit" name="submit" value="submit" style="width: 100px;"/>
<input type="reset" value="Reset" style="width: 100px; "/>
</form> </div>
</body>
You should return true at the end of your validate() function if your validation was successful. Right now you always return false. Thats why the button doesn´t seams to work.
Seems like you missed something.
You should return true after succesfull validation.
if (x == "" || x == null) {
alert("First Name must be filled out");
return false;
} else if (y == "" || y == null) {
alert("Last Name must be filled out");
return false;
} else if (!email.match(filter)) {
alert("Enter Proper Email ID");
return false;
} else if (document.getElementById("country").value == "") {
alert("Please select a country");
return false;
} else if (getSelectedValue == null) {
alert("Select Payment Mode")
return false;
} else {
return true;
}
Or just return true after if-else statement.
I have a function to validate all fields, but I also want to disable the submit button until the fields are filled out AND validation is complete. What is the best way to go about doing this? I'm very new to JavaScript so very specific instructions/explanation is appreciated :)
function fieldValidation() {
var name = document.forms['RegForm']['Name'].value;
var address = document.forms['RegForm']['Address'].value;
var email = document.forms['RegForm']['EMail'].value;
var password = document.forms['RegForm']['Password'].value;
var telephone = document.forms['RegForm']['Telephone'].value;
var job = document.forms['RegForm']['Job'].value;
var comment = document.forms['RegForm']['Comment'].value;
var fullName = /^[a-zA-Z]+ [a-zA-Z]+$/;
var phnFormat = /((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}/;
if (name === '') {
alert('Please enter your name.');
return false;
}
if (!fullName.test(name)) {
alert('Please make sure we have your full name.');
return false;
}
if (address === '') {
alert('Please enter your address.');
return false;
}
if (email === '') {
alert('Please enter your e-mail address.');
return false;
}
if (password === '') {
alert('Please enter a password.');
return false;
}
if (telephone === '') {
alert('Please enter your telephone number.');
return false;
}
if (!phnFormat.test(telephone)) {
alert('Please enter your phone number in the following format: (123) 555-1212)');
return false;
}
if (job.value === '') {
alert('Please select a job choice.');
return false;
}
if (comment.value === '') {
alert('Please enter a comment.');
return false;
}
return true;
}
<div class="container">
<main>
<form name="RegForm" action="/submit.php" onsubmit="return fieldValidation()" method="post">
<p>Name: <input type="text" size=65 name="Name" id="nameInput"> </p><br>
<p>Address: <input type="text" size=65 name="Address"> </p><br>
<p>E-mail Address: <input type="email" size=65 name="EMail"> </p>
<input type="checkbox" id="confirmApp" name="confirm">
<label for="confirmApp">I want to receive an email confirming my application.</label>
<br>
<p>Password: <input type="password" size=65 name="Password"> </p><br>
<p>Telephone: <input type="tel" size=65 name="Telephone"> </p><br>
<label for="jobChoice">Job Choice:</label>
<select name="Job" id="jobChoice">
<option value="">--- Select Job Choice ---</option>
<option value="IT">IT</option>
<option value="Human Resources">Human Resources</option>
<option value="Maintenance">Maintenance</option>
<option value="Management">Management</option>
<option value="Other">Other</option>
</select></p><br><br>
<p>Comments: <textarea cols="100" rows="10" name="Comment"> </textarea></p>
<p><input type="submit" value="send" name="Submit" id="submitBtn">
<input type="reset" value="Reset" name="Reset"></p>
</form>
</main>
</div>
You could do it in a couple of ways:
You could have a onclick="your validation function" for each input running your validation code.
Or you could add the required tag to each required input, this way the user cant submit the form unless every required field is filled in a.e. <input type="text" size="65" name="Name" id="nameInput"required>, however option two does not hide the submit button.
If you only want to disable the submission and not the submit button persé I'd suggest using the required tag for the relevant input fields.
I have a form that keeps resetting every time I hit the required field when I click submit. Is there a way for my form to not submit or clear up when I hit the submit button, while checking for the required fields? My form alerts me, the submits. I don't know how to stop that, and make the alert go from one text type to the next. Like it checks the first input type, if it meets the requirements, then it checks for the next input type, is that possible?
<html>
<!--All my images were taken from google images-->
<!--4/29/2016-->
<title>LMC GYM</title>
</body>
<link rel= " stylesheet " type="text/css" href="Acss.css" />
<head>
<script>
function validate_form (){
valid = true;
var emailverify = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var letter = /^[a-zA-Z]+$/;
var zip = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
if (emailverify.test(document.contact_form.contact_email.value) == false){
alert ("Please put in a valid email provider.");
valid = false;
}
if (document.contact_form.contact_email.value ==""){
alert ("Please put in your email.");
valid = false;
}
if (document.contact_form.contact_pass.value ==""){
alert ("Please put in a password.");
valid = false;
}
if (document.contact_form.contact_pass1.value != document.contact_form.contact_pass.value){
alert ("Please make sure passwords are the same.");
valid = false;
}
if (document.contact_form.contact_first.value ==""){
alert ("Please put in your first name.");
valid = false;
}
if (letter.test(document.contact_form.contact_first.value) == false){
alert ("No numbers! Please enter a valid first name.");
valid = false;
}
if (document.contact_form.contact_last.value ==""){
alert ("Please put in your last name.");
valid = false;
}
if (letter.test(document.contact_form.contact_last.value) == false){
alert ("No numbers! Please enter a valid last name.");
valid = false;
}
if (document.contact_form.contact_state.value ==""){
alert ("Please enter state abbrevation, example New York-NY.");
valid = false;
}
if (letter.test(document.contact_form.contact_state.value) == false){
alert ("Reminder no numbers! Please put in state abbrevation.");
valid = false;
}
if (document.contact_form.contact_city.value ==""){
alert ("Please put in your current city.");
valid = false;
}
if (letter.test(document.contact_form.contact_city.value) == false){
alert ("Reminder no numbers! Please put in your current city.");
valid = false;
}
if (document.contact_form.contact_add.value ==""){
alert ("Please put in your address.");
valid = false;
}
if (document.contact_form.contact_zip.value ==""){
alert ("Please put in your zip code.");
valid = false;
}
if (zip.test(document.contact_form.contact_zip.value) == false){
alert ("No letters in zip code!!.");
valid = false;
}
if (document.contact_form.contact_phone.value ==""){
alert ("Please put in your phone number.");
valid = false;
}
if (( document.contact_form.gen[0].checked == false) && (
document.contact_form.gen[1].checked == false )){
alert ("Please choose your Gender: Male or Female");
valid = false;
}
if (document.contact_form.Membership.selectedIndex == 0){
alert ("Please choose a membership.");
valid = false;
}
if (( document.contact_form.card[0].checked == false) && (document.contact_form.card[1].checked == false ) && (document.contact_form.card[2].checked == false ) && (document.contact_form.card[3].checked == false )){
alert ("Please choose a card type");
valid = false;
}
if (document.contact_form.contact_cn.value ==""){
alert ("Please put in your card number.");
valid = false;
}
if (document.contact_form.contact_cvv.value ==""){
alert ("Please put in your 3 digit cvv.");
valid = false;
}
if (document.contact_form.Expmonth.selectedIndex == 0){
alert ("Please choose a month on your credit card.");
valid = false;
}
if (document.contact_form.Expyear.selectedIndex == 0){
alert ("Please choose a year on your credit card.");
valid = false;
}
if (document.contact_form.contact_date.value ==""){
alert ("Please fill in the 'Expiration Date' box in the month and year format MMYY.");
valid = false;
}
if (document.contact_form.terms.checked == false){
alert ("Please check the Terms & Conditions box.");
valid = false;
}
return false;
}
</script>
</head>
<body>
<div class= "contains">
<div class ="head">
<h4> LMC GYM </h4>
<body background="https://wallpaperscraft.com/image/dumbbells_sports_gym_106546_3840x2 160.jpg">
</h4>
</div>
<div class ="nav">
<h5>Navigate</h5>
<ul>
<li>Home</li>
</br>
<li>Offers</li>
</br>
<li>Gym Form</li>
</ul>
</div><!--nav><-->
<div class="chunk">
</script>
</head>
<form name="contact_form" method="post" onSubmit="return validate_form ( );">
<h1> Signup now to join the LMC GYM </h1>
<fieldset>
<legend>Account Information:</legend>
E-mail: <input type="email" name="contact_email"> </br></br>
Password: <input type="password" name="contact_pass"></br></br>
Verify Password: <input type="password" name="contact_pass1"></br></br>
</fieldset>
</br>
<fieldset>
<legend>Contact Information:</legend>
First Name: <input type="text" name="contact_first" maxlength="13"> </br></br>
Last Name: <input type="text" name="contact_last" maxlength="13"> </br></br>
State: <input type="text" name="contact_state" maxlength="2"> </br></br>
City: <input type="text" name="contact_city" maxlength="13"> </br></br>
Address: <input type="text" name="contact_add" maxlength="21"> </br></br>
Zip Code: <input type="number" name="contact_zip" maxlength="5" > </br></br>
Phone Number: <input type="number" name="contact_phone" maxlength="10" > </br> </br>
Your Gender: <input type="radio" name="gen" value="Male"> Male
<input type="radio"name="gen" value="Female"> Female </br></br>
</fieldset> </br>
<fieldset>
<legend>Payment Information:</legend>
Membership:
<select name="Membership" >
<option value="">Please choose an option:</option>
<option value= "Bronze "> Bronze </option>
<option value= "Silver"> Silver </option>
<option value= "Gold">Gold</option> </select> </br></br>
Card Type: <input type="radio" name="card" value="Mastercard"> Mastercard
<input type="radio"name="card" value="Visa"> Visa </br>
<input type="radio"name="card" value="American Express"> American Express
<input type="radio"name="card" value="Discover"> Discover </br> </br>
Card Number: <input type="number" name="contact_cn" maxlength="16"> </br></br>
Card CVV: <input type="number" name="contact_cvv" min="009" maxlength="3"> </br></br>
Good Through:
<select name="Expmonth" >
<option value=""> Month:</option>
<option value= "01 "> 01 </option>
<option value= "02 "> 02 </option>
<option value= "03"> 03 </option>
<option value= "04">04</option>
<option value= "05 "> 05 </option>
<option value= "06"> 06 </option>
<option value= "07">07</option>
<option value= "08"> 08 </option>
<option value= "09">09</option>
<option value= "10"> 10 </option>
<option value= "11"> 11 </option>
<option value= "12">12</option> </select>
<select name="Expyear" >
<option value=""> Year:</option>
<option value= "18 "> 18 </option>
<option value= "19 "> 19 </option>
<option value= "20"> 20 </option>
<option value= "21">21</option>
<option value= "22 "> 22 </option>
<option value= "23"> 23 </option>
<option value= "24">24</option>
<option value= "25"> 25 </option>
<option value= "26">26</option>
<option value= "27"> 27 </option>
<option value= "28"> 28 </option>
<option value= "29">29</option> </select> </br></br>
</fieldset>
Do you agree to the Terms and Conditions?</br></br>
<input type="checkbox" name="terms" value="Yes"> Yes
</br></br>
<p><input type="submit" name="send" value="Submit"></p>
<p><input type="reset" name="reset"></p>
</form>
</body>
</html>
</div><!--"chunk"><-->
<div class="foot">
</div><!--foot><-->
</div><!--contains><-->
</body>
</html>
event.preventDefault(); prevents default behaviour (duh), which doesn't refresh the page.
I would use the following piece of code:
function validate_form(){
//
//
//
}
var form = document.querySelector('form');
form.addEventListener('submit', function(event){
event.preventDefault();
validate_form();
}
But, as RobG suggested, this would prevent the default submission routine as well. So you should explicitly add a call to submit function (or the form's submit method, if you are using it), e.g.
event.preventDefault();
if(validate_form()){
form.submit()
} else { /*error handling routine*/ }
Or you could do it in one line like this (doesn't make sense with default submit, since it would be implementing the default behaviour anyway):
event.preventDefault();
return validate_form() && my_submit_nethod();
// form submits only if validate_form evaluated to true
Or, just return the validation result and leave the form to submit. Note, that currently, if the validation returns true, your page will refresh.
return validate_form();
Finally, another thing you could do is change the form's submission method:
var form = document.querySelector('form');
function my_submit_routine(){
// here goes your code for submitting
};
form.submit = my_submit_routine;
Hi so i was reading how to validate html forms, all my validators client side are working woth patterns and type. The problem is when i press submit the javascript validation dont run. There is my code:
<script language="javascript">
function validateForm()
{
var xa = document.forms["regform"]["password"].value;
var xb = document.forms["regform"]["password2"].value;
var xc = document.forms["regform"]["email"].value;
var xd = document.forms["regform"]["email2"].value;
if (xa == xb && xc == xd){
return true; }
else{ return false; alert("Please enter a valid captcha code");}
}
$(document).ready(function(e) {
try {
$("body select").msDropDown();
} catch(e) {
alert(e.message);
}
});
</script>
Them the form:
<form name="regform" onsubmit="return validateForm();" action="actions/register_acc.php" method="post">
<input type="password" name="password" class="input-style" required="required">
<input type="password2" name="password" class="input-style" required="required">
<input name="email" class="input-style" placeholder="your#email.com" required="required" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$">
<input name="email2" class="input-style" placeholder="your#email.com" required="required" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$">
<input type="submit" value="ok">
</form>
Inside the form i also have these:
<select name="selectname" id="webmenu">
<option value="1">1</option>
<option value="2">2</option>
</select>
And in the head these:
<script src="js/msdropdown/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="js/msdropdown/jquery.dd.min.js" type="text/javascript"></script>
The problem lies in the validateForm method itself, specifically in the else block. You're returning false before the alert call. Swap the two calls around and you should see the alert message appear.
For clarity's sake, I would change the message in the alert box as it isn't directly relevant to the fields you're validating.
function validateForm()
{
var xa = document.forms["regform"]["password"].value;
var xb = document.forms["regform"]["password2"].value;
var xc = document.forms["regform"]["email"].value;
var xd = document.forms["regform"]["email2"].value;
if (xa == xb && xc == xd){
return true;
}
else {
alert("Please enter a valid captcha code");
return false;
}
}
See this Fiddle
I've created a form, that I need to validate with JavaScript or using Jquery. How would I validate if the dropdown list has the value "Title" and if the text box is empty and display it on the page rather then an alert box :
<form action="" method="post" accept-charset="UTF-8" name="myForm">
<option value="Title" id="title_3-0" disabled selected>Title</option><option value="Mr" id="title_3-1">Mr</option>
<option value="Mrs" id="title_3-2">Mrs</option><option value="Miss" id="title_3- 3">Miss</option>
<option value="Ms" id="title_3-4">Ms</option><option value="Dr" id="title_3-5">Dr</option>
<option value="Professor" id="title_3-6">Professor</option></select></div></div>
TextBox:
<input type="text" class="text" name="firstname_4" id="amf-input-firstname_4" value="" placeholder="First Name">
I also have a button.
Here is a start:
<script>
function validateForm()
{
var return_value = true;
var x=document.forms["myForm"]["firstname_4"].value;
if (x==null || x=="")
{
document.getElementById("error").innerHTML += "First name must be filled out<br />";
return_value = false;
}
var y=document.forms["myForm"]["selectid"];
if(y.options[y.selectedIndex].value == "Title")
{
document.getElementById("error").innerHTML += "You need to select a title<br />";
return_value = false;
}
return return_value;
}
</script>
<span id="error"></span>
<form name="myForm" onsubmit="return validateForm()" method="post">
First name: <input type="text" class="text" name="firstname_4" id="amf-input-firstname_4" value="" placeholder="First Name">
<input type="submit" value="Submit">
</form>
If you like, you can also put an "error span element" above/beneath each field and set each error individually:
<script>
function validateForm()
{
var return_value = true;
var x=document.forms["myForm"]["firstname_4"].value;
if (x==null || x=="")
{
document.getElementById("error1").innerHTML = "First name must be filled out";
return_value = false;
}
var y=document.forms["myForm"]["selectid"];
if(y.options[y.selectedIndex].value == "Title")
{
document.getElementById("error2").innerHTML = "You need to select a title";
return_value = false;
}
return return_value;
}
</script>
<form name="myForm" onsubmit="return validateForm()" method="post">
First name: <input type="text" class="text" name="firstname_4" id="amf-input-firstname_4" value="" placeholder="First Name">
<span id="error1"></span>
Title: <input .... >
<span id="error2"></span>
<input type="submit" value="Submit">
</form>
Since you are new to this, look up these links and read up. It will guide you through it. That's better than us giving you all the code. Because this kind of form validation is important and hence you better learn it from scratch.
Link-1
Link-2
Link-3 (using library)
Html:
<select id="ddl"> <option value="Title" id="title_3-0" selected>Title</option><option value="Mr" id="title_3-1">Mr</option>
<option value="Mrs" id="title_3-2">Mrs</option><option value="Miss" id="title_3- 3">Miss</option>
<option value="Ms" id="title_3-4">Ms</option><option value="Dr" id="title_3-5">Dr</option>
<option value="Professor" id="title_3-6">Professor</option></select>
<input type="text" class="text" name="firstname_4" id="amf-input-firstname_4" value="" placeholder="First Name">
<input type="button" value="Submit" id="btn"/>
<span id="error"/>
JQuery:
$('#btn').click(function (){
if(($('#amf-input-firstname_4').val()=='') || ($("#ddl :selected").val() == 'Title'))
{
$('#error').html('Please select title and enter name.');
}
else
{
$('#error').html('Success');
}
return false;
});
Demo:
http://jsfiddle.net/8h8HF/