How to validate with Javascript? - javascript

Thanks to having to work so much, I am completely confused on JavaScript. I have tried so many things and have not gotten my form to validate even once. I have to use plain JavaScript to:
**Validate the email - the email must have # and the domain should be yahoo.com
Phone No.: Must contain exactly 10 digits
Age: Must be a positive number less than 120
The validation should happen when the user submits the form. In case any of the above validation fails, the corresponding fields should be highlighted in red
If the validation is successful, the page should redirect to http://yahoo.com**
I'm not looking for someone to necessarily give me the exact answer, but push me in the right direction, because I do have a basic understanding of JS.
<!DOCTYPE HTML>
<div id="form">
<form name="myForm" action="http://fsu.edu" onsubmit="return validateForm()" method="post">
<head>
<link rel="stylesheet" HREF="C:\Users\Neshia\Desktop\CGS3066\Form Validation Style Sheet.css" TYPE="text/css">
<script>
function ValidatemyForm()
{
var email = document.myForm.email;
var phone = document.myForm.phonenumber;
var age = document.myForm.age;
}
{
age = age.replace(/[^0-9]/g, '');
if(age.length != 10)
{
alert("not 10 digits");
}
else {
alert("yep, its 10 digits");
}
}
</script>
</head>
<div id="header">
<hr id="HR1">
<h1> Web Programming: Assignment 3 </h1>
<p> Form Validation with Javascript </p>
<hr id="HR2">
</div>
<div id="input">
First name: <br>
<input type="text" name="firstname">
<br>
Last name: <br>
<input type="text" name="lastname">
<br>
FSU Email: <br>
<input type= "text" name="email">
<br>
Phone No.: <br>
<input type="numbers" name="phonenumber">
<br>
Age: <br>
<input type="numbers" name="age">
</div>
<hr id="HR3">
<br>
<div id="Sex">
Sex: <br>
<input type="radio" name="sex" value="male"> Male
<br>
<input type="radio" name="sex" value="female"> Female
<br>
<input type="radio" name="sex" value="other"> Other
</div>
<hr id="HR32">
<div id="languages">
Programming languages you want to learn: <br>
<input type="checkbox" name="python" value="python"> Python
<br>
<input type="checkbox" name="java" value="java"> Javascript
<br>
<input type="checkbox" name="C++" value="C++"> C++
<br>
<input type="checkbox" name="lisp" valie="lisp"> Lisp
</div>
<hr id="HR32">
<div id="submit">
<input type="Submit" value="Submit">
</div>
<hr id="HR12">
</form>
</div>

Aneshia,
You have a few problems. First the function listed in the "onsubmit" attribute of your form does not match your javascript function. Also there are some problems with your {} braces. After you get that fixed be sure to call .value after your form elements to get the value of the input ie. (document.myForm.email.value).
Here is the code with some fixes:
<form name="myForm" onsubmit="return validateForm()" method="post">
<head>
<link rel="stylesheet" HREF="C:\Users\Neshia\Desktop\CGS3066\Form Validation Style Sheet.css" TYPE="text/css">
<script>
function validateForm() {
var email = document.myForm.email.value;
var phone = document.myForm.phonenumber.value;
var age = document.myForm.age.value;
console.log(age)
var okToSubmit = true;
age = age.replace(/[^0-9]/g, '');
if (age.length != 10) {
alert("not 10 digits");
okToSubmit = false;
} else {
alert("yep, its 10 digits");
}
if (age > 120 || age < 0) {
alert("Must be a positive number less than 120");
okToSubmit = false;
}
return okToSubmit;
}
Another thing that may help is to bring up the javascript console in your browser and run your function manually in the console by typeing 'validateForm();'

