Form validation on submit don't work - javascript

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

Related

validate email and display accordingly

I want to check the email validity in Javascript and then show alert box if its invalid and if valid then show the div2. But its not working
Here is javascript:
function _(x){
return document.getElementById(x);
}
function Phase1()
{
myemail = _("email").value;
var reg = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (reg.test(designeremail) == false)
{
alert('Invalid Email Address');
}
else
{
_("phase1").style.display = "none";
_("phase2").style.display = "block";
}
}
Here is my html:
<form id="myform" onsubmit="return false" >
<div id="phase1">
<label>Email</label><div><input type="text" id="email" name="email" required></div>
<div><button onclick="Phase1()" class="btn"><strong>Next</strong></button></div>
</div>
<div id="phase2">
<label>Name</label><div><input type="text" id="mname" name="myname" required></div>
<div><button onclick="Phase2()" class="btn"><strong>Submit</strong></button></div>
</div>
</form>
but even with wronng email it proceeds and shows the phase2
I think this is js and not php. Btw, it's because probably you're testing on the wrong variable:
if (reg.test(designeremail) == false)
you're testing designeremail, which is different from email from the form which probably you wanted test against to.

Can not run document.getElementById

I just wrote a simple javascript to submit a form.
<div class=login>
<fieldset>
<legend>Login</legend>
<form id="form" method="get" action="summary_iframe.html" onsubmit="return validate()">
User: <input type="text" id="userAc" value="" name="userAc"><br>
Password: <input type="text" id="userPw" value="" name="userPw"><br>
This is the function, check that both user and password are not blank and there is no intervening space in use.
function validate(){
var userAc = document.getEmelentById('userAc').value;
var userPw = document.getEmelentById('userPw').value;
if(userAc.length == 0 || userPw.lenth == 0 || userAc.indexOf(' ')>-1 || userPw.indexOf(' ')>-1)
{
alert("Please input again!");
return false;
}
else
{
checkLogin(userAc, userPw);
return true;
}
}
But it does not work, I used a browser to debug and when it's running this line, it quits form the function.
var userAc = document.getEmelentById('userAc').value;
Please tell me what's wrong. Thanks!
Please alter your function as below.
function validate(){
var userAc = document.getElementById('userAc').value;
var userPw = document.getElementById('userPw').value;
if(userAc.length == 0 || userPw.lenth == 0 || userAc.indexOf(' ')>-1 || userPw.indexOf(' ')>-1)
{
alert("Please input again!");
return false;
}
else
{
checkLogin(userAc, userPw);
return true;
}
}
You need to use as document.getElementById('userAc').value, instead of document.getEmelentById('userAc').value. Hereafter please check your browser console before you post any question here. Thanks
You have missed Submit Button.
<form id="form" method="get" action="summary_iframe.html" onsubmit="return validate()">
User: <input type="text" id="userAc" value="" name="userAc"><br>
Password: <input type="text" id="userPw" value="" name="userPw"><br>
<input type="submit" value="submit" name="btnSubmit">
</form>

Submitting form even when validation regex is wrong

i am having this problem when i submit the form where both the password and username is wrong. I get an alert box saying that i have enter the wrong details. But when the username is correct and password is validation is wrong it will give me an arlet box by when pressed ok it will submit the form even when i have returned false.
Help please much appreciated
<script type="text/javascript">
function validate(form_id, firstName, password){
var Reg = /^[A-Za-z0-9_]{1,20}$/;
var Reg1 = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
var username = document.forms[form_id].elements[firstName].value;
var password = document.forms[form_id].elements[password].value;
if (Reg.test(username) == false) {
alert('Invalid Username.');
document.forms[form_id].elements[firstName].focus();
return false;
}
if (Reg1.test(password) == false) {
alert('Invalid Password.');
document.forms[form_id].elements[password].focus();
return false;
}
}
</script>
<form id="form_id" action="userlogininput.cgi" onsubmit="javascript:return validate('form_id','firstName','password');" name="form" method="post">
Username : <input type="text" id="firstName" name="firstName" class="textboxH-300" required><br>
Password : <input type="password" id="password" name="password" class="textboxH-300" required><br><br>
<input id="submitbtn" type="submit" value="Submit"/>
</form>
You can use e.preventDefault() to prevent form sending.
Here is a code example
(function(){
function validate(e) {
e.preventDefault(); // prevent the form sending
var Reg = /^[A-Za-z0-9_]{1,20}$/;
var Reg1 = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
var username = document.getElementById('firstName');
var password = document.getElementById('password');
if (Reg.test(username.value) == false) {
alert('Invalid Username.');
username.focus();
return false;
}
if (Reg1.test(password.value) == false) {
alert('Invalid Password.');
password.focus();
return false;
}
}
//add event listener for form submission
document.getElementById('form_id').addEventListener('submit',validate);
})();
<form id="form_id" action="userlogininput.cgi" name="form" method="post">
Username :
<input type="text" id="firstName" name="firstName" class="textboxH-300" required>
<br> Password :
<input type="password" id="password" name="password" class="textboxH-300" required>
<br>
<br>
<input id="submitbtn" type="submit" value="Submit" />
</form>
Try prevent default event.
Bind function to the form submit event:
function validate(form){
var Reg = /^[A-Za-z0-9_]{1,20}$/;
var Reg1 = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
var username = form.querySelector('[name=firstName]');
var password = form.querySelector('[name=password]');
if (Reg.test(username.value) == false) {
event.preventDefault();
alert('Invalid Username.');
username.focus();
return false;
}
if (Reg1.test(password.value) == false) {
event.preventDefault();
alert('Invalid Password.');
password.focus();
return false;
}
}
<form onsubmit="validate(this)">
<input name="firstName">
<br>
<input name="password">
<br>
<button type="submit">submit</submit>
</form>

