I'm trying to create a fun little registration sheet to practice my validation. When I hit the submit button I have two issues. The first issue is my form keeps clearing every input field the moment I hit submit. I tried to use have my onclick = return false but this did nothing. The next issue I'm having is when I hit submit nothing happens at all. I'm not sure where I have messed up but if someone could point it out to me.
<!-- create a function to validate and pass information along -->
function Validation() {
<!-- declare variables -->
var ifErrors = false;
<!-- create the array to display error messages when cycled through -->
var ErrorMessage = new Array();
var myUserName = document.getElementById("txtUsername").value;
var myPassword = document.getElementById("txtPassword").value;
var myFirstName = document.getElementById("txtFirstName").value;
var myLastName = document.getElementById("txtLastName").value;
var myDateOfBirth = document.getElementById("txtDateOfBirth").value;
var myEmail = document.getElementById("txtEmail").value;
var myPhoneNumber = document.getElementById("txtPhoneNumber").value;
var LettersOnly = /^[a-z]+$/;
var DateOfBirthValidate = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/;
var Dates = new Date();
var DateSupplied = document.getElementById("txtDateOfBirth").value;
var PhoneNumberValidate = /^\([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
<!-- Begin validation -->
//validate for username being blank
if (myUserName = "")
{
ifErrors = true;
ErrorMessage.push('Username is required');
}
//validate for username not being 8 or more characters
if(myUserName.length < 8)
{
ifErrors = true;
ErrorMessage.push('Username must be 8 or more characters');
}
//validate for password being blank
if (myPassword == "")
{
ifErrors = true;
ErrorMessage.push('Password is required');
}
//validate for password not being 8 or more characters
if (myPassword.length < 8)
{
ifErrors = true;
ErrorMessage.push('Password must be 8 or more characters');
}
//validate for first name being blank
if (myFirstName == "")
{
ifErrors = true;
ErrorMessage.push('First name can not be blank');
}
//validate for last name being blank
if (myLastName == "")
{
ifErrors = true;
ErrorMessage.push('Last name can not be blank');
}
//validate for date of birth being blank
if (myDateOfBirth == "")
{
ifErrors = true;
ErrorMessage.push('Last name can not be blank');
}
//validate for date of birth not being formatted like (MM/DD/YYYY)
if (document.getElementById("txtDateOfBirth").value.length > 1)
{
if (! (txtDateOfBirth,valueOf().match(DateOfBirthValidate)));
{
ifErrors = true;
ErrorMessage.push('not a valid date of birth');
}
}
//create a variable to hold date, and see if it's greater than the current date
DateSupplied = new Date(DateSupplied);
if (DateSupplied > Dates)
{
ifErrors = true;
ErrorMessage.push('Date supplied can not be greater than the current date');
}
//va;idate for phone number
if (document.getElementById("txtPhoneNumber").value.length > 1)
{
if (! (txtPhoneNumber.valueOf().match(PhoneNumberValidate)))
{
ifErrors = true;
ErrorMessage.push('Phone number is not valid');
}
}
//successful validation
if (ifErrors == false)
{
ifErrors = true;
alert('Your registration has been processed');
//document.getElementById("RegisterForm").reset();
}
//Display list of messages in list
var DisplayMessage = "";
ErrorMessage.forEach(function (message)
{
DisplayMessage += "<li>" + message + "</li>";
}
);
document.getElementById("Errors").innerHTML = DisplayMessage;
}
<body>
<h3>Registration</h3>
<div>
<ul id="Errors"> </ul>
</div>
<br/>
<form ="RegisterForm">
<label id="lblUsername">Username:</label>
<input type="text" id="txtUsername" />
<br/>
<label id="lblPassword">Password:</label>
<input type="password" id="txtPassword" />
<br/>
<label id="lblFirstName">First Name:</label>
<input type="text" id="txtFirstName" />
<br/>
<label id="lblLastName">Last Name:</label>
<input type="text" id="txtLastName" />
<br/>
<label id="lblDateOfBirth">Date of Birth:</label>
<input type="text" id="txtDateOfBirth" />
<br/>
<label id="lblEmail">Email:</label>
<input type="text" id="txtEmail" />
<br/>
<label id="lblPhoneNumber">Email:</label>
<input type="text" id="txtPhoneNumber" />
<br/>
<input type="submit" value="Submit" onclick="Validation(); return false;" />
<input type="reset" value="reset Form" />
</form>
</body>
return false; does not stop the form from being submitted.
In order to achieve this behavior, you have to call .preventDefault() on the click event of the <input>, or on the submit event of the <form>. Example:
<form>
<input type="submit" onclick="someFn(event)">
</form>
<script>
function someFn(e) {
e.preventDefault();
console.log('form not submitted...');
}
</script>
To prevent all submit events in one go (regardless of which form element initiated it) you can call .preventDefault() on the form's onsubmit handler parameter (which is the submit event):
<form onsubmit="someFn(event)">
<input type="submit">
<button>Submit</button>
</form>
<script>
function someFn(e) {
e.preventDefault();
console.log('form not submitted...');
}
</script>
As a side-note, the submit input does not clear out your form. It sends it.
Because you haven't specified an action attribute on your <form> element, the submission is sent to the current URL.
Which, in practice, reloads the page.
Which, in practice renders a brand new instance of the form, obviously empty.
This is also the reason why "nothing happens at all". The default browser behavior when submitting a form is to actually load the <form>'s action URL (whether it's explicitly specified or not). You're navigating to that URL, along with the form's values. Which means you're not allowing the browser to finish running the code in Validation();. To wait around and see the results of Validation function, you have to prevent the default form submission behavior.
Docs:
<form>: MDN, HTML (Living Standard)
<input type="submit">: MDN, HTML (Living Standard)
Event.preventDefault(): MDN, DOM (Living Standard)
Related
My javascript isn't running when I click submit on my form page.
<form onsubmit="validateReg()">
<p>
//email registration
<input type="text" id="e-mail" placeholder="Email" />
</p><p>
//password registration
<input type="text" id="pswd" placeholder="Password" />
</p>
<br>
<input type="submit" class="submit">
</for
I've tried multiple times linking the Javascript to the Html form and on the page when I click submit it doesn't return any of my error alerts.
//HTML
<form onsubmit="validateReg()">
<p>
<input type="text" id="e-mail" placeholder="Email" />
</p><p>
<input type="text" id="pswd" placeholder="Password" />
</p>
<br>
<input type="submit" class="submit">
</form>
//Javascript
//Main Function
function validateReg(){
var email = document.getElementById('e-mail').value;
var password = document.getElementById('pswd').value;
var emailRGEX = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var emailResult = emailRGEX.test(email);
//validate Email
if(emailResult == false){
alert("Please enter a valid email address");
return false;
}
//validate lower case
var lowerCaseLetters = /[a-z]/g;
if(password.value.match(lowerCaseLetters)) {
return true;
}else{
alert("Password needs a lower case!");
return false;
}
//validate upper case
var upperCaseLetters = /[A-Z]/g;
if(password.value.match(upperCaseLetters)){
return true;
}else{
alert("Password needs an upper case!");
return false;
}
//validate numbers
var numbers = /[0-9]/g;
if(password.value.match(numbers)){
return true;
}else{
alert("Password needs a number!");
return false;
}
//validate special characters
var special = /[!##$%^&*(),.?":{}|<>]/g;
if(password.value.match(special)){
return true;
}else{
alert("Password needs a special character!");
return false;
}
if(password.value.length >=8){
return true;
}else{ alert("Password needs to be at least 8 characters");
return false;
}
}
I expect the code to output errors when a password is incorrectly submitted and when a password and email is correctly submitted so out put thank you.
As Oluwafemi put it you could put an event listener on your 'submit' event instead. I would put the event on the submit button though. That way you can stop it on the click event without having to fire the submit of the form. If you update your code it could help with troubleshooting in the future.
It wouldn't take much to modify your code either.
First, you would need to update your form to look like this:
<form id="form">
<p>
<input type="text" id="e-mail" placeholder="Email" />
</p>
<p>
<input type="text" id="pswd" placeholder="Password" />
</p>
<br />
<input id="submitButton" type="submit" class="submit">
</form>
Then add this below your javascript function like so:
document.querySelector("#submitButton").addEventListener("click", function(event) {
event.preventDefault;
validateReg()
}, false);
What this is doing is stopping the submit of the form and doing the check as expected. You can read more on this on the Mozilla developer site.
You will need to add document.getElementById('form').submit(); to any return statement that was set to true.
I did however, update the code to have the submit become the default functionality and the checks just return false if they fail like this:
//Javascript
//Main Function
function validateReg() {
var email = document.getElementById('e-mail').value;
var password = document.getElementById('pswd').value;
var emailRGEX = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var emailResult = emailRGEX.test(email);
//validate Email
if(emailResult == false){
alert("Please enter a valid email address");
return false;
}
//validate lower case
var lowerCaseLetters = /[a-z]/g;
if(password.match(lowerCaseLetters) == null) {
alert("Password needs a lower case!");
return false;
}
//validate upper case
var upperCaseLetters = /[A-Z]/g;
if(password.match(upperCaseLetters) == null){
alert("Password needs an upper case!");
return false;
}
//validate numbers
var numbers = /[0-9]/g;
if(password.match(numbers) == null){
alert("Password needs a number!");
return false;
}
//validate special characters
var special = /[!##$%^&*(),.?":{}|<>]/g;
if(password.match(special) == null){
alert("Password needs a special character!");
return false;
}
if(password.length < 8){
return false;
}
document.getElementById('form').submit();
}
A better way to do this is to add an event listener to your js file and listen for the 'submit' event. Followed by your function.
Furthermore ensure that your js file is added to your script tag in your HTML file. That should work if your logic is correct.
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>
I am using a jQuery for mobile number validation without page refresh on submit button but it is not working and when I click the submitbutton. But with page refresh it works.
Here is my code:
index.html
<html>
<head>
<title>Submit Form Without Refreshing Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" href="css/refreshform.css" />
<script src="js/fresh.js"></script>
</head>
<body>
<div id="mainform">
<!-- Required div starts here -->
<form id="form">
<label>First Name:</label>
<br/>
<input type="text" id="fname" placeholder="First Name"/><br/>
<br/>
<label>Last Name:</label>
<br/>
<input type="text" id="lname" placeholder="Last Name"/><br/>
<br/>
<label>MobliNo:</label>
<br/>
<input type="text" id="mobile" placeholder="Your MobNo"/><br/>
<br/>
<label>ConfirmMobliNo:</label>
<br/>
<input type="text" id="remobile" placeholder="Confirm MobNo"/><br/>
<br/>
<label>Email:</label>
<br/>
<input type="text" id="email" placeholder="Your Email"/><br/>
<br/>
<input type="button" id="submit" value="Submit" onclick = "return Validate()"/>
</form>
</div>
</body>
</html>
refresh.js
$(document).ready(function(){
$("#submit").click(function(){
var fname = $("#fname").val();
var lname = $("#lname").val();
var mobile = $("#mobile").val();
var remobile = $("#remobile").val();
var email = $("#email").val();
// Returns successful data submission message when the entered information is stored in database.
$.post("refreshform.php",{ fname1: fname, lname1: lname, mobile1: mobile, remobile1: remobile, email1: email},
function(data) {
alert(data);
$('#form')[0].reset(); //To reset form fields
});
});
});
function Validate() {
var mobile = document.getElementById("mobile").value;
var pattern = /^\d{10}$/;
if (pattern.test(mobile)) {
alert("Your mobile number : " + mobile);
return true;
}
alert("It is not valid mobile number.input 10 digits number!");
return false;
}
What should I do to achieve validation without page refresh?
$("#submit").click(function(){
var fname = $("#fname").val();
var lname = $("#lname").val();
var mobile = $("#mobile").val();
....
should be
$('#form').submit(function(event){
event.preventDefault();
if (Validate())
{
// Do the posting
var fname = $("#fname").val();
var lname = $("#lname").val();
var mobile = $("#mobile").val();
....
or *)
$('#form').on('submit', function(event){
event.preventDefault();
if (Validate())
{
// Do the posting
var fname = $("#fname").val();
var lname = $("#lname").val();
var mobile = $("#mobile").val();
....
By including event.preventDefault() in the event handler, you block the default action for the element that triggered the event. In this case, the default action is submitting the form, so without this change, the form will still be submitted in the normal way, after it is submitted through AJAX.
*) Side note: on is a bit more flexible for binding events. You can also specify a selector as the second parameter. This way, you can set an event handler in the document (or another containing element), which will automatically be called for events on any child element that matches the given selector. This is especially useful if you have dynamic pages where elements are added or removed, because you won't have to add the event handlers every time you add an element. In this particular case it won't matter much, but I thought I'd let you know. The syntax for that is:
$(document).on('submit', '#form', function(event){
Do it in a slight different way. Remove
onclick = "return Validate()"
from the button and put that inside the click function like this
$("#submit").click(function(){
var valid = Validate();
if(valid){
/// Then your rest of process here.
}
});
Hope that works.
This will just check whether the phone number has 10 digits
function Validate() {
var mobile = document.getElementById("mobile").value;
var remobile = document.getElementById("remobile").value;
if(isNaN(mobile) || isNaN(remobile)){
alert("Invalid. Mobile and re mobile should be numbers only.");
return false;
}
if(mobile.length != 10){
alert("Invalid number. It should be 10 digits only.");
return false;
}
if(remobile.length != 10){
alert("Invalid Re mobile number. It should be 10 digits only.");
return false;
}
if(mobile != remobile){
alert("Mobile and remobile does not match!");
return false;
}
alert("Valid Number.");
return true;
}
in you form use:
<form id="form" onsubmit="return Validate();">
and button just submit:
<input type="submit" id="submit" value="Submit" />
in your js validate code instead of return true
var fname = $("#fname").val();
var lname = $("#lname").val();
var mobile = $("#mobile").val();
var remobile = $("#remobile").val();
var email = $("#email").val();
// Returns successful data submission message when the entered information is stored in database.
$.post("refreshform.php",{ fname1: fname, lname1: lname, mobile1: mobile, remobile1: remobile, email1: email},
function(data) {
alert(data);
$('#form')[0].reset(); //To reset form fields
});
return false;
in this case you will submit form without page refresh
function Validate() {
var mob = /^[1-9]{1}[0-9]{9}$/;
if (mob.test($.trim($("#<%=mobile.ClientID %>").val())) == false) {
alert("Please enter valid mobile number.");
$("#<%=mobile.ClientID %>").focus();
return false;
}
I am trying to validate a form using javascript, Here is my code
<script type="text/javascript">
function prevSubmit(){
var oForm = document.forms[0];
var pass1= oForm.elements["passwd"];
var pass2=oForm.elements["repasswd"];
var flag = 1;
if (pass1.value.length>16) {
document.getElementById("passError").innerHTML = "password may atleast 16 chars";
flag = 0;
}
else
document.getElementById("passError").innerHTML = "";
if(pass1.value<=16 && pass1.value!=pass2.value)
{
document.getElementById("passError").innerHTML = "password must be same";
flag = 0;
}
else
document.getElementById("passError").innerHTML = "";
return flag;
}
</script>
and here is my form element,
<form id="registration_form" action="registration.php" method="post" onsubmit="return prevSubmit();">
<p>
<label>Name</label>
<input type="text" name="name"/>
<span id="NameError"></span>
</p>
<p>
<label>Email</label>
<input type="text" name="email"/>
<span id="emailError"></span>
</p>
<p>
<label>Password</label>
<input type="password" name="passwd"/>
<span id="passError"></span>
</p>
<p>
<label>Repeat Password</label>
<input type="password" name="repasswd"/>
</p>
<input type="submit" class="button" value="sign up"/>
</form>
what I am trying to accomplish is check the password, if no match or greater than 16, then show the message and prevent submission, but its not working, Why?
Use true and false as the values of flag, not 1 and 0. You have to return false to prevent submission, anything else allows submission.
First this error message makes no sense
password may atleast 16 chars
Secondly, your second error check is wrong
if(pass1.value<=16 && pass1.value!=pass2.value)
You are saying if the value is less that the number 16 and the two values do not match.
Why would the value be less that 16? The check should just be
if (pass1.value!=pass2.value)
ANd as the others suggested, use true/false, not 1 and 0 as truthy values.
I agree with answers of Barmar and epascarello.
The if conditions should be implemented in this way:
var oForm = document.forms[0];
var pass1= oForm.elements["passwd"];
var pass2=oForm.elements["repasswd"];
var ctrlError = document.getElementById("passError");
if (pass1.value.length < 16) {
ctrlError.innerHTML = "Password must be at least 16 characters long.";
return false;
}
else if (pass1.value != pass2.value) {
ctrlError.innerHTML = "Passwords do not match.";
return false;
}
else {
ctrlError.innerHTML = "";
return true;
}
just "return false" from javascript method
<input type="submit" class="button" value="sign up" onclick="javascript:return myFunc();"/>
function myFunc()
{
return false;
}
this is basic example of how to prevent submission of form, if we return false then browser/javascript engine prevent further propagation of click event and submission is prevented.
I have some input form on names: owner, number, city
<input id="id_owner" type="text" name="owner" maxlength="250" />
<input id="id_number" type="text" name="number" maxlength="250" />
<input id="id_city" type="text" name="city" maxlength="250" />
How to check if the user has not entered the data to a form (befor sending) that does not show this dialog from this code:
<a type="submit" name"save-continue-to-review" data-toggle="modal" data-target="#dialog" href=""
class="btn primary btn-primary" title="Order">Order
</a>
and it will show another
Here is full code: http://wklej.org/id/927806/
Eventually you'll be able to use HTML5 form validation. But until then, use some jQuery code like this. (only because you tagged the question with jQuery. You could potentially do it with vanilla JS.)
(un-tested code, but should work)
var fields = $('input')
$('form').submit(function(e){
e.preventDefault()
valid = true
fields.each(function(){
if ($(this).val() == null) {
valid = false
}
});
if (valid == true) {
$('form').submit()
} else {
alert("At least one field was not valid!")
}
});
1) Add this on your form
onsubmit="return validateForm(this);"
2)The validate function (checks if fields are empty)
function validateform(formObj)
{
inputs = formObj.GetElementsByTagName('input');
for(i=0; i < inputs.length; i++)
{
if($.trim(inputs[i].value) == '')
{
alert('Field: ' + inputs[i].name + ' is empty!');
return false;
}
}
return true;
}
if ( !$(this).val() ) {
valid = false
}
maybe this post is useful for you