Validate forms using javascript - javascript

I want to validate 3 inputs (name, email and password) in a form using javascript. When the user submits the form, and all the fields are empty, it works correctly showing the error messages. But then if I write a correct password (length 7) and wrong email and name, and I try to submit the form again the "Password too short" message is stil there and the password is correct. What I am doing wrong?
Javascript file
function verify(){
if(verName()&verEmail()&verPassword())
{
return true;
}else
{
verName();
verEmail();
verPassword();
return false;
}
}
function verPassword(){
var ok = true;
var frm = document.getElementById("register");
var pass = frm.elements[2].value;
if(pass.length<6)
{
var text="Password too short";
document.getElementById('textPassword').innerHTML=text;
ok = false;
}
return ok;
}
HTML file
<form id='register' name='register' onsubmit="return verify()">

function verify(){
document.getElementById('textPassword').innerHTML = ' ';
if(verName()&verEmail()&verPassword())
{
return true;
}else
{
verName();
verEmail();
verPassword();
return false;
}
}

change your code it like this:
function verify(){
if(verName()&verEmail()&verPassword())
{
return true;
}
else
{
if(verName());
if(verEmail());
if(verPassword());
return false;
}
}
with this solution, each validation occurs if the previous validation runs true! and if not, just the previous validation errors shows up !
in each function verName(), verEmail() and verPassword(), return Boolean value of TRUE of FALSE
also add this line of code, on your form submit event:
verify() {
document.getElementById('textPassword').innerHTML= ' '
....
....
}

The problem is that your verPassword function is adding that error string when the password is invalid, but it doesn't remove it when the password is valid.
Also, your verify function makes little sense.
How about:
function verify(){
return verName() && verEmail() && verPassword();
}
function verPassword(){
var frm = document.getElementById("register");
var pass = frm.elements[2].value;
var ok = pass.length > 5;
var text = ok ? "" : "Password too short";
document.getElementById('textPassword').innerHTML=text;
return ok;
}

You have to empty the #textPassword element by write something like: document.getElementById('textPassword').innerHTML.
In addition I can see some wrong codes there. First, if every ver* function returns true or false, you better use && rather than & in if condition expression. Or you can just return the evaluated value of the condition expression like this: return verName() && verEmail() && verPassword().
Second, the ver* functions are already called while if evaluate condition expression. No need to call those functions again in else part.
And I don't think you need ok variable in verPassword() function.
I suggest to change the code like below:
function verify(){
return verName() && verEmail() && verPassword();
}
function verPassword(){
var frm = document.getElementById("register");
var pass = frm.elements[2].value;
var textPassword = document.getElementById('textPassword');
if (pass.length < 6) {
var text="Password too short";
textPassword.innerHTML = text;
return false;
} else {
textPassword.innerHTML = ""; // Empty #textPassword
return true;
}
}

Related

JavaScript form validation with else if

