JavaScript validation - document.getElementById not working in Bootstrap modal - javascript

I am using an onSubmit() function to validate form entries.
The form and validation function work OK,if the form is in a standalone php file or an html file.
But when the form is embedded in a Bootstrap modal the JS validation function throws an error message. [object HTMLInputElement]
I have tried changing document.getElementById('uemail') to document.getElementById('uemail').value as recommended in another answer,
but no value has apparently been passed to the function.
If I remove the onSubmit() attribute then the values are passed correctly to the action script on the server.
This must be common usage. What am I doing wrong?
This is an abbreviated section of my code:
<script>
function formCheck() {
var valid = true;
//alert('in function');
var email = document.getElementById('uemail');
alert('email:' + email);
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email)) {
alert('Please provide a valid email address');
email.focus;
valid = false;
}
return valid;
}
</script>
<form id="regform" action="action.php" method="post" onSubmit="return formCheck()">
Email: <input type="text" name="uemail" id="uemail" size="50" value="" required><span id ="ast">*</span><br>
<input type="submit" name="Submit" value="Register" />
</form>

EDIT: looks like you can't do document.getElementById, you can do this instead:
function formCheck(formEl) {
//...
var email = formEl.getElementsByTagName("input")[0].value;
// this will get the first input-element in your form
and
onsubmit="return formCheck(this)"
Mistake: The variable email you are testing is a HTMLElement, not a string:
Solution: set email to the value of the HTMLInputElement:
var email = document.getElementById('uemail').value;
also email.focus; is not doing anything, use email.focus();
Demo:
function formCheck() {
var valid = true;
//alert('in function');
var email = document.getElementById('uemail').value;
alert('email:' + email);
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email)) {
alert('Please provide a valid email address');
email.focus;
valid = false;
}
return valid;
}
<form id="regform" action="action.php" method="post" onsubmit="alert(formCheck())">
Email:
<input type="text" name="uemail" id="uemail" size="50" value="" required><span id="ast">*</span>
<br>
<input type="submit" name="Submit" value="Register" />
</form>

Related

JavaScript Email address validation

