Can't get form validation in JS to work - javascript

so I have been learning basic JS and i can't get form validation to work for numbers. I will post a code snippet below. Please I am a noob so can I possibly have an answer that is easier to understand from someone who is just learning the language. The first three if statements work fine, but the fourth I have trouble with...
var checkbox = function() {
var error = "";
var firstname = document.getElementById("fn").value;
var lastname = document.getElementById("ln").value;
var email = document.getElementById("Email").value;
var age = parseInt(document.getElementById("age").value);
var address = document.getElementById("A").value;
var phone = parseInt(document.getElementById("pn").value);
if(firstname.length < 1){
error = "Enter a valid first name!";
}
if(lastname.length < 1){
error += "\nEnter a valid last name!";
}
if(email.length <1){
error += "\nEnter a valid email!";
}
if(age.length < 1 ){
error += "\nEnter a valid age!";
}
if(error.length){
alert(error)
return false;
}
return true;
}

you can try with this one
if(firstname.trim() == ""){
error = "Enter a valid first name!";
}
if(lastname.trim()==""){
error += "\nEnter a valid last name!";
}
if(email.trim() ==""){
error += "\nEnter a valid email!";
}
if(age.trim() == "" ){
error += "\nEnter a valid age!";
}
if(error.length>0){
alert(error)
return false;
}

What are you checking your age field against on? Are you checking for its presence? if so, you can do this:
if(!age) {
error += "\nThis field is required";
}
If you are checking if the value in the age field is a number, you can do this:
if(typeof age !== "number") {
error += "\nPlease enter a valid number!";
}
If you are checking if the age field is under a certain age range you can do this:
if(age !== 30) {
error += "\nYou are under 30!";
}

You should check the length of document.getElementById("age").value before call parseInt. Otherwise variable age can be NaN. For example:
var ageVal = document.getElementById("age").value;
var age;
if (ageVal){ //same as ageVal.length > 0
age = parseInt(age);
if (!age){// it can be NaN
error += "\nEnter a valid age!";
}
}
else
{
error += "\nEnter an age!"; //here we have age not set
}

Please try this
if(isNaN(age)){
error += "\nEnter a valid age!";
}
isNan() is an inbuilt javascript function. More information can be found at http://www.w3schools.com/jsref/jsref_isnan.asp

Related

JavaScript display multiple error message form submission?

What am I doing wrong in my JavaScript? I would like to display an error message if a user forgets to type in any of my HTML form fields. I would like to create an error message for the name, email, and phone number fields. Even if a user puts in their name, I would like error messages for the remainder 2, or remainder 1, or no error messages. I have attached my JavaScript code below. Thank you for those who help.
function validateForm() {
var ret = true;
var name = document.forms["contactform"]["name"].value;
if (name == "") {
document.getElementById('error').innerHTML = "Please enter your name";
ret = false;
}
var email = document.forms["contactform"]["email"].value;
if (email == "") {
document.getElementById('erroremail').innerHTML = "Please enter your email";
ret = false;
}
var phone = document.forms["contactform"]["phone"].value;
if (phone == "") {
document.getElementById('errorphone').innerHTML = "Please enter your phone";
ret = false;
}
return ret;
}
If you want separate error display for each input you could just add else with empty innerHTML.
Something like this:
var name = document.forms["contactform"]["name"].value;
var nameError = document.getElementById('error');
if (name == "") {
nameError.innerHTML = "Please enter your name";
ret = false;
} else {
nameError.innerHTML = "";
}
Full example here: https://jsfiddle.net/1h1tkh7y/
Create a variable called something like :
var fieldsInError = "";
Then in your validation in each check if it fails validation add the field:
fieldsInError += "name," (or whatever the field is)
Then at the end of the function update your error field with something like:
document.getElementById('error').innerHTML = "Please enter " + fieldsInError.substring(0, fieldsInError.length-1);
So your function would look something like this:
function validateForm() {
var fieldsInError = "";
var name = document.forms["contactform"]["name"].value;
if (name == "") {
fieldsInError += "name,"
}
var email = document.forms["contactform"]["email"].value;
if (email == "") {
fieldsInError += "email,"
}
var phone = document.forms["contactform"]["phone"].value;
if (phone == "") {
fieldsInError += "phone,"
}
if(fieldsInError != ""){
document.getElementById('error').innerHTML = "Please enter " + fieldsInError.substring(0, fieldsInError.length-1);
return false;
} else {
return true;
}
}