Adding Span with Class to a input tag with Jquery

I am trying to add a Span after my Input that will have the class "error" and the text "test".
I've tried the append, and insertAfter methods. I can get the code to work on jsfiddle but I cannot get the code to work on my application.
I have put the HTML and JS/Jquery below. My end result would have a Span (with the class error) next to each input with the type text. I would then set a value for this span based on a validation loop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Zito - Lab 7</title>
<link rel="stylesheet" href="main.css">
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js" type="text/javascript"></script>
<script src="http://code.jquery.com/jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="reservation.js" type="text/javascript"></script>
</head>
<body>
<h1>Reservation Request</h1>
<form action="response.html" method="get"
name="reservation_form" id="reservation_form">
<fieldset>
<legend>General Information</legend>
<label for="arrival_date">Arrival date:</label>
<input type="text" name="arrival_date" id="arrival_date" autofocus><br>
<label for="nights">Nights:</label>
<input type="text" name="nights" id="nights"><br>
<label>Adults:</label>
<select name="adults" id="adults">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select><br>
<label>Children:</label>
<select name="children" id="children">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select><br>
</fieldset>
<fieldset>
<legend>Preferences</legend>
<label>Room type:</label>
<input type="radio" name="room" id="standard" class="left" checked>Standard
<input type="radio" name="room" id="business" class="left">Business
<input type="radio" name="room" id="suite" class="left last">Suite<br>
<label>Bed type:</label>
<input type="radio" name="bed" id="king" class="left" checked>King
<input type="radio" name="bed" id="double" class="left last">Double Double<br>
<input type="checkbox" name="smoking" id="smoking">Smoking<br>
</fieldset>
<fieldset>
<legend>Contact Information</legend>
<label for="name">Name:</label>
<input type="text" name="name" id="name"><br>
<label for="email">Email:</label>
<input type="text" name="email" id="email"><br>
<label for="phone">Phone:</label>
<input type="text" name="phone" id="phone" placeholder="999-999-9999"><br>
</fieldset>
<input type="submit" id="submit" value="Submit Request"><br>
</form>
</body>
</html>
JS/JQuery
$(document).ready(function() {
var emailPattern = /\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
var phonePattern = /\b(\d{3})([-])(\d{3})([-])(\d{4})\b/;
var datePattern = /\b(0[1-9]|1[012])([/])(0[1-9]|1[0-9]|2[0-9]|3[01])([/])((20)\d\d)\b/;
$(":text").after("<span class='error'>*</span>");
$("#arrival_date").focus();
$("#reservation_form").submit(
function(event) {
var isValid = true;
// validate arrival date
var arrivalDate = $("#arrival_date").val();
if (arrivalDate == "") {
$("#arrival_date").next().text("This field is required");
isValid = false;
} else if (!datePattern.test(arrivalDate)) {
$("#arrival_date").next().text("Must be in the format 12/12/2012");
isValid = false;
} else {
$("#arrival_date").next().text("");
}
// validate nights
var nights = $("#nights").val();
if (nights == "") {
$("#nights").next().text("This field is required");
isValid = false;
} else if ((isNaN(parseInt(nights))) || (parseInt(nights) <=0)) {
$("#nights").next().text("This field must be a number and not zero");
isValid = false;
} else {
$("#nights").next().text("");
}
// validate name
var name = $("#name").val();
if (name == "") {
$("#name").next().text("This field is required");
isValid = false;
} else {
$("#name").next().text("");
}
// validate email
var email = $("#email").val();
if (email == "") {
$("#email").next().text("This field is required");
isValid = false;
} else if (!emailPattern.test(email) ) {
$("#email").next().text("Must be a valid email address.");
isValid = false;
} else {
$("#email").next().text("");
}
// validate phone
var phone = $("#phone").val();
if (phone == "") {
$("#phone").next().text("This field is required");
isValid = false;
} else if (!phonePattern.test(phone) ) {
$("#phone").next().text("Must be in the format 999-999-9999");
isValid = false;
} else {
$("#phone").next().text("");
}
if (isValid == false) {
event.preventDefault();
$("#arrival_date").focus();
}
}
);
}); // end ready
Most easy way is to add a Div container around the form and just append the warning to that. To effectively append after an element you need to give it a class or id.
var email = $("#email"); //using class instead of input:text
var html = "<span class='error'>TEST!</span>"
email.after( html );
But I personally would like something like this better:
var generateError = function(){
var html = "<div id='error' style='top: 0; left:0; width:100%; height: 50px; background-color: red; text-allign: center; display:none; z-index: 100;'> ERROR!!</div>"
$(body).append( html );
}
var showError = function( text ){
var err = $("#error");
err.html( text );
err.show(500).delay(2000).hide(500);
}
Code is fairly self-explaining, but this will make two functions: generateError and showError.
generateError you need to call before you want to show the error, possibly when the page loads it will add a small header on top of all you other elements and will appear hidden.
showError uses a text argument with the error you want to show. Then it will set the text to the div and show it for two seconds.
This then is more what you are looking for?
$(document).ready(function () {
var input = $("input");
var emailPattern = /\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
input.keypress(function (ele) {
// if regex.test( input ) === false
createErrors(ele.target);
})
});
var createErrors = function (ele) {
$('<span>TEST!</span>').insertAfter(ele);
$("#arrival_date").focus();
};
This works on keypress, that means the regex gets checked every time a key is pressed. It also passes the element where the user is typing as parameter, this means that you wont get errors for all input:text, but only for the ones where there is an error.
Updated Fiddle (still not perfect, but if its an school exercise this will help you to finish it :)

.focus() not working in Javascript Function

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();">

Categories