HTML Form won't submit after validaiton with Javascript - javascript

I have questions regarding form submitting in HTML with Javascript.
My Javascript is as follows:
function validateForm() {
var a= document.forms["myForm"]["pname"].value;
var b = document.forms["myForm"]["pemail"].value;
var c = document.forms["myForm"]["pdob"].value;
var d = document.forms["myForm"]["unit of choice"].value;
var els = document.forms["myForm"].elements["Issue[]"];
var f = document.forms["myForm"]["description"].value;
var g = document.forms["myForm"]["pdatee"].value;
var h = document.forms["myForm"]["ptimee"].value;
var isValid = false;
for (i = 0; i < els.length; i += 1) {
if (els[i].checked) {
isValid = true;
}
}
if (a == null || a == "") {
alert("Your name cannot be blank");
}
if (b == null || b == "") {
alert("Enter a valid email address.");
}
if (c == null || c == "") {
alert("Enter a valid Date of Birth. (dd/mm/yyyy)");
}
if (d == null || d == "") {
alert("Unit and Tutor have to be selected.");
}
if (!isValid) {
alert("Must select an Issue.");
}
if (f == null || f == "") {
alert("Must fill in a description.");
}
if (f == null || f == "") {
alert("Must fill in a description.");
}
if (g == null || g == "") {
alert("Preferred date must follow the format set.");
}
if (h == null || h == "") {
alert("Preferred time must follow the format set.");
}
return false;
}
And this is my form with its attributes in HTML:
<form name="myForm" onsubmit="return validateForm()" method="post" action="confirm.html" novalidate="novalidate" >
What happens is that when I click the Submit button after filling in all the requirements(so everything does not return false) , the form won't submit itself.
After reading around regarding return false, I tried adding else{ return true; } but all it does is submit my form without validation at all.
What do I do to make it work with only Javascript and/or HTML? Thank you!

At the end of the submission function, you are returning:
return false;
}
No matter if the validation was successful or not. This prevents the form from submitting. Make sure you are using return true here and correctly validate using a flag and then if the flag is true, return false.
You have already a flag isValid. Replace the above line with:
return isValid;
}

You need to check if your inputs have passed your tests.
You can do that by using your var isValid.
All you need to do is set isValid to false if one of your conditions was not met, and then return isValid.
function validateForm() {
var a= document.forms["myForm"]["pname"].value;
var b = document.forms["myForm"]["pemail"].value;
var c = document.forms["myForm"]["pdob"].value;
var d = document.forms["myForm"]["unit of choice"].value;
var els = document.forms["myForm"].elements["Issue[]"];
var f = document.forms["myForm"]["description"].value;
var g = document.forms["myForm"]["pdatee"].value;
var h = document.forms["myForm"]["ptimee"].value;
var isValid = false;
for (i = 0; i < els.length; i += 1) {
if (els[i].checked) {
isValid = true;
}
}
if (a == null || a == "") {
isValid=false;
alert("Your name cannot be blank");
}
if (b == null || b == "") {
isValid=false;
alert("Enter a valid email address.");
}
if (c == null || c == "") {
isValid=false;
alert("Enter a valid Date of Birth. (dd/mm/yyyy)");
}
if (d == null || d == "") {
isValid=false;
alert("Unit and Tutor have to be selected.");
}
if (!isValid) {
isValid=false;
alert("Must select an Issue.");
}
if (f == null || f == "") {
isValid=false;
alert("Must fill in a description.");
}
if (f == null || f == "") {
isValid=false;
alert("Must fill in a description.");
}
if (g == null || g == "") {
isValid=false;
alert("Preferred date must follow the format set.");
}
if (h == null || h == "") {
isValid=false;
alert("Preferred time must follow the format set.");
}
return isValid;
}

Related

Javascript Validation not working (onSubmit)