I have been creating JavaScript validation for a form though run into difficulties. There are currently two parts to parts at (at the moment) for JavaSCript to check (email and sms). THe script is only running email and not checking sms at all when should be checking both together. If both are fine then return true. Any ideas?
function validateForm() {
var emailBoxChecked = document.getElementById("checkemail").checked
var emailBoxChecked = document.getElementById("checksms").checked
var errordiv = document.getElementById('error');
var errorsms = document.getElementById('errorsms');
/*postOptOutSix.checked = false;
postOptOutForever.checked = false*/
// Conditions
if (document.getElementById("emailradios") ==null && document.getElementById("emailforever") ==null) {
if (document.getElementById("smsforever") ==null && document.getElementById("smsforever") ==null) {
return true;
}
else if (document.getElementById("checksms").checked ==false && document.getElementById("smsOptOutSix").checked ==false && document.getElementById("smsOptOutForever").checked ==false) {
errordiv.innerHTML += "<p id='errorp' style='color:red;'>*SMS - Please either opt-in post or select either of the options.'";
return false;
} else {
return true;
}
}
else if (document.getElementById("checkemail").checked ==false && document.getElementById("emailOptOutSix").checked ==false && document.getElementById("emailOptOutForever").checked ==false) {
errorsms.innerHTML += "<p id='errorp' style='color:red;'>*Email - Please either opt-in post or select either of the options.'";
return false;
} else {
return true;
}
}
You'd need to separate the 2 conditions checks, and only then check if some failed or not before returning.
Something like this should do the trick:
function validateForm () {
var errors = [];
// Empty any previous errors
document.getElementById('error').innerHTML = "";
// Check for SMS
if (!document.getElementById("checksms").checked &&
!document.getElementById("smsOptOutSix").checked &&
!document.getElementById("smsOptOutForever").checked) {
// add the SMS error to the array
errors.push("<p id='errorp' style='color:red;'>*SMS - Please either opt-in post or select either of the options.'");
}
// Check for Email
if (!document.getElementById("checkemail").checked &&
!document.getElementById("emailOptOutSix").checked &&
!document.getElementById("emailOptOutForever").checked) {
// add the Email error to the array
errors.push("<p id='errorp' style='color:red;'>*Email - Please either opt-in post or select either of the options.'");
}
// Display the error(s) if any
if (errors.length > 0) {
errors.forEach(function (err) {
document.getElementById('error').innerHTML += err;
});
return false;
}
return true;
}
Also, I noticed that id='errorp' is there twice. Rename one of them.
var emailBoxChecked = document.getElementById("checkemail").checked
var emailBoxChecked = document.getElementById("checksms").checked
You are setting the same variable from different elements. Shouldn't it be like this?
var emailBoxChecked = document.getElementById("checkemail").checked
var smsBoxChecked = document.getElementById("checksms").checked
Use HTML required and pattern attributes along with inputElement.checkValidity() which returns true or false. You could look on keyup, for example, to make sure all inputs are valid and if so enable the submit button and if not disable it.

phone number validation wont pass