You may be intrigued to note that html5 now validates some of these forms so you do not need to use Javascript.
See HTML Form Validation
You asked about email, age and phone.
Consider the following examples::
<form>
<input type="email" name="email" pattern=".*#yahoo\.com"> <br>
<input type="number" min="18" max="120" name="age"> <br>
<input type="tel" name="phonenumber"> <br>
<input type='submit'>
</form>
If you want the fields to be required you could use
<form>
<input type="email" name="email" pattern=".*#yahoo\.com" required> <br>
<input type="number" min="18" max="120" name="age" required> <br>
<input type="tel" name="phonenumber" required> <br>
<input type='submit'>
</form>
See http://diveintohtml5.info/forms.html
In your comments a few days later, you mentioned needing to do this in Javascript. I think the best way is still using HTML5 and a clever way to do this if you have to use javascript might be to set the input attributes through javascript. Something like this could get you started on the logic.
While I generally do not like getting this specific in the code, I commented things so you can get a general feel for how you can work with data in javascript.
function validate(event){
// First we stop the form from even submitting until we run the code below
event.stopPropagation();
// Here we are going to place a reference to the objects we want to validate in an array
var references = ['email','age','phonenumber'];
// Now we are going to grab our list of inputs from the page
var inputs = document.getElementsByTagName('input');
// We run through a for loop to look for specific elements
for(i = 0; i < inputs.length; i++){
/*
This line simply asks, is the 'name' of this element inside our references array.
This works by using the indexOf function which is built into Javascript.
indexOf simply provides the index where it finds the phrase you are looking for.
In this example, we are using it to see if an index exists by checking it against negative 1
*/
if(references.indexOf(inputs[i].getAttribute('name')) > -1){
// A switch block lets you present a different outcome based on the criteria being looked for
switch(inputs[i].getAttribute('name')){
// In this case we see if we get an email named element
case 'email':
// We set the attributes to match our requirements for this email element and so on through this switch block for age and phonennumber
inputs[i].setAttribute('type','email');
inputs[i].setAttribute('pattern','.*#yahoo\.com');
break;
case 'age':
inputs[i].setAttribute('type','number');
inputs[i].setAttribute('min',18);
inputs[i].setAttribute('max',120);
break;
case 'phonenumber':
inputs[i].setAttribute('type','tel');
break;
}
// When we are all done, we set the elements to be required
inputs[i].setAttribute('required',true);
}
}
// Now we submit the form
event.submit();
}
<form>
<input type="text" name="email"> <br>
<input type="text" name="age"> <br>
<input type="text" name="phonenumber"> <br>
<input type='submit' onclick='validate(event)'>
</form>

<input type='text' id='txtEmail'/>
<input type='submit' name='submit' onclick='Javascript:checkEmail();'/>
<script language="javascript">
function checkEmail() {
var email = document.getElementById('txtEmail');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
}
</script>

Related

how to do html form vaildation in jquery