Vaidation function called on submit.
HTML
<input type="submit" class="submit" value="submit">
JS
window.load = function() {
var form = document.getElementById('form');
form.onsubmit = function(e) {
return validate(); // will be false if the form is invalid
}
}
Validate()
function validate() {
var x = document.forms["form"]["fname"].value;
var y = document.forms["form"]["pname"].value;
var email = document.forms["form"]["email"].value;
var phone = document.forms["form"]["phone"].value;
var date = document.forms["form"]["date"].value;
var month = document.forms["form"]["month"].value;
var year = document.forms["form"]["year"].value;
return false;
alert('wass');
if (x==null || x == "" || isNaN(x) == false) {
alert("Check Name, It can't have numbers. You can use Roman numbers.");
return false;}
else if (y == null || y == "") {
alert("Picture Name must be filled out");
return false;
}
else if(email == '' || email.indexOf('#') == -1 || email.indexOf('.') == -1)
{
alert("Insert valid Email Address");
return false;
}
else if(phone == ''|| phone <1000000000 || phone >9999999999){
alert("Enter valid phone number");
return false;
}else if(date =='' || date<01 || date >31){
alert("Enter valid Date ");
return false;
}else if(month =='' || month<1 || month >12){
alert("Enter valid Month ");
return false;
}else if(year =='' || year<1800 || year >2016){
alert("Enter valid Year ");
return false;
}
//Function used to make colors red instead of individual codelines
function makeRed(inputDiv){
inputDiv.style.backgroundColor="#AA0000";
//inputDiv.parentNode.style.backgroundColor="#AA0000";
//inputDiv.parentNode.style.color="#FFFFFF";
}
//Function made to clean the divs when the validation is met.
function makeClean(inputDiv){
inputDiv.style.backgroundColor="#FFFFFF";
inputDiv.parentNode.style.backgroundColor="#FFFFFF";
inputDiv.parentNode.style.color="#000000";
}
}
Form still gets submitted. Possible issues?
You'll need to prevent the default form submission using:
e.preventDefault();
Place this above your validate function.
Then use the submit() function on the form to actually submit the form provided your validation passes.
At the minute your form is submitting regardless.
You need to prevent default functionality of form submit, by calling e.preventDefault(). In your case:
window.load = function () {
document.getElementById('form').onsubmit = function (e) {
if (!validate()) {
e.preventDefault();
}
}
}

code does not validate email from a form, in javascpricpt