function ClientContactCheck(){
var clientcontact = $("#client_contact_id").val();
if(clientcontact.length != ""){
if(!isNaN(clientcontact)){
$("#client_contact_id").css('border-color', "#dfe0e6");
return true;
}
}else{
$("#client_contact_id").css('border-color', "red");
}
return false;
}
i am using this function to validation phone number , my intention is simple just not be empty and must be number.
but if put !isNaN and my input was 123-456-789 , it wont valid cause the - was not a number, how to i make my function bypass the - ?
so if the input value had - it will pass thought.
thank
You can use :
str.replace("-", "");
and then check your input if it is a number only.
Edit:
var res = str.replace(/\-/g,'');
You can check it with a regular expression:
var clientcontact = $("#client_contact_id").val();
if (/^[0-9\-]+$/.test(clientcontact)) {
$("#client_contact_id").css('border-color', "#dfe0e6");
return true;
} else {
$("#client_contact_id").css('border-color', "red");
return false;
}
This will allow '-', '--', '---' too. If that is not desired, you can do one more check: ... && !/^-*$/.test(clientcontact)
You can do something like this to validate the phone number.
function phonenumber(inputtxt)
{
var phoneno = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
if((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}
More at http://www.w3resource.com/javascript/form/phone-no-validation.php

jQuery - Checking val isn't empty and contains a specific piece of text

So I've got a .js file that checks that the values of my form. I'm trying to check that the form values aren't empty, and that one of the values contains a specific piece of text (in this case, my name). If the form does hold my name, then run the rest of the script.
Where I have commented //etc etc, an AJAX script is ran that posts to a PHP file.
This is all functioning as expected, until I run the additional if statement checking the input value for my name.
$('#submit').click(function(e){
this.enabled=true;
if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === ""){
$('#message').html('you did not fill out one of the fields').css("color", "#be4343")
return false;
if($('#name').val().indexOf("Rich") != -1){ // without this if statement, the code runs fine.
$('#message').html("You have entered the wrong name.");
return false;
}
} else {
if($('#name, #topic_title').length && $('#name, #topic_title').val().length){
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}}
// etc etc
});
Question: How would I go about checking that the value of the id '#name' isn't empty, and that it contains a specific piece of text?
Thanks in advance,
Richie.
Solution:
I removed the additional if statement and included the following code.
var name = $('#name').val();
if ( name.indexOf("Rich") || $.trim($("#name").val()) === ""){
If you indent your code consistently, it's fairly clear why you have a problem:
$('#submit').click(function(e) {
this.enabled = true;
if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === "") {
$('#message').html('you did not fill out one of the fields').css("color", "#be4343")
return false;
if ($('#name').val().indexOf("Rich") != -1) { // Note that this is WITHIN the `if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === "")` condition
$('#message').html("You have entered the wrong name.");
return false;
}
} else {
if ($('#name, #topic_title').length && $('#name, #topic_title').val().length) {
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}
}
// etc etc
});
If you want it to be handled, it needs to be an else if for that condition instead:
$('#submit').click(function(e) {
this.enabled = true;
if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === "") {
$('#message').html('you did not fill out one of the fields').css("color", "#be4343")
return false;
} else if ($('#name').val().indexOf("Rich") != -1) { // without this if statement, the code runs fine.
$('#message').html("You have entered the wrong name.");
return false;
} else {
if ($('#name, #topic_title').length && $('#name, #topic_title').val().length) {
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}
}
// etc etc
});
(Well, as you have return, those could both just be if rather than else if...)
There are other problems though, for instance this expression in your final block:
$('#name, #topic_title').length
...which checks to see if either #name or #topic_title elements exist in your DOM at all (it doesn't do anything to check their values, and it doesn't require that they both exist, just one of them), and this:
$('#name, #topic_title').val().length
...will only check the value in #name, it will completely ignore the value in #topic_title, because when used as a getter, val only gets the value of the first element in the jQuery set. (Almost all of jQuery's functions that can be getters or setters are like that; the exception is text which is different from the others.)
Finally, this line:
this.enabled = true;
...is almost certainly a no-op, since the button cannot be clicked if it's not enabled, and as lshettyl points out, the property's name is disabled, not enabled. So this.disabled = false; if you're trying to enable it, or this.disabled = true; if you're trying to disable it.
By the look of your code, I assume you have a form that has either a class or an ID (or nothing). It'd be clever to use the form's submit event as opposed to click event of the submit button. This way you ensure that the form can also be submitted via the enter button (remember accessibility?). This is only an extension to T.J. Crowder's answer which has lots of good points from which you can learn/improve coding.
//Let's say your form has an ID 'topic'
$("#topic").on("submit", function() {
//Cache jQuery objects that would be resued, for better performance.
var $name = $("#name"),
$title = $("#topic_title"),
$msg = $('#message');
//One of the elements doesn't exist (exit)
//1 + 1 <= 1
if ($name.length + $title.length <= 1) {
return;
}
if ($.trim($name.val()) === "" || $.trim($title.val()) === "") {
$msg.html('you did not fill out one of the fields').css("color", "#be4343")
return;
} else if ($name.val().indexOf("Rich") !== -1) {
$msg.html("You have entered the wrong name.");
return;
} else {
//You do not need further checks such as length, val etc.
//as they have already been checked above.
var name = $name.val();
var topic_title = $title.val();
}
});
You can make comparison to know if it's empty:
if($('#name, #topic_title').length && $('#name, #topic_title').val().length){
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}}
if(name=='' || name==undefined){
//do stuff here
}
});

Simple javascript form validation won't return true