i am using html and jquery to do some form vaildations
for ex if user click on a field and doesn't enter any thing, than he clicks on different field... i want to turn field border to red. this way user will know that he can not skip this field...
also when user clicks on button submit, than i also want to do this same, if field is empty than turn border to red
below is what i have so far, is there a better way to do this? bbc it seem like i am repeating alot of same code
on up side it does work fine, so guess i can just keep on repeating code
note i have like 20+ fields so jquery function will be long
forgot to tell that i am using asp fields:
<asp:TextBox ID="FirstNameCTB" ClientIDMode="Static" class="input form-control input-md" runat="server"></asp:TextBox>
javascript code:
<script type="text/javascript">
$(function () {
$('#FirstNameCTB').blur('input', function () {
if ($('#<%=FirstNameCTB.ClientID%>').val().trim() == '')
$('#<%=FirstNameCTB.ClientID%>').css('border-color', 'red');
else
$('#<%=FirstNameCTB.ClientID%>').css('border-color', '');
});
$('#LastNameCTB').blur('input', function () {
if ($('#<%=LastNameCTB.ClientID%>').val().trim() == '')
$('#<%=LastNameCTB.ClientID%>').css('border-color', 'red');
else
$('#<%=LastNameCTB.ClientID%>').css('border-color', '');
});
$('.CHECKOUTLBC').click(function () {
if ($('#<%=FirstNameCTB.ClientID%>').val().trim() == '') {
$('#<%=FirstNameCTB.ClientID%>').css('border-color', 'red');
return false; // dont go to server side
} else {
$('#<%=FirstNameCTB.ClientID%>').css('border-color', '');
}
if ($('#<%=LastNameCTB.ClientID%>').val().trim() == '') {
$('#<%=LastNameCTB.ClientID%>').css('border-color', 'red');
return false; // dont go to server side
} else {
$('#<%=LastNameCTB.ClientID%>').css('border-color', '');
}
});
});
</script>
https://jqueryvalidation.org/ can be your solution.
Also here's the examples.
https://jqueryvalidation.org/files/demo/
This plugin has, red border, submit control etc.
Also this plugin will be good.
http://www.formvalidator.net/#reg-form
$.validate({
modules : 'location, date, security, file',
onModulesLoaded : function() {
$('#country').suggestCountry();
}
});
// Restrict presentation length
$('#presentation').restrictLength( $('#pres-max-length') );
<form action="" id="registration-form">
<p>
E-mail
<input name="email" data-validation="email">
</p>
<p>
User name
<input name="user" data-validation="length alphanumeric"
data-validation-length="3-12"
data-validation-error-msg="User name has to be an alphanumeric value (3-12 chars)">
</p>
<p>
Password
<input name="pass_confirmation" data-validation="strength"
data-validation-strength="2">
</p>
<p>
Repeat password
<input name="pass" data-validation="confirmation">
</p>
<p>
Birth date
<input name="birth" data-validation="birthdate"
data-validation-help="yyyy-mm-dd">
</p>
<p>
Country
<input name="country" id="country" data-validation="country">
</p>
<p>
Profile image
<input name="image" type="file" data-validation="mime size required"
data-validation-allowing="jpg, png"
data-validation-max-size="300kb"
data-validation-error-msg-required="No image selected">
</p>
<p>
User Presentation (<span id="pres-max-length">100</span> characters left)
<textarea name="presentation" id="presentation"></textarea>
</p>
<p>
<input type="checkbox" data-validation="required"
data-validation-error-msg="You have to agree to our terms">
I agree to the terms of service
</p>
<p>
<input type="submit" value="Validate">
<input type="reset" value="Reset form">
</p>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.26/jquery.form-validator.min.js"></script>
Assuming all your form inputs are called input, you could loop through them and apply the function with something similar to this.
var inputs = document.getElementsByTagName('input');
for(n = 0; n < inputs.length; n++){
$(function () {
inputs[n].blur('input', function () {
if (inputs[n].val().trim() == '')
inputs[n].css('border-color', 'red');
else
inputs[n].css('border-color', '');
});
});
}
couple things:
issue maybe be that javascript is beeing run before the controls
you should not mix core javascript with jquery libary
you do not need loop when using blur, on, click, etc jquery functions
keeping all those above things in mind, below is a better solutions. works for me
$(function () {
$(".input").blur(function () {
if ($(this).val().trim() == '')
$(this).css('border-color', 'red');
else
$(this).css('border-color', '');
});
});
Have a look at this example below.
<form class="cmxform" id="commentForm" method="get" action="">
<fieldset>
<legend>Please provide your name, email address (won't be published) and a comment</legend>
<p>
<label for="cname">Name (required, at least 2 characters)</label>
<input id="cname" name="name" minlength="2" type="text" required>
</p>
<p>
<label for="cemail">E-Mail (required)</label>
<input id="cemail" type="email" name="email" required>
</p>
<p>
<label for="curl">URL (optional)</label>
<input id="curl" type="url" name="url">
</p>
<p>
<label for="ccomment">Your comment (required)</label>
<textarea id="ccomment" name="comment" required></textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit">
</p>
</fieldset>
</form>
<script>
$("#commentForm").validate();
</script>
Have a look at this example:

Will not return false, or display the alert for function combine() when true. Does someone see a mistake I don't?

// I apologize for giving the whole code, with omission of the urls, but my code will be returning false just fine, then the next time I try to add a new function, it will no longer return false, and upon removing the new function, it does not return to working again as it did before. I have tried onsubmit=return and onclick=return both.
The other issue is for function combine() in my code. It doesn't ever seem to work, and I have tried numerous different methods. I have tried just alerting with "Test", and the alert doesn't even work.
UPDATED: Now we have it returning false properly for invoices not matching, with alert. It also gives alert for Emails not matching, however it does not return false for emails not matching, and continues to the url. I am showing no errors in the console now. It also does correctly combine and alert to show the invoice and name together.
UPDATE: Now have it working completely. See my final comment below to see how I fixed this last issue. Hope this helps someone!
<!DOCTYPE html>
<!-- // working code except for combining the invoice with the name -->
<head>
<title>INFORMATION FORM</title>
</head>
<!-- // This code compares two fields in a form and submit it -->
<!-- // if they're the same, or not if they're different. -->
<body>
<script type="text/javascript">
function checkInvoice(theform) {
if (theform.invoice1.value != theform.invoice2.value)
{
alert("The INVOICE numbers do not match, please review for mistakes to assure your account gets credited.");
return false;
} else {checkEmail(theform);
}
}
function checkEmail(theform) {
if (theform.EMAIL_1.value != theform.Email.value)
{
alert("The EMAIL addresses you provided do not match. Please correct the EMAIL address and try again.");
return false;
} else {
<!-- // This code combines two fields into the CustRefID-->
function combine()
{
var y=document.getElementById("invoice2").value;
var x=document.getElementById("FName").value;
var InvoiceName = y+""+x;
document.getElementById("CustRefID").value = InvoiceName;
alert(document.getElementById("CustRefID").value);
}
combine(); <!--// this calls the combine function when the email addresses match-->
return true;
}
}
</script>
<form name=theform action= "https://hos###/Index" method ="POST" target="_blank" onsubmit="return checkInvoice(this);" >
<input type="hidden" name="HostedKey" id="HostedKey" value="####" />
<input type="hidden" name="Gateway_ID" id="Gateway_ID" value="#####" />
<input type="hidden" name="IndustryCode" id="IndustryCode" value="2" />
<!-- the next line blank value tells the hosted page to allow the customer to use credit cards as the only allowed payment type. -->
<!-- If you want to only allow more than credit cards, replace “CC” with “” for the value -->
<input type="hidden" name="PaymentType" id="PaymentType" value="CC" />
<!-- the next line allows the hosted page to capture some perhaps useful info to identify the payment. -->
<strong><span style="color: #ff0000;">INVOICE</span></strong> Number: <input type="text" name="invoice1" required id="invoice1" value="" size="40" maxlength="40" />
<br>
Please Confirm your <strong><span style="color: #ff0000;">INVOICE</span></strong> number: <input type="text" name="invoice2" required id="invoice2" value="" size="40" maxlength="40" />
<p>
Patient Full Name (as it appears on your paper bill): <input type="text" name="FName" id="FName" required value="" size="40" maxlength="40" />
<p>
PHONE (###-###-####): <input type="text" pattern="^\d{3}-\d{3}-\d{4}$" name="PhoneNumber" required id="PhoneNumber" value="" />
<p>
<input type="hidden" name="Amount" id="Amount" value="" />
<!-- the next line’s N value tells the hosted page to not display recurring payment fields -->
<input type="hidden" name="RecurringType" id="RecurringType" value="N" />
<input type="hidden" name="RecurringAmount" id="RecurringAmount" value="" />
<!-- the next line defines where users are directed after a successful purchase. It is suggested you create a simple Thankyou page for the site. -->
<input type="hidden" name="RURL" id="RURL" value="http://www.######.com/thankyou/" />
<!-- the next line defines where users are directed after they hit the Cancel button on the TXP Hosted page -->
<input type="hidden" name="CURL" id="CURL" value="http://www.########.com/cancelled/" />
<!-- If AVSRequired equals "Y", Address Line 1 and ZIP Code become required fields on the hosted page -->
<input type="hidden" name="AVSRequired" id="AVSRequired" value="Y"/>
<!-- If CVV2Required is set to "Y", than CVV2 becomes a required field on the hosted page -->
<input type="hidden" name="CVV2Required" id="CVV2Required" value="Y"/>
<!-- If EmailRequired is set to "Y", then Email becomes a required field on the hosted page -->
<input type="hidden" name="EmailRequired" id="EmailRequired" value="Y"/>
<!-- the next line defines enables/disables the ability to receive response data in an POST format. When set to N, no response data is returned to the RURL -->
<input type="hidden" name="PostRspMsg" id="PostRspMsg" value="N"/>
<!-- You can also use a graphic for the button to improve the appearance -->
<p> Enter Your Email Address:<br>
<input type="TEXT" name="EMAIL_1" value="" id=EMAIL_1 required size="40" maxlength="40">
<br>
Please Confirm Your Email Address:
<br>
<input type="TEXT" name="Email" required value= "" size="40" maxlength="40" />
<br>
<input type="hidden" name="CustRefID" id="CustRefID" value="" />
<!-- the next line defines what text is on the button. Replace Submit Payment Now with whatever you desire -->
<p>
<input type="SUBMIT" name="Button" id="Button" value="Make Payment Now" ></p>
</form>
</body>
</html>

jQuery, submit() with multiple forms using .each()

First off, I realize this is not an optimal solution, but the actual production environment is a product of a drunken orgy involving Magento and a lot of cheap plugins, so don't judge me too harshly. I can't be held responsible for other peoples' messes.
I'm trying to submit multiple forms from one page using jQuery. It works fine in IE and FF. Page has four forms, which I loop through them in JS to see if their checkbox is checked and then submit them one by one, using .each() and .submit(). In Chrome, jQuery(this).submit() does not fire until after you have completely exited the function, and then it only actually submits the last form.
Uses jQuery 1.8.1. The working mockup is here
The code follows:
<!DOCTYPE html>
<html>
<head>
<title>asdfad</title>
<script type="text/javascript" src=http://code.jquery.com/jquery-1.8.1.min.js"></script>
</head>
<body class=" listraknewsletter-index-index">
<form id="form4" method="post" class="signup-form"
action="http://www.example.com/action1"
target="_blank">
<input type="hidden" name="crvs" value="hiddenValue1"/>
<label for="checkbox">newsletter 1</label>
<input name="checkbox" type="checkbox"
class="signup-checkbox"
name="sos-checkbox" />
</form>
<form id="form2" method="post" class="signup-form"
action="http://www.example.com/action2"
target="_blank">
<input type="hidden" name="crvs" value="hiddenValue2"/>
<label for="checkbox">newsletter 2</label>
<input name="checkbox" type="checkbox"
class="signup-checkbox"
name="sos-checkbox" />
</form>
<form id="form3" method="post" class="signup-form"
action="http://www.example.com/action3"
target="_blank">
<input type="hidden" name="crvs" value="hiddenValue3"/>
<label for="checkbox">newsletter 3</label>
<input name="checkbox" type="checkbox"
class="signup-checkbox" name="sos-checkbox" />
</form>
<form id="form1" method="post" class="signup-form"
action="http://www.example.com/action4"
target="_blank">
<input type="hidden" name="crvs" value="hiddenValue4"/>
<label for="checkbox">newsletter 4</label>
<input name="checkbox" type="checkbox"
class="signup-checkbox" name="sos-checkbox" />
</form>
<!-- Area for entering in information -->
<form method="post" action="/">
<label for="email">email</label>
<input type="text" id = "nl_email" name="email"
size="40" maxlength="100" value = ""/>
<label for="name">name</label>
<input type="text" name="name" id = "nl_name" maxlength="50" size="40" value=""/>
<input type="button" value="Subscribe" onclick="processSignups();" />
<script type="text/javascript">
// requires jQuery
jQuery.noConflict();
function processSignups() {
// make sure you have a valid email and name
// make sure email is at least not null
// this is not a pretty regex for sure lol,
// but tis' RFC 2822 valid
var nl_email = jQuery('input#nl_email').val();
var re = new RegExp(/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/);
if (re.test(nl_email) == false) {
alert('Please enter a valid email');
return false;
}
// name is not null
if (jQuery('input#nl_name').val() == '') {
alert('Please enter your name');
return false;
}
// make sure at least one checkbox is selected
var checkboxes = jQuery('input.signup-checkbox');
var atLeastOne = false;
jQuery(checkboxes).each(function() {
if (jQuery(this).is(':checked')) {
atLeastOne = true;
}
});
if (atLeastOne == false) {
alert('Please select at least one newsletter checkbox');
return false;
}
// select your forms by class
// var forms = jQuery('form.signup-form');
// for each form
var formIds = new Array();
jQuery('form.signup-form').each(function(index) {
// get the checkbox
var checkbox;
checkbox = jQuery(this).children('input.signup-checkbox');
// if it is checked
if (jQuery(checkbox).is(':checked')) {
// add a hidden field to the form to hold the email
jQuery(this).append('<input type="hidden" name="email" value="' + nl_email + '" />');
// and submit form
jQuery(this).submit();
}
});
// might as well clear the email and name inputs
jQuery('input#nl_name').val('');
jQuery('input#nl_email').val('');
// return false;
}
</script>
</form>
</body>
</html>
Chrome doesn't treat target="_blank" like the other browsers. Try _tab, or dynamically changing them $(this).attr('target', '_'+$(this).attr('id'));

Form alerts for multipe inputs

I have the following code, and need to get an alert that will specify which fields are empty or null, and return an alert for each empty or null field. I'm new to JavaScript and struggling a great deal with this. Can anyone give me some advice on this?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE></TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
function checkForm(form){
var len = form.length;
//create for loop
for (var i=0; i<len; i++){
if (form.elements[i].type=="text" || form.elements[i].type==null){
if (form.fax number.value=="" || form.fax number.type==null){
alert("Please fill out the fax number field");
}
}
}
}
function emailTest(emailText){
var email = emailText.value;
var emailPattern = /^.+#.+\..{2,}$/;
if (!(emailPattern.test(email))) {
alert("Please enter a valid email address.");
document.myForm[1].focus();
}
}
// -->
</SCRIPT>
</HEAD>
<BODY>
<H3>Assignment 2 Form</H3>
<HR>
<FORM NAME="myForm" METHOD="post"
ACTION="mailto:joeschmoe#blahblah.ca">
Name:<BR>
<INPUT TYPE="text" size="30" NAME="name"><br>
Email address:<BR>
<INPUT TYPE="text" size="30" NAME="email address" onBlur="emailTest(this);"><br>
Phone number:<BR>
<INPUT TYPE="text" size="30" NAME="phone number"><br>
Fax number:<BR>
<INPUT TYPE="text" size="30" NAME="fax number"><p>
<INPUT TYPE="submit" VALUE="Submit Data" onClick="return checkForm(this.form);">
<INPUT TYPE="reset" VALUE="Reset Form">
</FORM>
</BODY>
</HTML>
Ok...wow. I spent way too much time on this.
Your form should look like the following:
<FORM NAME="myForm" id="myForm">
<label for="name">Name:</label><br />
<INPUT TYPE="text" size="30" NAME="name" /><br />
<label for="email_address">Email address:</label><BR />
<INPUT TYPE="text" size="30" NAME="email_address" /><br />
<label for="phone_number">Phone number:</label><BR />
<INPUT TYPE="text" size="30" NAME="phone_number" /><br />
<label for="fax_number">Fax number:</label><BR />
<INPUT TYPE="text" size="30" NAME="fax_number" /><br />
<INPUT TYPE="button" VALUE="Submit Data" onClick="return checkForm()" />
<INPUT TYPE="reset" VALUE="Reset Form" />
</FORM>
Form Summary:
You should utilize labels for form elements
Never use spaces for the name attribute or any identifying attribute for that matter (name, class, id)
inputs should end with /> as should any tag without an end tag (<br /> too)
I pulled out the onBlur event and just added it as a piece of the overall validation process. No need to make it too complicated
I used a button input type instead of a submit input type. See why in the JavaScript
And then your JavaScript:
function checkForm() {
var valid = false; //Set a boolean variable that will be changed on each block
//of validation
if (document.myForm.fax_number.value === "") {
alert("Please fill out the fax number field");
}
if (document.myForm.email_address.value === "") {
alert("Email address is required");
} else {
valid = emailTest(document.myForm.email_address.value);
}
//all other checks within if statements
if (valid) {
document.myForm.action = "mailto:soandso#so.com";
document.myForm.submit();
}
}
function emailTest(emailText) {
var emailPattern = /^.+#.+\..{2,}$/;
var ret = false;
if (!(emailPattern.test(emailText))) {
alert("Please enter a valid email address.");
} else {
ret = true;
}
return ret;
}
Javascript Summary
In JavaScript interacting with HTML forms, forms are called as such: document.formName where formName is the string in the name="" attribute of the form tag or document.forms[i] where i is the numerical instance of the form on the page, i.e. the first form on the page is i = 0, thus it would be called as document.forms[0]
Check each input by name for a value with document.myForm.(elementName).value where elementName is the string from your <input>s name attribute.
Instead of using a submit, I used a regular button. When the "Submit Data" button is clicked in the form, it runs checkForm() which makes sure everything is valid
If everything is valid, it assigns an action to the form with document.myForm.action=youraction and then submits it via JavaScript with document.myForm.submit()
Notes
Don't use W3Schools to learn about anything ever.
Read more about forms here

javascript form validation not working and can't fin why

So I have this html:
<form action="insert.php" method="post" onsubmit="return validateForm(this)">
<label for="FUP start date">FUP start date:</label>
<input type="text" name="inputField" id="inputField"/>
</br>
</br>
<label for="FUP end date">FUP end date: </label>
<input type="text" name="inputField2" id="inputField2" />
</br>
</br>
<label for="Allowed traffic">Allowed traffic:</label>
<input type="text" name="Allowed_traffic" id="Allowed_traffic"/>
</br>
</br>
<label for="Frequency">Frequency: </label>
<input type="text" name="Frequency" id="Frequency" />
</br>
</br>
<input type="submit" value="submit">
</form>
And this javascript for password (Parola):
<script>
function validateForm(formElement) {
if (formElement.Allowed_traffic.length < 5) {
alert('aaaPlease enter a password that is at least 5 characters long');
return false;
}
if (formElement.Allowed_traffic.length > 10) {
alert('Please enter a password that is less than 10 characters long');
return false;
}
}
</script>
What am I doing wrong? I want to check on submit that the password has between 5 and 10 characters.
Thank you!
Replace .length with .value.length.
You're currently looking at the length property of the <input> element itself (which probably doesn't exist). What you want to be looking at is the length property of the value of the <input> element, so do the following:
if (formElement.Allowed_traffic.value.length < 5) {
alert('aaaPlease enter a password that is at least 5 characters long');
return false;
}
else if (formElement.Allowed_traffic.value.length > 10) {
alert('Please enter a password that is less than 10 characters long');
return false;
}
Note that I've changed it to an if ... else if because if the first condition is true then the second one can't be.
Try to use
var Allowed_traffic = document.getElementById("Allowed_traffic");
instead of
formElement.Allowed_traffic

Categories

Resources