Verification function for HTML form data - javascript

I've created a function in JavaScript to verify an html form data, my code as below:
function checkPetitionForm_ff() {
if (document.petition_form.petition_firstname.value == "FIRST NAME" || document.petition_form.petition_firstname.value == "") {
alert("Please enter your First Name!")
document.petition_form.petition_firstname.focus();
return false;
}
if (document.petition_form.petition_lastname.value == "LAST NAME" || document.petition_form.petition_lastname.value == "") {
alert("Please enter your Last Name!")
document.petition_form.petition_lastname.focus();
return false;
}
if (document.petition_form.petition_age.value == "AGE" || document.petition_form.petition_age.value == "") {
alert("Please enter your Age!")
document.petition_form.petition_age.focus();
return false;
}
if (document.petition_form.state.value == "Select State") {
alert("Please select your state!")
document.petition_form.state.focus();
return false;
}
if (document.petition_form.petition_address.value == "HOME ADDRESS" || document.petition_form.petition_address.value == "") {
alert("Please enter your address!")
document.petition_form.petition_address.focus();
return false;
}
if (document.petition_form.zip.value == "ZIP CODE" || document.petition_form.zip.value == "") {
alert("Please enter your Zipcode!")
document.petition_form.zip.focus();
return false;
}
if (document.petition_form.phone2.value == "PHONE" || document.petition_form.phone1.value == "" || isNumeric(document.petition_form.phone1.value) == false) {
alert("Please enter the complete phone No!")
document.petition_form.phone2.focus();
return false;
}
if (document.petition_form.phone1.value == "PHONE" || document.petition_form.phone1.value == "" || isNumeric(document.petition_form.phone1.value) == false) {
alert("Please enter the complete phone No!")
document.petition_form.phone1.focus();
return false;
}
if (document.petition_form.phone3.value == "PHONE" || document.petition_form.phone1.value == "" || isNumeric(document.petition_form.phone1.value) == false) {
alert("Please enter the complete phone No!")
document.petition_form.phone3.focus();
return false;
}
if (document.petition_form.level.value == "YOUR LEVEL OF EDUCATION") {
alert("Please select your level of education!")
document.petition_form.level.focus();
return false;
}
if (document.petition_form.degree.value == "DEGREE OF INTEREST") {
alert("Please select your degree!")
document.petition_form.degree.focus();
return false;
}
if (!(document.getElementById(edu).checked)) {
alert("Please select Education!")
document.petition_form.edu.focus();
return false;
}
else {
return true;
}
}
The verifications are working good until "phone2" field and will not complete the verification after this.
I'll do appreciate if you can help me and advise how to solve this.

I think you are getting an exception as isNumeric is not a JavaScript Global function. You need to define it in your page (check out Validate decimal numbers in JavaScript - IsNumeric() for a clean implementation of isNumeric).
Also you should surround your method call with exception handling to get better details of the exception.

In that line you're actually checking phone2 only in the first condition, the others are phone1.
document.petition_form.phone2.value=="PHONE" || document.petition_form.phone1.value=="" || isNumeric(document.petition_form.phone1.value)==false
Also be aware that you do the same for phone3.

