I have written code for a basic registration page to run on my webserver but javascript doesn't seem to be working in the html file. I do a form post with a javascript function to find errors but it seems to be completely ignoring the javascript code when I test it. Is there a problem with my javascript code or in the html code? My code is shown below.
<script type="text/javascript" language="Javascript">
function checkPasswordMatch(){
var password = document.getElementById("pass1").value;
var password2 = document.getElementById("pass2").value;
if(password != password2){
document.getElementById("divcheckpasswordmatch").innerHTML = "Passwords do not match!";}
else{
document.getElementById("divcheckpasswordmatch").innerHTML = "Passwords match.";}
}
// $(document).ready(function(){
// $("#pass2").keyup(checkPasswordMatch);
// })
function Error() {
var user = document.getElementById("user").value;
var pass1 = document.getElementById("pass1").value;
var pass2 = document.getElementById("pass2").value;
var email = document.getElementById("email").value;
if(user=""){
document.form1.username.focus();
document.getElementById("usernameerror").innerHTML = "Enter username.";
return false;
}
if(pass1=""){
document.form1.password1.focus();
document.getElementById("passworderror1").innerHTML = "Enter password.";
return false;
}
if(pass2=""){
document.form1.password2.focus();
document.getElementById("passworderror2").innerHTML = "Enter password.";
return false;
}
if(email=""){
document.form1.useremail.focus();
document.getElementById("emailerror").innerHTML = "Enter email";
return false;
}
}
</script>
</head>
<body>
<div id="link">
Home
<a align="right" href="signin">Sign-in</a>
</div>
<div id="header">
<center><h1><i>IMGCAPTURE</i></h1></center>
</div>
<div id="create">
<center><h2>Create Your Account</h2></center>
<form name="form1" action="account" onsubmit="return Error()" method="POST">
<div id="username"><center><h3>Enter Username: <input type="text" name="username" id="user" cols="15" rows="1"></input></h3></center></div>
<div id="usernameerror"></div>
<div id="password"><center><h3>Enter Password: <input type="password" name="password1" id="pass1" cols="15" rows="1"></input></h3></center></div>
<div id="passworderror1"></div>
<div id="confirmpassword"><center><h3>Re-Enter Password: <input type="password" name="password2" id="pass2" onChange="checkPasswordMatch()" cols="15" rows="1"></input></h3></center></div>
<div id="passworderror2"></div>
<div class="registrationFormAlert" id="divcheckpasswordmatch"></div>
<center><h3>Enter Email: <input type="email" name="useremail" id="email" cols="15" rows="1">
</input></h3></center>
<div id="emailerror"></div>
<center><input type="submit" value="Create Account" onclick="Error()"></input></center>
</form>
</div>
</body>
</html>
It may be that you are not calling the functions you are creating. So since you are not calling those functions with arguments, nothing inside them is going to happen. Let me know if this fixes it.
Also, stylistically you would want the Javascript code at the end of the HTML file.
Instead of binding your input name="password2" to the function by the onChange-tag, try binding it like this:
$(document).on('change', 'input[name="checkPasswordMatch"]', checkPasswordMatch);
function checkPasswordMatch() {
...
}
And in your HTML, remove the onChange tag:
<div id="confirmpassword">
<center>
<h3>
Re-Enter Password: <input type="password" name="password2" id="pass2" cols="15" rows="1"></input>
</h3>
</center></div>
It seems you've forgotten to include jQuery. If you use pure JS, it works :
<script type="text/javascript">
function checkPasswordMatch() {
var password = document.getElementById("pass1").value;
var password2 = document.getElementById("pass2").value;
if (password != password2) {
document.getElementById("divcheckpasswordmatch").innerHTML = "Passwords do not match!";
} else {
document.getElementById("divcheckpasswordmatch").innerHTML = "Passwords match.";
}
}
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("pass2").addEventListener('keyup', checkPasswordMatch);
});
function Error() {
var user = document.getElementById("user").value;
var pass1 = document.getElementById("pass1").value;
var pass2 = document.getElementById("pass2").value;
var email = document.getElementById("email").value;
if (user = "") {
document.form1.username.focus();
document.getElementById("usernameerror").innerHTML = "Enter username.";
return false;
}
if (pass1 = "") {
document.form1.password1.focus();
document.getElementById("passworderror1").innerHTML = "Enter password.";
return false;
}
if (pass2 = "") {
document.form1.password2.focus();
document.getElementById("passworderror2").innerHTML = "Enter password.";
return false;
}
if (email = "") {
document.form1.useremail.focus();
document.getElementById("emailerror").innerHTML = "Enter email";
return false;
}
}
</script>
You probably want to use == or === in your if statements. You're assigning user, etc. to an empty string in your if conditionals.
if(user == ""){
document.form1.username.focus();
document.getElementById("usernameerror").innerHTML = "Enter username.";
return false;
}
Related
I currently have a form with a few variables like username, password, and email which sends the data to a node.js server. Before sending the data, I have a few checks such as whether the inputs are valid and whether the email already exists in my file. The checking aspect of my code works, however the javascript function which I use to check returns before opening the file to check for duplicate emails. I feel that if I could somehow make the onsubmit function asynchronous, that would help.
Here is my code and the segment where I check for duplicate emails is near the end:
<html>
<body>
<form id='form' action="/signup.html" method="POST" onsubmit="return submitIt();">
<div style="text-align:center">
<label for="name">Full Name</label><br>
<input type="text" size="100" id="name" name="name" placeholder="Enter Your Full Name: "><br><br>
<label for="email">Email</label><br>
<input type="text" size="100" id="email" name="email" placeholder="Enter Your Email: "><br><br>
<label for="password">Password</label><br>
<input type="text" size="100" id="password" name="password" placeholder="Enter Your Password: "><br><br>
<button type="submit" id="submit">Submit</button>
</div>
</form>
</body>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
var ret = true;
async function submitIt() {
let name = document.getElementById("name").value;
let email = document.getElementById("email").value;
let password = document.getElementById("password").value;
if (name == "" || name.length < 4) {
document.getElementById("name").value = "";
document.getElementById("name").placeholder = "Please enter a real name";
ret = false;
}
if (email == "" || email.length < 4) {
document.getElementById("email").value = "";
document.getElementById("email").placeholder = "Please enter a real email";
ret = false;
}
if (ret) {
let found = false;
for (let i = 0; i < email.length; i++) {
if (email[i] == '#') {
found = true;
}
}
if (!found) {
document.getElementById("email").value = "";
document.getElementById("email").placeholder = "Please enter a real email";
ret = false;
}
}
if (password.length < 5) {
document.getElementById("password").value = "";
document.getElementById("password").placeholder = "Password must be atleast 5 characters.";
ret = false;
}
await $.ajax({
type:"POST",
url:'/getUsers',
dataType: "text",
success: function(content) {
let contents = content.split('\n');
for (let i = 0; i < contents.length; i += 3) {
if (contents[i] == email) {
document.getElementById("email").value = "";
document.getElementById("email").placeholder = "Email already in use.";
ret = false;
}
}
}
});
return ret;
}
</script>
</head>
</html>
Any help would be greatly appreciated!
Have you tried moving onSumbmit call from form to the button?
const submitButton = document.getElementById(***)
submitButton.addEventListener('click', () => {your code})
Another way could be preventing default behavior of the submit form.
async function submitIt(event) {
event.preventDefault;
event.stopImmediatePropagation;
....your code....
}
I don't have access to a PC right now to check it, but one of the provided solutions should work. Cheers!
I have a simple form. Ive tried to disable the the submit button until fields have been filled out, however it seems to not be working. can anyone point me in the right direction to what I'm doing wrong.
<form id="casmansForm">
Name: <input type="name" id="userName" class="inputs"><br>
Email: <input type="name" id="userName" class="inputs"><br>
Text: <input type="name" id="userName" class="inputs"><br>
<input type="submit" id="userSubmit" disabled><br>
</form>
<div id='alertMessage'></div>
var userName = document.getElementById('userName');
var userEmail = document.getElementById('userEmail');
var userText = document.getElementById('userText');
var userSubmit = document.getElementById('userSubmit');
var alertMessage = document.getElementById('alertMessage');
function checkForm(){
if(userName.value == "" || userEmail.value == "" || userText.value == "")
{
alertMessage.innerHTML = 'Please fill in form correctly';
userSubmit.disabled = true;
return false;
} else {
alertMessage.innerHTML = 'Thank you for filling in form';
userSubmit.disabled = false;
return true;
}
}
userName.addEventListener("blur",checkForm,false);
userEmail.addEventListener("blur",checkForm,false);
userText.addEventListener("blur",checkForm,false);
Your main issue is that you have used the same id on more than one element. ids must be unique within a document.
Also, return false is not doing anything for you in this context.
Lastly, don't use .innerHTML when you aren't supplying any HTML, use textContent for that instead.
var userName = document.getElementById('userName');
var userEmail = document.getElementById('userEmail');
var userText = document.getElementById('userText');
var userSubmit = document.getElementById('userSubmit');
var alertMessage = document.getElementById('alertMessage');
function checkForm(){
if(userName.value == "" || userEmail.value == "" || userText.value == "") {
alertMessage.textContent = 'Please fill in form correctly';
userSubmit.disabled = true;
} else {
alertMessage.textContent = 'Thank you for filling in form';
userSubmit.disabled = false;
}
}
userName.addEventListener("blur",checkForm,false);
userEmail.addEventListener("blur",checkForm,false);
userText.addEventListener("blur",checkForm,false);
<form id="casmansForm">
Name: <input type="name" id="userName" class="inputs"><br>
Email: <input type="name" id="userEmail" class="inputs"><br>
Text: <input type="name" id="userText" class="inputs"><br>
<input type="submit" id="userSubmit" disabled>
</form>
<div id='alertMessage'></div>
I have the following code:
function passVerif() {
if (document.forms['form'].pass.value === "") {
messagePV.innerHTML = ("Password field is empty!")
//alert("Password field is empty!");
return false;
}
return true;
}
function emailVerif() {
if (document.forms['form'].email.value === "") {
messageEV.innerHTML = ("Email field is empty!")
//alert("Email field is empty!");
return false;
}
return true;
}
function validate() {
var email = document.getElementById("input").value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (!emailFilter.test(email)) {
messageV.innerHTML = ("Please enter a valid e-mail address!")
//alert('Please enter a valid e-mail address!');
return false;
}
}
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br>
<input type="button" name="required" onclick="return passVerif(), emailVerif(), validate()">
</form>
</div>
<div id="messagePV"></div>
<div id="messageEV"></div>
<div id="messageV"></div>
As you can see, input type is submit. Because of that (page is refreshing after click on button) the text I want to show disappears after refresh.
As I read on other posts, the simple change from submit to button will do the dew.
But I am suspecting that I messed up the return false and return true instructions in all of my functions.
Is this correct? If they are in a logical way I can avoid the page refresh and continue to use submit? At least until all conditions are met and the form is good to go.
In other words, can someone help me to put return false and true in such way that the page will refresh only if all conditions are met.
Thanks a lot, I am not even a noob.
Codes are copied from different sources on the internet. I am at the very beginning of coding road. Please have mercy :)
I would change it to one validation function and have a bool that is returned based on if it has errored or not:
// Just have one validation function
function validate() {
var errorMessage = ''; // build up an error message
var email = document.forms['form'].email.value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (email === "") {
errorMessage += "Email field is empty!<br>";
} else if (!emailFilter.test(email)) { // this can be else if
errorMessage += "Please enter a valid e-mail address!<br>";
}
if (document.forms['form'].pass.value === "") {
errorMessage += "Password field is empty!<br>"
}
if (errorMessage === '') {
return true; // return true as no error message
} else {
document.getElementById('error-message').innerHTML = errorMessage; // show error message and return false
return false;
}
}
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br>
<input type="submit" name="required" onclick="return validate();">
</form>
</div>
<div id="error-message">
<!-- CAN HAVE ONE ERROR MESSAGE DIV -->
</div>
I tried with your code and I could find the the messages were not getting updated based on the conditions. So I did few modifications to your code to display the message based on which condition fails.
HTML
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br><br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br><br>
<input type="submit" name="required" value="Submit" onclick="return passVerif(), emailVerif(), validate()">
</form>
</div>
<div id="messagePV"></div>
<div id="messageEV"></div>
<div id="messageV"></div>
JS
function passVerif() {
messagePV.innerHTML = ("")
if(document.forms['form'].pass.value === "") {
messagePV.innerHTML = ("Password field is empty!")
//alert("Password field is empty!");
return false;
}
return true;
}
function emailVerif() {
messageEV.innerHTML = ("")
if(document.forms['form'].email.value === "") {
messageEV.innerHTML = ("Email field is empty!")
//alert("Email field is empty!");
return false;
}
return true;
}
function validate() {
messageV.innerHTML = ("")
var email = document.getElementById("input").value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (!emailFilter.test(email)) {
messageV.innerHTML = ("Please enter a valid e-mail address!")
//alert('Please enter a valid e-mail address!');
return false;
}
}
By initializing the errormessage filed to empty sting u can maintain the fresh set of error messages.
Jsfiddle: https://jsfiddle.net/85w7qaqx/1/
Hope this helps out.
struggling to understand why the append element doesn't work in my JS.
Here's the JavaScript file and the HTML file is below.
JS file.
var ck_name = /^[A-Za-z0-9 ]{3,20}$/;
var ck_email = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var ck_username = /^[A-Za-z0-9_]{1,20}$/;
var ck_password = /^[A-Za-z0-9!##$%^&*()_]{6,20}$/;
function validate(form){
var name = form.name.value;
var email = form.email.value;
var username = form.username.value;
var password = form.password.value;
var errors = [];
if (!ck_name.test(name)) {
errors[errors.length] = "You valid Name .";
}
if (!ck_email.test(email)) {
errors[errors.length] = "You must enter a valid email address.";
}
if (!ck_username.test(username)) {
errors[errors.length] = "You valid UserName no special char .";
}
if (!ck_password.test(password)) {
errors[errors.length] = "You must enter a valid Password ";
}
if (errors.length > 0) {
errors.forEach(function(entry){
$('#errors').append("<li>" + entry +"</li>")
});
}
}
index.html
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="main.css">
</head>
<body>
<form name="form" action="#" onSubmit="validate(this)" method="post">
<input type="text" name="name" />
<input type="text" name="email" />
<input type="text" name="username" />
<input type="password" name="password" />
<ul id="errors"></ul>
</form><body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="form-validator.js"></script>
</body>
</html>
Any help would be greatly appreciated. The error messages appear for awhile before the form redirects to '#'.
I assume that if there are errors, you don't want the form to submit. You should then return false when there are errors.
Change these lines in the validate() function:
if (errors.length > 0) {
errors.forEach(function(entry){
$('#errors').append("<li>" + entry +"</li>")
});
return false;
}
return true;
And change this on the <form> element:
onSubmit="return validate(this);"
Try a separate validation button:
function validate() {
var valid = true;
var ck_name = /^[A-Za-z0-9 ]{3,20}$/;
var ck_email = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var ck_username = /^[A-Za-z0-9_]{1,20}$/;
var ck_password = /^[A-Za-z0-9!##$%^&*()_]{6,20}$/;
function validate(form) {
var name = form.name.value;
var email = form.email.value;
var username = form.username.value;
var password = form.password.value;
var errors = [];
if (!ck_name.test(name)) {
errors[errors.length] = "You invalid Name .";
valid = false;
}
if (!ck_email.test(email)) {
errors[errors.length] = "You must enter a valid email address.";
valid = false;
}
if (!ck_username.test(username)) {
errors[errors.length] = "You valid UserName no special char .";
valid = false;
}
if (!ck_password.test(password)) {
errors[errors.length] = "You must enter a valid Password ";
valid = false;
}
if (errors.length > 0) {
errors.forEach(function(entry) {
$('#errors').append("<li>" + entry + "</li>")
});
}
if (valid) {
$('#realSubmit').click();
} else {
alert('Please fill out all fields!');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form" action="#" onSubmit="validate(this)" method="post">
<input type="text" name="name" />
<input type="text" name="email" />
<input type="text" name="username" />
<input type="password" name="password" />
<ul id="errors"></ul>
<button type="button" onclick="validate()">Submit</button>
<button type="submit" id="realSubmit" style="display:none"></button>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
Hint. The page should NOT refresh. Your validations errors will stick if the page doesn't refresh. Instead of a submit button, use a regular button, bind a click event on it and handle the validation in there.
This is a common pitfall for beginning JS programmers, unless you do want the whole page to reload, don't make it reload via the regular form submit action.
Steps
Use a regular button for submission, like so...
<input type='button' id='submitMe' value='Submit' />
and in your jquery code, do something like so...
$(document).on('click', 'button#submitMe', function() {
// your validation code goes here...
...
return false; // do not make it bubble up the DOM
});
I want to keep viewers from entering words like "fssadf", and force them to enter a valid email which must contain the "#" in the middle and "." to prevent spam and injection.
I also want the form to display an error message that says "change the email field to the correct email"
I use js_function.js which contain this:
function validEmail()
{
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var email_address = $("#email").val();
if(reg.test(email_address) == false)
return false;
else
return true;
}
but it does not prevent the viewer from sending me "sfdasfd" instead of a valid email.
What can I do to achieve the above?
check out the files below:
http://www.mediafire.com/?kx5bvttc0s2fbrs
thanks,
rami
Though I didn't see any error on my program what you provided but still you may
use
var reg = /^[_a-z0-9]+(\.[a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
instead of this
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
I think that will help. I provided the total Javascript code what worked properly for me.
function validEmail()
{
var reg = /^[_a-z0-9]+(\.[a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
var email_address = $("#email").val();
if(reg.test(email_address) == false)
return false;
else
return true;
}
Use this
or you may use this too in other way
HTML
<form>
//Other Codes
<input type="text" name="email" id="email" onchange="validate(this.value)" />
//Other Codes
</form>
And Javascript
<script>
function validate(email)
{
var reg = /^[_a-z0-9]+(\.[a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
if(reg.test(email) == false)
{
alert("This is a invalid Email Address!");
document.getElementById('email').value = '';
document.getElementById('email').focus();
return false;
}
else{
return true;
}
}
</script>
OR
HTML
<form>
//Other Codes
<input type="text" name="email" id="email" onchange="validate()" />
//Other Codes
</form>
And Javascript
<script>
function validate()
{
var reg = /^[_a-z0-9]+(\.[a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
var email = document.getElementById('email').value;
if(reg.test(email) == false)
{
alert("This is a invalid Email Address!");
document.getElementById('email').value = '';
document.getElementById('email').focus();
return false;
}
else{
return true;
}
}
</script>
And the last solution will be quiet easier to apply I think.
Error Message on Page instead of Popup
HTML
<form>
//Other Codes
<input type="text" name="email" id="email" onchange="validate()" />
<span id="errormessage"></span>
//Other Codes
</form>
And Javascript
<script>
function validate()
{
var reg = /^[_a-z0-9]+(\.[a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
var email = document.getElementById('email').value;
if(reg.test(email) == false)
{
document.getElementById('errormessage').innerHTML= 'fill your email';
document.getElementById('email').value = '';
document.getElementById('email').focus();
return false;
}
else{
document.getElementById('errormessage').innerHTML= '';
return true;
}
}
</script>
try with this
$(document).ready(function() {
$('#btn-submit').click(function() {
$(".error").hide();
var hasError = false;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailaddressVal = $("#UserEmail").val();
if(emailaddressVal == '') {
$("#UserEmail").after('<span class="error">Please enter your email address.</span>');
hasError = true;
}
else if(!emailReg.test(emailaddressVal)) {
$("#UserEmail").after('<span class="error">Enter a valid email address.</span>');
hasError = true;
}
if(hasError == true) { return false; }
});
});
Duplicate of this question:
Validate email address in JavaScript?
There is some valuable discussion in the comments about edge cases that SHOULD NOT be ignored.
Did you try to Google this one before you asked? IT is a /very/ common question.
If you're after a pure HTML5 solution using jQuery.... Here's a live demo
HTML
<form id="form">
Email <input name="field1" required="required" type="email" /> <br />
<div id="error"></div>
<input required="required" name="submit" type="submit" />
</form>
Code
$(document).ready(function() {
var validCheckInput = function() {
if ($(this)[0].checkValidity()) {
$(this).removeClass("error");
$("#error").empty();
} else {
$(this).addClass("error");
$("#error").text("change the email field to the correct email");
}
if ($("#form")[0].checkValidity()) {
$("#form input[type='submit']").removeAttr("disabled");
} else {
$("#form input[type='submit']").attr("disabled", "disabled");
}
};s
var binds = function(validCheck) {
$(this).change(validCheck);
$(this).focus(validCheck);
$(this).keyup(validCheck);
validCheck.call($(this));
}
$("#form input").each(function() {binds.call(this, validCheckInput)});
});
CSS
.error {
border: 2px solid red;
}