I have JavaScript code that will validate a form on the first submit request, but if the user then hits submit again, even though they have not rectified the form errors, the form will not process the validation function and will just submit.
I would like the validation function to be executed every time the user clicks on the submit button.
Thanks for any help, code below.
Martin
<form action="site.url" method="post" name="signup" onsubmit="return validateForm()">
<label for="firstname"><span id="inactiveErrorFname">Please enter your first name<br></span>
First name <strong title="Required" class="required">*</strong></label><br>
<input type="text" name="firstName">
<label for="surname"><br><span id="inactiveErrorSname">Please enter your Surname<br></span>
Surname</label><input type="text" name="lastName">
<label for="email">
<span id="inactiveErrorEmail"><br>Please enter your Email address<br></span>
Email address <strong title="Required" class="required">*</strong></label>
<input type="text" name="emailAddress">
<input class="button" type="submit" value="Sign up" />
</form>
<script>
function validateForm()
{
var x=document.forms["signup"]["firstName"].value;
var y=document.forms["signup"]["lastName"].value;
var z=document.forms["signup"]["emailAddress"].value;
var atpos=z.indexOf("#");
var fname;
var sname;
var email;
/* Validate first name */
if (x==null || x=="")
{
document.getElementById("inactiveErrorFname").id = "activeErrorFname";
fname = "true";
}
/* Validate Surname */
if (y==null || y=="")
{
document.getElementById("inactiveErrorSname").id = "activeErrorSname";
sname = "true";
}
/* Validate email */
if (atpos<1)
{
document.getElementById("inactiveErrorEmail").id = "activeErrorEmail";
email = "true";
}
if (fname=="true" || sname=="true" || email =="true")
{
return false;
}
}
</script>
The problem you are facing is created by the fact you are changing the id's of certain elements. The first time you run your code, these statements are succesfully runned:
document.getElementById("inactiveErrorFname").id = "activeErrorFname";
document.getElementById("inactiveErrorSname").id = "activeErrorSname";
document.getElementById("inactiveErrorEmail").id = "activeErroremail";
The second time however the id's of these elements have changed, resulting in the fact that these statements call upon unexisting elements. This results in a javascript fatal error, with as consequence no return false. The second time your form will thus be submitted as it normally is. The solution to this problem is not changing the id's but changing the class of the error-labels. You can find an example in this fiddle.
HTML:
<form action="#" method="post" name="signup" onsubmit="return validateForm()">
<label for="firstname">
<span class="inactive" id="errorFname">Please enter your first name<br></span>
First name <strong title="Required" class="required">*</strong>
</label><br>
<input type="text" name="firstName"><br><br>
<label for="surname">
<span class="inactive" id="errorSname">Please enter your Surname<br></span>
Surname
</label><br>
<input type="text" name="lastName"><br><br>
<label for="email">
<span class="inactive" id="errorEmail"><br>Please enter your Email address<br></span>
Email address <strong title="Required" class="required">*</strong>
</label><br>
<input type="text" name="emailAddress"><br><br>
<input class="button" type="submit" value="Sign up" />
</form>
Javascript:
function validateForm()
{
var x=document.forms["signup"]["firstName"].value;
var y=document.forms["signup"]["lastName"].value;
var z=document.forms["signup"]["emailAddress"].value;
var atpos=z.indexOf("#");
var fname;
var sname;
var email;
/* Validate first name */
if (x==null || x=="")
{
document.getElementById("errorFname").className = "active";
fname = "true";
}
/* Validate Surname */
if (y==null || y=="")
{
document.getElementById("errorSname").className = "active";
sname = "true";
}
/* Validate email */
if (atpos<1)
{
document.getElementById("errorEmail").className = "active";
email = "true";
}
if (fname=="true" || sname=="true" || email =="true")
{
return false;
}
return false;
}
Related
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.
So I currently have a download link and an input field for an email address on my website.
In order to download the file you first need to put in your email.
I use a form to do this, with the email field being an input field and the download button being a submit button.
I like HTML5's form validation (the required fields, field types etc, it all looks very nice).
The problem is that if I use onClick in my submit button then none of the nice form validation works.
<form>
<input type="email" id="email" placeholder="Please enter email" required>
<input type="submit" class="btn" onclick="downloadWin()" value="Windows">
<input type="submit" class="btn" onclick="downloadOsx()" value="Osx">
</form>
<script>
function downloadWin(){
event.preventDefault();
var email = $("#email").val();
if(email != ''){
if(validateEmail(email)){
location.href='http://s/index.php?page=downloadWin&email='+email;
}
}
}
function downloadOsx(){
event.preventDefault();
var email = $("#email").val();
if(email != ''){
if(validateEmail(email)){
location.href='http://s/index.php?page=downloadOsx&email='+email;
}
}
}
</script>
This might not be the cleanest way to do it, so please if you think you know a better way tell me :)
Try this:
<form onsubmit="download(this.email.value,this.system.value)" id="form">
<input type="email" id="email" name="email" placeholder="Please enter email" required>
<input type="radio" name="system" value="Win" required >Windows
<input type="radio" name="system" value="Osx" >Osx
<input type="submit" class="btn" value="Download">
</form>
<script type="text/javascript">
document.getElementById("form").addEventListener("submit", function(event){
event.preventDefault();
});
function download(email_value,sys_value){
location.href='http://s/index.php?page=download'+sys_value+'&email='+email_value;
}
</script>
Result:
try this code
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\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,}))$/;
return re.test(email);
}
function downloadWin() {
var email = $("#email").val();
if (email != '') {
if (validateEmail(email)) {
location.href = 'http://s/index.php?page=downloadWin&email=' + email;
}
}
return false;
}
function downloadOsx() {
var email = $("#email").val();
if (email != '') {
if (validateEmail(email)) {
location.href = 'http://s/index.php?page=downloadOsx&email=' + email;
}
}
return false;
}
Below is the working code snippet (without using HTML5 validation). You can run and test it. I have used the jquery with jquery.validate plugin. You can uncomment the commented code to redirect user to the target url. Let us know if this what you are looking for or not. Feel free to comment if there is anything that you feel confusing.
$(document).ready(function(){
$(".btn-download").on("click", function(e) {
e.preventDefault();
e.stopImmediatePropagation();
if ($("#validateForm").valid()) {
var name = $(this).val();
var email = $("#email").val();
if (name === "Windows") {
//location.href = 'http://s/index.php?page=downloadWin&email=' + email;
console.log('http://s/index.php?page=downloadWin&email=' + email);
}
if (name === "Osx") {
console.log('http://s/index.php?page=downloadOsx&email=' + email);
//location.href = 'http://s/index.php?page=downloadOsx&email=' + email;
}
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.1/jquery.validate.min.js"></script>
<form method="post" action="" id="validateForm" novalidate>
<input type="email" id="email" placeholder="Please enter email" required>
<input type="submit" name="btnSubmit" class="btn btn-download" value="Windows">
<input type="submit" name="btnSubmit" class="btn btn-download" value="Osx">
</form>
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>
I'm starting simple JavaScript form validation. I write two statement, first if statement working well but second one is not. But this two if statement separately working. I don't understand what I'm wrong. Here is the HTML code:
<form id="loginForm" name="loginForm" method="post" action="my-profile.html">
<div class="form-group">
<label>Email</label>
<input type="email" name="email" id="eMail" placeholder="abcde00#example.com" class="form-control" required="required" />
<span class="erRor" id="error1">Please input valid email address</span>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" placeholder="Password" name="password" id="pasSword" class="form-control" required="required" />
<span class="erRor" id="error2">Invalid email and password</span>
<span class="erRor" id="error3">This field should not be empty</span>
</div>
<div class="form-group">
<button type="submit" onclick="return validate();">Login</button>
</div>
</form>
JavaScript code here:
function validate(){
/* email validation */
var changeColor = document.getElementById("eMail");
var error1 = document.getElementById("error1");
var email1 = document.loginForm.email;
var re = /^(([^<>()[\]\\.,;:\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(!re.test(email1.value)){
changeColor.style.border = "2px solid red";
error1.style.display = "block";
return false;
}
/* empty fild check for password field */
var pas = document.getElementById("pasSword");
var error3 = document.getElementById("error3");
var password = document.loginForm.password;
if(password.value === ""){
pas.style.border = "2px solid red";
error3.style.display = "block";
return false;
}
}
Please help me out of this.
Note: I want to learn "AS YOU TYPE JavaScript for validation". I haven't find any proper tutorial or desiccation.
You are using return false, hence second validation is not working.
Try this:
var valid = true;
if(conditoin_one){
valid = false;
// update error element
}
if(conditoin_two){
valid = false;
// update error element
}
return valid;
My javascript form validation is working correctly. I want it so that when the form is valid, it will go to a different page. I am having trouble with that part. I tried using the document object to submit it if everything is valid but its not working
Javascript:
function func(){
var first = document.getElementById('fname').value;
var last = document.getElementById('lname').value;
var email = document.getElementById('mail').value;
var phone = document.getElementById('phone').value;
var val_phone = /^\(\d{3}\)\d{3}-\d{4}$/;
var val_mail = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
if ( first == "" || last == "" || email == "" || phone == "")
{
alert("Do not Leave Any Blank Answers");
return;
}
if ( phone != phone.match(val_phone) || email != email.match(val_mail) )
{
alert("Incorrect Format! \n Please Check Email and Phone Number! ");
return;
}
else {
document.forms["survey"].sumbit();
}
}
HTML:
<form id="survey" name="survey" action="SlideShow.html" method="post">
First Name:<br>
<input type="text" id="fname" name="fname" required="required"><br>
Last Name:<br>
<input type="text" id="lname" name="lname" required="required"><br>
Email:<br>
<input type="email" id="mail" name="mail" required="required"><br>
Phone Number:<br>
<input type="text" id="phone" name="phone" required="required"><br><br>
<input type="button" value="Submit" onclick="func()">
</form>
Your else block is calling sumbit(), but the proper spelling is submit().
Additionally, I recommend getting in the habit of a strict === check as opposed to a ==.
Here's a JSFiddle with the updated and refactored code:
http://jsfiddle.net/cyeof94g/