I am making an HTML form with fields validation using JavaScript. I am stuck on email validation. I searched internet and found something like this-
JS Code
function validateemail() {
var x=document.myform.email.value;
var atposition=x.indexOf("#");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length) {
alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);
return false;
}
}
HTML Code
<body>
<form name="myform" method="post" action="#" onsubmit="return validateemail();">
Email: <input type="text" name="email"><br/>
<input type="submit" value="register">
</form>
Please explain me this?
Check this i am using something like this i minified some of them
You must Enter Valid Email address something like this Example#example.com
$(document).ready(function() {
$('.insidedivinput').focusout(function() {
$('.insidedivinput').filter(function() {
var emil = $('.insidedivinput').val();
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (emil.length == 0) {
$('.fa-check').css('display', 'none');
$('.fa-close').css('display', 'inline');
$('.sendmailbuttontrigger').attr('disabled', 'disabled');
$('.SendEmail').attr('disabled', 'disabled');
} else if (!emailReg.test(emil)) {
$('.SendEmail').attr('disabled', 'disabled');
$('.sendmailbuttontrigger').attr('disabled', 'disabled');
$('.fa-check').css('display', 'none');
$('.fa-close').css('display', 'inline');
} else {
// alert('Thank you for your valid email');
$('.fa-close').css('display', 'none');
$('.sendmailbuttontrigger').removeAttr('disabled');
$('.fa-check').css('display', 'inline');
}
})
});
});
.fa-check{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='email' class='insidedivinput'><i class='fa-check'>Validated</i><i class="fa-close">UnValidated</i>
<button class="sendmailbuttontrigger" disabled>
Send
</button>
If you just want to validate an email address, you can use the validation that's built into HTML:
<form onsubmit="return false;">
<input type="email" required="1">
<input type="submit">
</form>
(Leave out the onsubmit for your own form, of course. It's only in my example to keep you from leaving the page with the form.)
I also searched on the Internet and use this one and it's working.
// email validation
checkEmail = (inputvalue) => {
const pattern = /^([a-zA-Z0-9_.-])+#([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
if (pattern.test(inputvalue)) return true;
return false;
}

Can't submit form through javascript to php

I have a form in html which I want to run verification in Javascript first before POST ing to PHP. However the link up to the PHP section does not seem to be working despite the fact that I have assigned names to each input tag and specified an action attribute in the form tag.
Here is the HTML code for the form:
<form id="signupform" action="signupform.php" method="post">
<input type="text" name="Email" placeholder="Email Address" class="signupinput" id="email" />
<br />
<input type="password" name="Password" placeholder="Password" class="signupinput" id="passwordone" />
<br />
<input type="password" placeholder="Repeat Password" class="signupinput" id="passwordtwo" />
<br />
<input type="button" value="Sign Up" class="signupinput" onClick="verifypass()" id="submit" />
</form>
The button calls the javascript function which I use to verify the values of my form before sending to php:
function verifypass() {
var form = document.getElementById("signupform");
var email = document.getElementById("email").value;
var password1 = document.getElementById("passwordone").value;
var password2 = document.getElementById("passwordtwo").value;
var emailcode = /^(([^<>()\[\]\\.,;:\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 (emailcode.test(email)) {
if (password1.length > 6) {
if (password1 == password2) {
form.submit(); //this statement does not execute
} else {
$("#passwordone").notify("Passwords do not match!", {
position: "right"
})
}
} else {
$("#passwordone").notify("Password is too short!", {
position: "right"
})
}
} else {
$("#email").notify("The email address you have entered is invalid.", {
position: "right"
})
}
}
For some reason, some JavaScript implementations mix up HTML element IDs and code. If you use a different ID for your submit button it will work (id="somethingelse" instead of id="submit"):
<input type="button" value="Sign Up" class="signupinput" onClick="verifypass()" id="somethingelse" />
(I think id="submit" has the effect that the submit method is overwritten on the form node, using the button node. I never figured out why, perhaps to allow shortcuts like form.buttonid.value etc. I just avoid using possible method names as IDs.)
I'm not sure why that's not working, but you get around having to call form.submit(); if you use a <input type="submit"/> instead of <input type="button"/> and then use the onsubmit event instead of onclick. That way, IIRC, all you have to do is return true or false.
I think it would be better if you do it real time, for send error when the user leave each input. For example, there is an input, where you set the email address. When the onfocusout event occured in Javascript you can add an eventlistener which is call a checker function to the email input.
There is a quick example for handling form inputs. (Code below)
It is not protect you against the serious attacks, because in a perfect system you have to check on the both side.
Description for the Javascript example:
There is two input email, and password and there is a hidden button which is shown if everything is correct.
The email check and the password check functions are checking the input field values and if it isn't 3 mark length then show error for user.
The showIt funciton get a boolean if it is true it show the button to submit.
The last function is iterate through the fields object where we store the input fields status, and if there is a false it return false else its true. This is the boolean what the showIt function get.
Hope it is understandable.
<style>
#send {
display: none;
}
</style>
<form>
<input type="text" id="email"/>
<input type="password" id="password"/>
<button id="send" type="submit">Send</button>
</form>
<div id="error"></div>
<script>
var fields = {
email: false,
password: false
};
var email = document.getElementById("email");
email.addEventListener("focusout", emailCheck, false);
var password = document.getElementById("password");
password.addEventListener("focusout", passwordCheck, false);
function emailCheck(){
if(email.value.length < 3) {
document.getElementById("error").innerHTML = "Bad Email";
fields.email = false;
} else {
fields.email = true;
document.getElementById("error").innerHTML = "";
}
show = checkFields();
console.log("asdasd"+show);
showIt(show);
}
function passwordCheck(){
if(password.value.length < 3) {
document.getElementById("error").innerHTML = "Bad Password";
fields.password = false;
} else {
fields.password = true;
document.getElementById("error").innerHTML = "";
}
show = checkFields();
console.log(show);
showIt(show);
}
function showIt(show) {
if (show) {
document.getElementById("send").style.display = "block";
} else {
document.getElementById("send").style.display = "none";
}
}
function checkFields(){
isFalse = Object.keys(fields).map(function(objectKey, index) {
if (fields[objectKey] === false) {
return false;
}
});
console.log(isFalse);
if (isFalse.indexOf(false) >= 0) {
return false;
}
return true;
}
</script>

PHP Code for Email Comparison / Verification

I am trying to create a function to compare two email fields.
As in :
Email : <input type="text" name="email" id="email" value="<?=$email?>"
required>
Confirm email : <input type="text" name="email2" id="email2"
onblur="confirmEmail()" value="<?=$email2?>" required>
Here is the JavaScript code I inserted into my HTML :
<script type="text/javascript">
function confirmEmail() {
var email = document.getElementById("email").value
var email2 = document.getElementById("email2").value
if (email != email2) {
alert('Email Not Matching!'); }
}
</script>
The code works.
Once the user enters the second email address, localhost displays an alert, saying : "Email not matching"
For extra-measure, I inserted the following into the form's properties : onsubmit="return confirmEmail()
So, if the user ignores the first warning, he gets a second warning when he tries to press the SUBMIT button.
Unfortunately, this is where I am stuck. Because : after the second warning, if the user still does not modify the "confirm email" , the SUBMIT button still works The form gets sent.
How can I modify the code, so that : the error message continues to display until the user changes the email2 correctly??
(I tried using the WHILE function, and the DO....WHILE function. They worked............except that, the error-message kept displaying over and over.........and did not allow me to make the required correction to the email field (haha). I had to close the window completely)
First, give your submit button an ID like this:
<input type="submit" value="Submit" id="mySubmit" disabled="disabled">
And in your if block add:
if (email !== email2) {
alert('Not matching')
document.getElementById("mySubmit").disabled = true;
}else{
document.getElementById("mySubmit").disabled = false;
}
What you could do is:
<script type="text/javascript">
var count=0;
function confirmEmail() {
var email = document.getElementById("email").value
var email2 = document.getElementById("email2").value
function chkEmail(){
if (email != email2 && count==0)
{ alert('Email Not Matching!'); count++ }
else if(email!=email2 && count ==1)
//display warning
}
chkEmail();
}
</script>
I would submit the form with JavaScript.
<form>
Email : <input type="text" name="email" id="email" value="<?=$email?>"
required>
Confirm email : <input type="text" name="email2" id="email2"
onblur="confirmEmail()" value="<?=$email2?>" required>
</form>
<button onclick="formSubmit()">Learn More</button>
Your formSubmit() function would simply pull in the values and submit them after the proper check. This way, regardless of what the user enters, it has to go through your verification before it is submitted.
function formSubmit() {
var email = document.getElementById("email").value;
var email2 = document.getElementById("email2").value;
if (email != email2) {
alert('Email Not Matching!');
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","/Your/Path/To/Your/Form-Processing/?email="+email,true);
xmlhttp.send();
}
The function above will go in your script tags. It checks email and email2 against each and then submits email with GET to the processing page the same way your form would. You can also pass other variables the same way by getting them with document.getElementById('#id').value and then send them through the GET method.
try this bro,
<form name="form" method="post" action="">
Email : <input type="text" name="email" id="email" value="<?=$email?>" required>
Confirm email : <input type="text" name="email2" id="email2" value="<?=$email2?>" required>
<input type="submit" value="submit" onsubmit="return confirmEmail();"/>
</form>
and in java script
<script type="text/javascript">
function confirmEmail() {
var email = document.getElementById("email").value;
var email2 = document.getElementById("email2").value;
if (email != email2)
{ alert('Email Not Matching!'); return false; }
else {
return true;
}
}
</script>

validation tells that all my email addresses are invalid

I do not know why it is telling me always that is an invalid email address even when it is correct.Any ideas? Demo on JSfiddle
my form
<form id="FormViewForm" method="post" action="/NewsletterMailer/subscribe/4" accept-charset="utf-8">
<input type="hidden" name="_method" value="POST" />
<input type="hidden" name="data[Form][id]" value="4" id="FormId" />
<input type="hidden" name="data[Form][type]" value="1" id="FormType" />
<input type="email" name="data[Form][e-mail]" value="" id="subscribe-email" placeholder="Enter your email..." required>
<input type="submit" value="+" class="large" id="subscribe-submit">
</form>
my custom.js
$('#FormViewForm').submit(function() {
validateEmail($('input').val());
return false;
});
function validateEmail(email) {
var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
if (re.test(email)) {
if (email.indexOf('#c-e.com', email.length - '#c-e.com'.length) !== -1) {
alert('Submission was successful.');
} else {
alert('Email must be a CE e-mail address (your.name#c-e.com).');
}
} else {
alert('Not a valid e-mail address.');
}
}
Simply a jQuery selector issue, you're missing a #.
validateEmail($('#subscribe-email').val());
Your function receives undefined as an e-mail and the regex fails.
You could also use pure JavaScript. (Note that document.getElementById does not require the #, which might have caused the confusion.)
validateEmail(document.getElementById('subscribe-email').value);
Please use right selector like
If you want to user id as selector
validateEmail($('#subscribe-email').val());
Or you can also use input tag as selector
validateEmail($('input[type=email]').val());
The id selector will be strong to all browser and also safe to use
Please try this code
$('#FormViewForm').submit(function() {
validateEmail($('#subscribe-email').val());
return false;
});
function validateEmail(email) {
var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
if (re.test(email)) {
if (email.indexOf('#c-e.com', email.length - '#c-e.com'.length) !== -1) {
alert('Submission was successful.');
} else {
alert('Email must be a CE e-mail address (your.name#c-e.com).');
}
} else {
alert('Not a valid e-mail address.');
}
}

form validation with onsubmit always return true take action

I have one form which i am trying to validate with javascript alert ok!
code is -
<form class="testimonialForm" id="testimonialForm" name="testimonialForm"
method="post" enctype="multipart/form-data" action="addtestimonial.php"
onSubmit="return validateForm()">
<li><label for="name">Name <em>*</em></label>
<input name="testimonial_submitter_name" value="{$testimonial_submitter_name}"
id="testimonial_submitter_name"
class="required" minlength="2" placeholder="your name here!"/>
</li>
and the javascript i used is
function validateForm()
{
var v1=document.getElementById("testimonial_submitter_name").value;
var v2=document.getElementById("testimonial_title").value;
if(v1=="")
alert ("enter the name");
}
Though if empty form is submitted it alert what is given to display in alert box.
But the form get submitted!
What is the problem?
How to solve? help me out !
Thanks in advance!
function validateForm() {
var name = document.getElementById("testimonial_submitter_name").value;
var title = document.getElementById("testimonial_title").value;
if (name == "") {
alert("enter the name");
return false;
}
return true;
}

Categories