Hide the javascript innerHTML after error is corrected

I have used the following javascript code to add inline error in my form. I want to error to be removed after the error is corrected after each field is corrected. I have created a single function for all the validations, so not able to use else and remove the error manually.
var emailpattern = /^[a-zA-Z][a-zA-Z0-9_]*(\.[a-zA-Z0-9_]+)*#[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.([a-zA-Z]{2,4})$/
var passwordpattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[$#$!%*?&])[A-Za-z\d$#$!%*?&]{8,}$/;
function validateForm() {
var x = document.forms["LoginForm"]["email"];
if (x.value == "") {
x.value = "";
document.getElementById('pointemail').innerHTML = "Please enter the email id.";
x.focus();
return false;
} else if (!emailpattern.test(x.value)) {
x.value = "";
document.getElementById('pointemail').innerHTML = "Please enter a valid email address.";
x.focus();
return false;
}
x = document.forms["LoginForm"]["password"];
if (x.value == "") {
x.value = "";
document.getElementById('pointpassword').innerHTML = "Please enter the password.";
x.focus();
return false;
} else if (!passwordpattern.test(x.value)) {
x.value = "";
document.getElementById('pointpassword').innerHTML = "Password should have minimum 8 characters, one upper case, one lower case and one special character";
x.focus();
return false;
}
}
Try This
var emailpattern = /^[a-zA-Z][a-zA-Z0-9_]*(\.[a-zA-Z0-9_]+)*#[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.([a-zA-Z]{2,4})$/
var passwordpattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[$#$!%*?&])[A-Za-z\d$#$!%*?&]{8,}$/;
function validateForm() {
var x = document.forms["LoginForm"]["email"];
document.getElementById('pointemail').innerHTML = "";
document.getElementById('pointpassword').innerHTML = "";
//Add your if else here.
}
Hope it will be useful. :)
Provide an extra else statement after elseif
else {
document.getElementById('pointemail').innerHTML = '';
}
Similarly for pointPassword

Check if <form> text element is null

I wanted to do an error check in Javascript which would pop up if a form-text element is empty.
var itemPrice = parseFloat(document.getElementById("tPrice").value);
if(itemPrice < 0 || itemPrice == null)
{
alert("Please enter a valid price");
return false;
}
I have tried itemPrice == "null"and itemPrice === "null".
Any insight would be great, thank you!
To check if the value is empty, just write getElementById("tPrice").value==='' without parseFloat.
var itemPrice = parseFloat(document.getElementById("tPrice").value);
if(getElementById("tPrice").value==='' || itemPrice < 0)
{
alert("Please enter a valid price");
return false;
}
This will give you the results you are looking for
if (typeof itemPrice == "undefined" || itemPrice <= 0) { ... }
You can use the isNaN function to tell if the function is not a number, which not only works for blank / empty values but also for any random text.
In the example below stackoverflow does not allow alert statements to be run, so I changed it to display the results inline.
function validateField() {
var itemPrice = parseFloat(document.getElementById("tPrice").value),
result = document.getElementById("result");
if(isNaN(itemPrice) || itemPrice < 0) {
result.innerHTML = '<span style="background:red;color:#fff">Please enter a valid price</span>';
return false;
}
result.innerHTML = '<span style="background:green;color:#fff">Price is valid</span>';
return true;
}
<input type="text" id="tPrice" />
<button onclick="validateField();">Validate Field</button>
Result:<span id="result"></span>
If the itemPrice have to be a number > 0 try this:
var itemPrice = document.getElementById("tPrice").value;
if(!(itemPrice > 0)) {
alert("Please enter a valid price");
return false;
}

If Statement Only Executing Else Part

I have a simple program that validates a sign up form. Basically I reach a problem when one of my "if" statements can only execute the "else" part. If I change the form so that "if" is executed, nothing happens. Below is my code:
function verifyprocedure() {
var originalpassword = document.getElementById("password").value;
var checkpassword = document.getElementById("verifypassword").value;
var emailcheck = document.getElementById("email").value;
var male = document.getElementById("gendermale");
var female = document.getElementById("genderfemale");
var form = document.getElementById("signup");
var emailexist = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (originalpassword == checkpassword) {
if (originalpassword.length < 9) {
if (emailexist.test(emailcheck)) //this is the statement that does not work
{
alert("Hello World!"); //this is whats supposed to be executed
} else { //this is successfully executed
$("#email").notify("Please enter a valid email address.");
}
} else {
$("#password").notify("Passwords must have at least 9 characters.");
}
} else {
$("#verifypassword").notify("Passwords do not match.");
}
}
Did you check whether it is working or not ?
anyway it is working for me,i think your input should be invalid you can use the following code for checking
var originalpassword ="abcdefgh";
var checkpassword = "abcdefgh";
var emailcheck = "arun#gmail.com";
var male ="male";
var emailexist = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (originalpassword == checkpassword) {
alert("hai");
}
if (originalpassword.length < 9) {
if (emailexist.test(emailcheck))
{
alert("Hello World!");
} else {
alert("Please enter a valid email address.");
}
}
Working DEMO
UPDATE
var originalpassword ="abcdefgh";
var checkpassword = "abcdefgh";
var emailcheck = "arun#gmail.com";
var male ="male";
var emailexist = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (originalpassword == checkpassword)
{
alert("hai");
if (originalpassword.length > 9)
{
if (emailexist.test(emailcheck))
{
alert("Hello World!");
}
else
{
alert("Please enter a valid email address.");
}
}
else
{
alert("Passwords must have at least 9 characters.");
}
}
else {
alert("Passwords do not match.");
}
Check this DEMO It will satisfy all conditions.
Note : Check your if condition for password length, if you want the desired output then it will be like if (originalpassword.length > 9)
if (originalpassword.length > 9) {
if (emailexist.test(emailcheck)) //this is the statement that does not work
{
alert("Hello World!"); //this is whats supposed to be executed
} else { //this is successfully executed
$("#email").notify("Please enter a valid email address.");
}
} else {
$("#password").notify("Passwords must have at least 9 characters.");
}

How to show the validation messages together

I need your assistant and help in modifying the below code to show the validation messages if not satisfied together not one by one. My code is:
function validateForm()
{
var x = "";
var y = "";
if ( (RFC.C1.checked) && (!RFC.Language_e.checked || !RFC.Language_e.checked ))
{
y += "Please Select the Language";
document.getElementById('error').innerHTML = y;
return false;
}
else if (document.RFC.Reason.value=="")
{
x += "Please enter a Reason";
document.getElementById('error').innerHTML = x;
return false;
}
else
{
return true;
}
}
In addition, the validation message is shown one time and if the user didn't correct it and submit the page, the error will not be shown again. Can you please help in the two issues?
I would do something like this:
function validateForm() {
var error = "";
var valid = true;
if ( (RFC.C1.checked) && (!RFC.Language_e.checked || !RFC.Language_e.checked )) {
error += "<li>Please Select the Language</li>";
valid = false;
}
else if (document.RFC.Reason.value=="") {
error += "<li>Please enter a Reason</li>";
valid = false;
}
if(valid === false) {
document.getElementById('error').innerHTML = "<ul>" + error + "</ul>";
}
return valid;
}
Get all your errors and store them.
Change the valid boolean to false if any single or multiple error occurs
Only display errors if they happen.
Link to the error locations in your page for easy navigation.
function validateForm()
{
var x = "";
var y = "";
var z = "";
if ( (RFC.C1.checked) && (!RFC.Language_e.checked || !RFC.Language_e.checked) )
{
y += "Please Select the Language";
document.getElementById('error').innerHTML = y;
return false;
}
else if ( document.RFC.Reason.value=="" )
{
x += "Please enter a Reason";
document.getElementById('error').innerHTML = x;
return false;
}
else if ( ((RFC.C1.checked) && (!RFC.Language_e.checked || !RFC.Language_e.checked )) && (document.RFC.Reason.value=="") )
{
z += "Please enter a Reason and Language";
document.getElementById('error').innerHTML = z;
return false;
}
else
{
return true;
}
}
By the way your code is working but not nice. You should read something about programming style. To get nice validation quicly you can use jQuery Validate plug-in.

Categories