hi i font know if this is the right place to ask this question but i have a problem with my code that i cannot figure out. i have tried many different algorithms and none work. i am trying to validate email from a form.
here is the code (form is in html)
function isValidString(str) {
var quot = "\"";
if (str.indexOf(quot) != -1)
return false;
var badStr = "$%^&*()_+[]{}<>?אבגדהוזחטיכךלמםנןסעפצקרשת";
var i = 0,
p;
while (i < str.length) {
p = badStr.indexOf(str.charAt(i));
if (p != -1)
return false;
i++;
}
return true;
}
function isValidEmail()
{
var str = document.getElementById("email").value;
document.write("email from isValidEmail(str) = " + email);
if (isEmpty(str) || str.length < 5) {
alert("isEmpty(str) || str.length < 5 = false");
return false;
}
if (!isValidString(str)) {
alert("!isValidString(str) = false");
return false;
}
var atSign = str.indexOf('#');
if (atSign == -1 || str.lastIndexOf('#') || atSign === 0 || atSign == str.length - 1) {
alert("atSign == -1 || str.lastIndexOf('#') || atSign == 0 || atSign == str.length - 1 = false");
return false;
}
var dotSign = str.indexOf('.', atSign);
if (dotSign == -1 || dotSign === 0 || dotSign == str.length - 1 || dotSign - atSign < 2) {
alert("dotSign == -1 || dotSign == 0 || dotSign == str.length - 1 || dotSign - atSign < 2 = false");
return false;
}
return true;
no matter what i input it always comes back valid.
here is the part where i apply it:
var email = document.getElementById("email").value;
if (emailcheck(email)) {
alert("invalid email");
return false;
}
return true;
thanks in advance
An example of using the parser library mentioned in my comment.
var eAddr = document.getElementById('eAddr'),
check = document.getElementById('check'),
pre = document.getElementById('out');
check.addEventListener('click', function (evt) {
pre.textContent = !!emailAddresses.parseOneAddress(eAddr.value.trim());
}, false);
<script src="https://rawgit.com/FogCreek/email-addresses/master/lib/email-addresses.js"></script>
<input id="eAddr"></input>
<button id="check">Test pattern</button>
<pre id="out"></pre>
Note: this will accept Goodhertz Inc <support#goodhertz.com> as it stands and you would need to further check the object returned by parseOneAddress to filter these out.
You don't call the rigth function i. e. call
var email = document.getElementById("email").value;
if (isValidString(email)) {
alert("invalid email");
return false;
}
return true;
instead of
var email = document.getElementById("email").value;
if (emailcheck(email)) {
alert("invalid email");
return false;
}
return true;
Using Regular expression is the best method for validating input elements. Below function can validate email perfectly.
function regExValidate_Email(id) {
var email = document.getElementById(id).value;
if (email != '') {
var regExforEmail = /^[a-zA-Z0-9._+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (regExforEmail.test(email)) {
$("#" + id).css("background-color", "#ffffff");
return true;
}
else {
alert('Please enter a valid email id. \nex: yourname#example.com');
document.getElementById(id).style.backgroundColor = '#feffea';
document.getElementById(id).value = '';
Ctrlid = id;
setTimeout("document.getElementById(Ctrlid).focus()", 1);
return false;
}
}
else { document.getElementById(id).style.backgroundColor = 'white'; }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Email: <input type="email" onblur="return regExValidate_Email(this.id)" id="txtEmail" />

How to I validate a password using regular expressions in javascript?

This is my code. It functions perfectly up to the password validation. It completely ignores my null test and goes straight to the actual validation but then refuses to go past it and keeps giving me my invalid password alert. Any ideas as to how to fix this issue?
function validate(){
var l = document.getElementById('lname').value;
var f = document.getElementById('fname').value;
var e = document.getElementById('email').value;
var e2 = document.getElementById('cemail').value;
var u = document.getElementById('newuser').value;
var p = document.getElementById('newpass');
var p2 = document.getElementById('cnewpass');
var str = new RegExp(/[a-zA-Z]{1,30}$/);
var em = new RegExp(/[a-z0-9._-]+#[a-z]+\.[a-z]{1,30}$/);
var pass = new RegExp(/[a-zA-Z0-9]{1,15}$/);
if (l == null || l == ""){
alert("Please enter your last name");
return false;
}
var ln = str.test(l);
if(ln==false){
alert("Invalid Name.");
documents.forms['registration']['lname'].focus;
return false;
}
if (f == null || f == ""){
alert("Please enter your first name");
return false;
}
var fn = str.test(f);
if(fn==false){
alert("Invalid Name.");
documents.forms['registration']['fname'].focus;
return false;
}
if (e == null || e == "") {
alert("Please enter an email address");
return false;
}
if (e2 == null || e2 == "") {
alert("Please enter an email address");
return false;
}
var eml = em.test(e);
if(eml==false){
alert("Invalid Email.");
documents.forms['registration']['email'].focus;
return false;
}
var eml2 = em.test(e2);
if(eml2==false){
alert("Invalid Email.");
documents.forms['registration']['cemail'].focus;
return false;
}
if(e2!=e){
alert("Please ensure that the emails match.");
return false;
}
if (u == null || u == "") {
alert("Please enter a user name");
return false;
}
var un = str.test(u);
if(un==false){
alert("Invalid user name");
documents.forms['registration']['newuser'].focus;
return false;
}
if (p == null || p == "") {
alert("works");
alert("Please enter a password");
return false;
}
if (p2 == null || p2 == "") {
alert("Please enter a password");
return false;
}
var pwrd = pass.test(p);
if(pwrd==false){
alert("Invalid Password.");
documents.forms['registration']['newpass'].focus;
return false;
}
if(p2!=p){
alert("Please ensure that the passwords match");
documents.forms['registration']['cnewpass'].focus;
return false;
}
}
You should amend js code that retriving data from from. Look,
var p = document.getElementById('newpass');
var p2 = document.getElementById('cnewpass');
Here You are trying to get NOT values of input tags, you are trying to get tag.
So You should replace above code with:
var p = document.getElementById('newpass').value;
var p2 = document.getElementById('cnewpass').value;
I hope it will help you
You should pass the value of password fields.
try changing the code to
var p = document.getElementById('newpass').value;
var p2 = document.getElementById('cnewpass').value;

How to validate multi-functions using Javascript in .asp

I am attempting to validate 6 functions on a form. I am getting the appropriate alerts set for each function but the form does not seem to be validating correctly and is submitting the form when the 'Generate' button is pressed.
I would be extremely grateful for any advice on this
This is how I have it set at present:
function ValidateFields(){
//Validate all Required Fields
if (RequiredTextValidate()&& CheckDateTime()&& ReasonAbsenceValidate()&&
ReturnDateChanged() && FirstDateChanged() && ActualDateChanged())return true;
}
<script type="text/javascript" language="Javascript">
function RequiredTextValidate() {
//check all required fields are completed
if (document.getElementById("<%=CompletedByTextBox.ClientID%>").value == "") {
alert("Completed by field cannot be blank");
document.getElementById("<%=CompletedByTextBox.ClientID%>").focus();
return false;
}
if (document.getElementById("<%=CompletedExtTextBox.ClientID %>").value == "") {
alert("Completed By Extension field cannot be blank");
document.getElementById("<%=CompletedExtTextBox.ClientID %>").focus();
return false;
}
if (document.getElementById("<%=EmployeeNoTextBox.ClientID %>").value == "") {
alert("Employee No field cannot be blank");
document.getElementById("<%=EmployeeNoTextBox.ClientID %>").focus();
return false;
}
if (document.getElementById("<%=EmployeeNameTextBox.ClientID %>").value == "") {
alert("Employee Name field cannot be blank");
document.getElementById("<%=EmployeeNameTextBox.ClientID %>").focus();
return false;
}
return true;
}
function CheckDateTime() {
// regular expression to match required date format
re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
if (document.getElementById("<%=SickDateTextBox.ClientID %>").value != '' && !document.getElementById("<%=SickDateTextBox.ClientID %>").value.match(re)) {
alert("Invalid date format: " + document.getElementById("<%=SickDateTextBox.ClientID %>").value);
document.getElementById("<%=SickDateTextBox.ClientID %>").focus();
return false;
}
// regular expression to match required time format
re = /^\d{1,2}:\d{2}([ap]m)?$/;
if (document.getElementById("<%=SickTimeTextBox.ClientID %>").value != '' && !document.getElementById("<%=SickTimeTextBox.ClientID %>").value.match(re)) {
alert("Invalid time format: " + document.getElementById("<%=SickTimeTextBox.ClientID %>").value);
document.getElementById("<%=SickTimeTextBox.ClientID %>").focus();
return false;
}
return true;
}
function ReasonAbsenceValidate() {
//check that reason for absence field is completed
if (document.getElementById("<%=ReasonTextBox.ClientID%>").value == "") {
alert("Reason for absence field cannot be blank");
document.getElementById("<%=ReasonTextBox.ClientID%>").focus();
return false;
}
return true;
}
function ReturnDateChanged() {
// check that either Return date or Date Unknown fields are completed
var ReturnDateValid = document.getElementById("<%=ReturnDateTextBox.ClientID%>").value;
var ReturnDateUnknown = document.getElementById("<%=ReturnUnknownCheckBox.ClientID%>").checked;
if (ReturnDateUnknown.checked)
{
ReturnDateValid.disabled = false;
ReturnDateUnknown.disabled = "disabled";
}
if (ReturnDateValid == "" && ReturnDateUnknown == "") {
alert("You must enter at least one field for anticipated return");
return false;
}
return true;
}
function FirstDateChanged() {
// check that either First date of sickness or Date Unknown fields are completed
var FirstDateValid = document.getElementById("<%=FirstDateTextBox.ClientID%>").value;
var FirstDateUnknown = document.getElementById("<%=FirstDateUnknownCheckBox.ClientID%>").checked;
if (FirstDateUnknown.checked)
{
FirstDateValid.disabled = false;
FirstDateUnknown.disabled = "disabled";
}
if (FirstDateValid == "" && FirstDateUnknown == "") {
alert("You must enter at least one field for first day of sickness");
return false;
}
return true;
}
function ActualDateChanged() {
// check that either Actual date of return or Date Unknown fields are completed
var ActualDateValid = document.getElementById("<%=ActualDateTextBox.ClientID%>").value;
var ActualDateUnknown = document.getElementById("<%=ActualDateUnknownCheckBox.ClientID%>").checked;
if (ActualDateUnknown.checked)
{
ActualDateValid.disabled = false;
ActualDateUnknown.disabled = "disabled";
}
if (ActualDateValid == "" && ActualDateUnknown == "") {
alert("You must enter at least one field for actual date of return");
return false;
}
return true;
}
function ValidateFields(){
//Validate all Required Fields
if (RequiredTextValidate()&& CheckDateTime()&& ReasonAbsenceValidate()&&
ReturnDateChanged() && FirstDateChanged() && ActualDateChanged())return true;
}
</script>
update function like following:
You need to return flase in case of invalid input to prevent form from being posted.
function ValidateFields() {
//Validate all Required Fields
if (RequiredTextValidate() && CheckDateTime() && ReasonAbsenceValidate() && ReturnDateChanged() && FirstDateChanged() && ActualDateChanged()) {
return true;
} else {
return false;
}
}
Update
if (document.getElementById("<%=SickTimeTextBox.ClientID %>").value != '' &&
!document.getElementById("<%=SickTimeTextBox.ClientID %>").value.match(re))
condition seems to be wrong. It should be like following.
if (document.getElementById("<%=SickTimeTextBox.ClientID %>").value == '' &&
!document.getElementById("<%=SickTimeTextBox.ClientID %>").value.match(re))
Use == instead of != operator.

At least one of two fields must be completed validation

First of all, I am not using jquery validation plugin.
I have the following validation in JavaScript:
var m = mob.substr(0,2);
var l = land.substr(0,2);
if (mob == '' && land == '') {
alert("You must enter at least one phone number");
return false;
}
else if (mob.length != 10 || m != "04") {
alert("Mobile number is invalid. Must be a valid australian mobile number.");
return false;
}
else if (land.length != 10 || l == "04" || l == "01" || l == "05" || l == "06" || l == "09" || l == "00") {
alert("Landline is invalid. Must be a valid australian landline number.");
return false;
}
As the title suggests, I want the user to be able to input just one or both of the fields but not leave both blank.
How can I incorporate this into the validation?
var m = mob.substr(0,2);
var l = land.substr(0,2);
if (mob === '' && land === '') {
alert("You must enter at least one phone number");
return false;
}
if (mob !== '' && (mob.length !== 10 || m !== "04")) {
alert("Mobile number is invalid. Must be a valid australian mobile number.");
return false;
}
if (land !== '' && (land.length !== 10 || l === "04" || l === "01" || l === "05" || l === "06" || l === "09" || l === "00")) {
alert("Landline is invalid. Must be a valid australian landline number.");
return false;
}
return true;
Here just add one more condition to the last two conditions. And make them as independent if statements. So all of them will be evaluated.
Just an idea...
function validate () {
var sMobile = ...;
var sLand = ...;
var lines = parsePhoneLines(sMobile, sLand);
if (lines.errors) {
for (var i = 0, length = lines.errors.length; i < length; i++) {
alert (lines.errors[i]);
}
return false;
} else {
return true;
}
}
function parsePhoneLines (sMobile, sLand) {
var mobile = parseMobile(sMobile),
land = parseLand(sLand);
if (mobile.errors && land.errors) {
return {
errors: mobile.errors.concat(land.errors)
};
} else {
return {
land: land.value,
mobile: mobile.value
};
}
}
function parseMobile (s) {
var errors = getErrorsForMobile(s);
if (errors.length === 0) {
return { value: s };
} else {
return { errors: errors };
}
}
function parseLand (s) {
var errors = getErrorsForLand(s);
if (errors.length === 0) {
return { value: s };
} else {
return { errors: errors };
}
}
Try this:
var m = mob.substr(0,2);
var l = land.substr(0,2);
if (mob == '' && land == '') {
alert("You must enter at least one phone number");
return false;
} else {
if (mob != '') {
if (mob.length != 10 || m != "04") {
alert("Mobile number is invalid. Must be a valid australian mobile number.");
return false;
}
} else {
if (land.length != 10 || l == "04" || l == "01" || l == "05" || l == "06" || l == "09" || l == "00") {
alert("Landline is invalid. Must be a valid australian landline number.");
return false;
}
}
}
return true;
Just need an else clause to the first if.
var m = mob.substr(0,2);
var l = land.substr(0,2);
var flag=1;
if (mob == '' && land == '') {
alert("You must enter at least one phone number");
return false;
}
else if (mob.length != 10 || m != "04") {
if(land.length>0)
{
//landline have value don not alert this
}
else
{
alert("Mobile number is invalid. Must be a valid australian mobile number.");
flag=0;//means invalid
}
}
else if (land.length != 10 || l == "04" || l == "01" || l == "05" || l == "06" || l == "09" || l == "00") {
if(flag==1)
{
return true;// means mobile have value
}
alert("Landline is invalid. Must be a valid australian landline number.");
return false;
}

Categories

Resources