It looks like a simple copy/paste error. Notice that the petition_form members referenced after phone2 are phone1... this does not make sense. Compare this line against your next validation where all of the members are phone1.
So, this line:
if (document.petition_form.phone2.value == "PHONE" ||
document.petition_form.phone1.value == "" ||
isNumeric(document.petition_form.phone1.value) == false) {
Should look like:
if (document.petition_form.phone2.value == "PHONE" ||
document.petition_form.phone2.value == "" ||
isNumeric(document.petition_form.phone2.value) == false) {
(Code is lined up in that manner to hilight the differences.)

Related

how to show onsubmit validation message on client-side in javascript except alert pop up box?

I want to validate form inputs before submitting to the server side, so I am using onsubmit, but I want to show each error message separately by not using 'alert', is that possible? How to do it? Or onsubmit can only return message over alert?
Update
I already validated each of the input by using functions and there are error messages inside each function. But if I put these functions under "submit", when I click submit, no error message shows up.
here is my validation:
document.addEventListener("DOMContentLoaded", function () {
myform.addEventListener("submit", function(){
// validate all inputs
validateName();
validateEmail();
validatePhone();
validateAddress();
validateCity();
validatePost();
validateProvince();
validateProduct1();
validateProduct2();
validateProduct3();
getAtLeastOne();
validateDelivery();
//validate input before submit
if (validateName() && validateEmail() && validatePhone() && validateAddress() &&
validateCity() && validatePost() && validateProvince() && validateProduct1() &&
validateProduct2() && validateProduct3() && getAtLeastOne() && validateDelivery())
{
// at least one product input is not empty
if (product1 !="" || product2 !=""||product3 !="")
{
return true;
}
else{
erorMessage.innerHTML =`Input fields are required.`;
return false;
}
}
});
});
You need to use event.preventDefault() to stop the form from submitting if there are issues. return false does nothing in an event handler attached using addEventListener.
myform.addEventListener("submit", function(e) {
// validate all inputs
validateName();
validateEmail();
validatePhone();
validateAddress();
validateCity();
validatePost();
validateProvince();
validateProduct1();
validateProduct2();
validateProduct3();
getAtLeastOne();
validateDelivery();
//validate input before submit
if (validateName() && validateEmail() && validatePhone() && validateAddress() &&
validateCity() && validatePost() && validateProvince() && validateProduct1() &&
validateProduct2() && validateProduct3() && getAtLeastOne() && validateDelivery()) {
// at least one product input is not empty
if (product1 != "" || product2 != "" || product3 != "") {
return true;
} else {
e.preventDefault();
erorMessage.innerHTML = `Input fields are required.`;
}
}
});

How do I find out if a input element's value is blank (null)

I have following code to check if the inputs with the ids emailForm and nameForm are blank, this however isn't working when I test the form by leaving it blank.
function setInfo() {
if (document.getElementById("emailForm").value == null ||
document.getElementById("nameForm").value == null) {
alert("Please Fill in all sections");
} else {
email = document.getElementById("emailForm").value;
name = document.getElementById("nameForm").value;
loaded();
}
}
Could someone help me with this, thanks!
Instead of checking for null specifically, you should check for falsy values. In some cases, the values for empty textboxes will be an empty string.
Replace this:
if (document.getElementById("emailForm").value == null || document.getElementById("nameForm").value == null) {
with this:
if (!document.getElementById("emailForm").value || !document.getElementById("nameForm").value) {
You shouldn't be checking whether the fields are null, you should be checking whether they content is an empty string (with .value == '').
This can be seen working in the following:
function setInfo() {
if (document.getElementById("emailForm").value == '' ||
document.getElementById("nameForm").value == '') {
console.log("Please fill in all sections");
} else {
email = document.getElementById("emailForm").value;
name = document.getElementById("nameForm").value;
//loaded();
console.log("All sections filled in");
}
}
const button = document.getElementById('go');
button.addEventListener('click', function() {
setInfo();
});
<input id="emailForm" />
<input id="nameForm" />
<button id="go">Go</button>
Make sure you calling function setInfo()
function setInfo() {
// You can check Value.Length also or
if (document.getElementById("emailForm").value === "" ||
document.getElementById("nameForm").value === "") {
alert("Please Fill in all sections");
} else {
email = document.getElementById("emailForm").value;
name = document.getElementById("nameForm").value;
loaded();
}
}
Try below solution:
function setInfo() {
var email=document.getElementById("emailForm").value;
var name=document.getElementById("nameForm").value;
if (email=='' || email==null || name=='' || name== null ) { // OR if (!email || !name)
alert("Please Fill in all sections");
return;
} else {
loaded();
}
}
You should check whether the string is empty or not instead of null. Try using the code below:
function setInfo() {
var a=document.getElementById("emailForm").value;
var b=document.getElementById("nameForm").value;
if (a == "" ||
b == "") {
alert("Please Fill in all sections");
} else {
email =
document.getElementById("emailForm").value;
name =
document.getElementById("nameForm").value;
alert("success alert");
}
}

Common javascript form validation not working

I've been trying to use the following javascript code to validate several fields on a contact form. The validation works for the first item being validated, the name field, but not the second, the email field. If the name field is filled in, the validation seems to skip over the email field check when it's blank and the form submits.
function validateForm()
{
var n = document.contact.name.value;
n = n.trim();
var ema = document.contact.email.value;
ema = ema.trim();
//Check if the name is missing
if (n == null || n == "" || empty(n))
{
alert("Please enter your name.");
document.contact.name.focus();
return false;
}
//Check if the email is missing
else if ( ema == null || ema == "" || empty(ema) )
{
alert( "Please enter your email address." );
document.contact.email.focus();
return false;
}
else
{
return( true );
}
}
Here is the HTML on the contact form:
<FORM name="contact" METHOD="POST" ACTION="thankyou.php" onsubmit="return validateForm()">
<input type="checkbox" name="newsletter" value="YES" width="30" height="30"> Check the box to subscribe to Herb's Newsletter
<input type="text" class="form-control" size=20 name="name" placeholder="Your name" />
<input type="email" class="form-control" name="email" placeholder="Email Address" />
<input class="btn btn-theme btn-subscribe" type="submit" value="Send" />
</form>
Thank you
You seem to be using empty function in your if clauses which doesn't seem to be defined nor it is part of the standard javascript functions. Try getting rid of it:
function validateForm() {
var n = document.contact.name.value;
n = n.trim();
var ema = document.contact.email.value;
ema = ema.trim();
//Check if the name is missing
if (n == null || n == "") {
alert("Please enter your name.");
document.contact.name.focus();
return false;
} else if (ema == null || ema == "") {
//Check if the email is missing
alert( "Please enter your email address." );
document.contact.email.focus();
return false;
} else {
return true;
}
}
And here's a live demo.
In your code you use else if statement.
Basically what you code does is:
check name -> if that is falsy check email -> if that is falsy move into else condition.
But when the name is true, the if statement will not move to else conditions because it it already satisfied. So if you want to check both, you either separate the statements and make a 5 separate ifs, make it a switch statement or you create one long check. For example:
if ((n == null || n == "" || empty(n)) || ( ema == null || ema == "" || empty(ema) ))
{
alert("Something is missing");
return false;
}
else
{
return( true );
}
or you use multiple ifs:
function validateForm() {
var n = document.contact.name.value;
n = n.trim();
var ema = document.contact.email.value;
ema = ema.trim();
//Check if the name is missing
if (n == null || n == "" || empty(n))
{
alert("Please enter your name.");
document.contact.name.focus();
return false;
}
//Check if the email is missing
if ( ema == null || ema == "" || empty(ema) )
{
alert( "Please enter your email address." );
document.contact.email.focus();
return false;
}
return( true );
}
The latter will always return true unless one of the if statements is triggered.
And see answer below about the empty() thing. I don't know what that is and if it messes anything up.

Either Can Not submit(); form in jQuery, or can not check if input fields are filled out

I am having trouble submitting the below form.
For background, I'm trying to "submit" a form for a delivery, and I need to know a) their pickup address, b) their dropoff address, and c) their description. I created <p class="error"> fields if those <input>s are empty (as in "Please enter a description").
If I remove the 'return false;' the form submits no matter what, but if I keep the 'return false;' the jQuery works (i.e. - error message appears) but now the form NEVER submits. Thoughts?
Here's my main.js
var main = function() {
$('form').submit(function() {
var pickup = $('#pickup').val();
if(pickup === "") {
$('.pickup-error').text("Please choose a pickup.");
}
var dropoff = $('#dropoff').val();
if(dropoff === "") {
$('.dropoff-error').text("Please choose a dropoff.");
}
var description = $('#description').val();
if(description === "") {
$('.description-error').text("Please tell us a little about what we're moving.");
}
return false;
});
};
$(document).ready(main);
var main = function () {
$('form').submit(function () {
var pickup = $('#pickup').val();
if (pickup === "") {
$('.pickup-error').text("Please choose a pickup.");
}
var dropoff = $('#dropoff').val();
if (dropoff === "") {
$('.dropoff-error').text("Please choose a dropoff.");
}
var description = $('#description').val();
if (description === "") {
$('.description-error').text("Please tell us a little about what we're moving.");
}
// did not pass validation
if (pickup != "" || dropoff != "" || description != "") {
return false;
}
// passed validation, submit
return true;
});
};
$(document).ready(main);

Javascript Email validation that allows a null value

I have this on submit function that checks for the email field to have a properly formatted address. Works fine. However, I want the field to allow a null value as this particular input is optional and not required. I know this should be simple, Im missing the obvious. Someone point me in the right direction...
EDIT: Providing the entire form validation this time. As every time I just replace the email portion its breaking other pieces....
function validateSMSForm()
{
if (SMSForm.PID_Form.value.length < 4)
{
alert("Please enter a valid Partner ID");
return false;
}
if (SMSForm.area.value.length < 3)
{
alert("Please enter a valid 10-digit cell phone number");
return false;
}
if (SMSForm.prefix.value.length < 3)
{
alert("Please enter a valid 10-digit cell phone number");
return false;
}
if (SMSForm.line.value.length < 4)
{
alert("Please enter a valid 10-digit cell phone number");
return false;
}
<!-- EMAIL VALIDATION HERE
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(form.emailaddress.value))
{
return (true)
}
alert("Please enter a valid email address")
return (false)
-->
}
Add a check for empty/null string first:
if ((!form.emailaddress.value) || (/^\w+([.-]?\w+)#\w+([.-]?\w+)(.\w{2,3})+$/.test(form.emailaddress.value))) {
//handle valid e-mail
} else {
//handle invalid e-mail
}
Like this
Assuming
<form onsubmit="return validateSMSForm(this)">
JavaScript:
function isEmail(str) {
return !str || /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,})+$/.test(str);
}
function validateSMSForm(SMSForm) {
if (SMSForm.PID_Form.value.length < 4) {
alert("Please enter a valid Partner ID");
return false;
}
if (SMSForm.area.value.length < 3 ||
SMSForm.prefix.value.length < 3 ||
SMSForm.line.value.length < 4) {
alert("Please enter a valid 10-digit cell phone number");
return false;
}
if (!isEmail(SMSForm.emailaddress.value)) {
alert("Please enter a valid email address")
return false; //
}
return true; // allow submission
}
var email = form.emailaddress.value;
if (!email){ return true } // this what your looking for?
if (/^\w+([.-]?\w+)#\w+([.-]?\w+)(.\w{2,3})+$/.test(email))
{
return (true)
}
alert("Please enter a valid email address")
return (false)

Categories