I created this function where it checks for multiple textboxes if they have values onsubmit. Basically it is a javascript form validator. When there are empty textboxes, form shouldn't submit and alert the user that there are required fields. Now, this works for me perfectly, however, when there are values already and the form is submitted, it still doesn't submit even though it should. I created an if statement to check if the errorString is empty or null, if it is, the form should submit but what happens is that it alerts the user with a blank string. I think the code is still going inside the if(errorString!=null || errorString=="") statement even though it shouldn't.
Thanks in advance
Please see my code below:
function validateForm()
{
var txtTitle = document.forms["actionStepsForm"]["txtTitle"].value;
var txtRequestor = document.forms["actionStepsForm"]["txtRequestor"].value;
var txtReprocessingRequest = document.forms["actionStepsForm"]["txtReprocessingRequest"].value;
document.getElementById('rowCount').value = counter-1;
var errorString = "";
if (txtTitle==null || txtTitle=="")
{
errorString += "Title field is required. \n";
}
if (txtRequestor==null || txtRequestor=="")
{
errorString += "Requestor field is required. \n";
}
if (txtReprocessingRequest==null || txtReprocessingRequest=="")
{
errorString += "Reprocessing request FR is required. \n";
}
if (errorString!=null || errorString!="")
{
alert(errorString);
return false;
}
else
{
return true;
}
}
//implementation if HTML form
<form name="actionStepsForm" id="actionStepsForm" action="add_reprocessing.php?action=add" method="POST" onsubmit="return validateForm()">
errorString can never be null because you've initialized it with "" so you can remove the condition "errorString != null".
It should become
if (errorString!="")
{
alert(errorString);
return false;
}
else
{
return true;
}
I think the correct condition should be
if (errorString != null && errorString != "")
otherwise the engine evaluated the 'errorString != null' condition, which evaluates to true (since errorString is "" and not null), and enter the code block.
Change
if (errorString!=null || errorString!="")
to
if (errorString!=null && errorString!="")
You have two 'not' statements that cancel each other out (one must always be false). Change it to:
if (errorString!=null && errorString!="")
{
alert(errorString);
return false;
}
else
{
return true;
}
The wrong line is the one everyone pointed out:
if (errorString!=null || errorString!="")
But I would like to point that you don't need to check for errorString!=null because you already created the variable as an empty string in the beginning of your code:
var errorString = ""; //created errorString as empty string
Therefore it will never actually be null, because you never set it as null anywhere (that is, you never set it as errorString = null).
If there are no errors, it will be an empty string always. So this will suffice:
if (errorString!="") //if errorString is different than what we created at `var`
{
alert(errorString);
return false;
}
else
{
return true;
}
Try With Different Logic. You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.
function myFunction() {
var errorString; //The Values can be like as null,blank,undefined,zero you can test
if(!(!(errorString))) //this condition is important
{
alert("errorString"+errorString);
}
else
{
alert("errorStringis "+errorString);
}
}

Javascript: onSubmit function submits form before function has finished?

I'm asking this because I am at a complete loss myself and need a fresh pair of eyes.
The following JavaScript function is successfully called on submission of the connected HTML form. The function starts and the first two if statements run (and halt the submission if they return false).
Then, the first test alert "before" appears and then the form submits, completely missing out the rest of the function. While testing I changed the final line to return false so that whatever happen the function should return false, but the form still submitted.
function validateForm(form)
{
// declare variables linked to the form
var _isbn = auto.isbn.value;
var _idisplay = auto.isbn.title;
var _iref = "1234567890X";
// call empty string function
if (EmptyString(_isbn,_idisplay)==false) return false;
// call check against reference function
if (AgainstRef(_isbn,_iref,_idisplay)==false) return false;
// call check length function
alert("before");///test alert
////// FORM SUBMITS HERE?!? /////////////
if (AutoLength(_isbn)==false) return false;
alert("after");///test alert
// if all conditions have been met allow the form to be submitted
return true;
}
Edit: this is what AutoLength looks like:
function AutoLength(_isbn) {
if (_isbn.length == 13) {
return true; {
else {
if (_isbn.length == 10) {
return true; {
else {
alert("You have not entered a valid ISBN10 or ISBN13. Please correct and try again.");
return false;
}
}
There are errors in your implementation of AutoLength. Currently, it looks like this:
function AutoLength(_isbn) {
if (_isbn.length == 13) {
return true; { // <------ incorrect brace
else {
if (_isbn.length == 10) {
return true; { // <------ incorrect brace
else {
alert("You have not entered a valid ISBN10 or ISBN13. Please correct and try again.");
return false;
}
}
See how it doesn't close all of its blocks? That's because you've used the wrong brace in two places, and you've forgotten to close the function.
You could rewrite the function like this:
function AutoLength(_isbn) {
return _isbn.length === 13 || _isbn.length === 10;
}
If you're hell-bent on using alert, you can do that inside validateForm (although I would try to find a more user-friendly way to show the error message).
In the future, when you're trying to debug code, you can use try and catch to "catch" Errors as they happen, like this:
try {
if (false === AutoLength(_isbn)) {
return false;
}
} catch (e) {
alert('AutoLength threw an error: '+e.message);
}
If the execution of the function is terminated by a runtime error, the form submits. So check out the script console log for error messages.

Categories

Resources