simple Form validation with javascript - javascript

I'm trying to create a simple HTML form & i want to use javascript to validate the values.
Here's the form tage:
<form action="" onSubmit="return formValidation();" method="Post" name="form">
Here's a part of the HTML form:
<label for="text">my text:</label>
<input type="text" name="text">
<div id="error"></div>
<input type="submit" value="submit">
& here's the formValidation() function:
function formValidation() {
var mytext=document.form.text;
if (textValidation(mytext, 3, 20)) {
}
return false;
}
& here's the textValidation() code:
function textValidation(txt, mn, mx) {
var txtlen = txt.value.length;
if (textlen == 0 || txtlen <=mn || txtlen > mx ) {
document.getElementById('error').innerHTML = '<h6 style="color: red;">text is invalid</h6>';
return false;
}
return true;
}
The problem is when i enter an invalid text, it shows the error but hitting the submit button again has no effect, even if i change the text.
i've used alert() & it worked fine.
what am i doing wrong?

You're setting the error text but you don't clear it so it just sticks around. Also, you have to return true in the if statement on your formValidation function otherwise it will always return false.
You can clear the message like this:
function textValidation(txt, mn, mx) {
var txtlen = txt.value.length;
if (textlen == 0 || txtlen <=mn || txtlen > mx ) {
document.getElementById('error').innerHTML = '<h6 style="color: red;">text is invalid</h6>';
return false;
}
document.getElementById('error').innerHTML = "";
return true;
}
Since formValidation always returns false, it will never allow the form to submit. That's fine for testing your JS, but later you'll want to use something like this:
function formValidation() {
var mytext=document.form.text;
if (textValidation(mytext, 3, 20)) {
return true;
}
return false;
}

You can write the form validate function like this
function formValidation() {
var mytext=document.form.text;
//if the variable boolval is initialized inside double quotes it is string now it is bool variable
var boolval=false;
if (textValidation(mytext, 3, 20)) {
boolval=true;
}
return boolval;
}
if textvalidation is true then it will initialize true to boolval or this function will return boolval false as we initialized before[which is default]

Your function formValidation() is always going to return false, regardless of the result of your conditional statement.
Consider your code, corrected in some ways:
function formValidation() {
var mytext=document.form.text;
if (textValidation(mytext, 3, 20)) {
}
return false;
}
If the function textValidation(mytext, 3, 20) is false, formValidation() returns false. If textValidation(mytext, 3, 20) is true, well... the body of the if statement executes, which is empty, and then formValidation returns false.
Additionally, there are also a number of mismatched parentheses and other syntax related issues in your code. Since Javascript is inherently flexible, you might miss these things in practice. I suggest using JSHint to validate and improve the general quality and design of your Javascript code.

Related

Stop form whitespace when user pressing submit

Okay, so I have a form. Applied a function to it.
All I want to do is when the form is submitted it launches the function, it checks to see if there is white space and throws out a message. I have the following:
function empty() {
var x;
x = document.getElementById("Username").value;
if (x == "") {
alert("Please ensure you fill in the form correctly.");
};
}
<input type='submit' value='Register' onClick='return empty()' />
<input type='text' id="Username" />
This is fine for if someone pressed the space-bar once and enters one line of whitespace, but how do I edit the function so that no matter how many spaces of whitespace are entered with the space-bar it will always throw back the alert.
Thanks in advance. I am very new to JavaScript. So please be gentle.
Trim the string before testing it.
x = document.getElementById("Username").value.trim();
This will remove any whitespace at the beginning and end of the value.
I have made a function for the same, i added another checks (including a regular expresion to detect multiples empty spaces). So here is the code:
function checkEmpty(field){
if (field == "" ||
field == null ||
field == "undefinied"){
return false;
}
else if(/^\s*$/.test(field)){
return false;
}
else{
return true;
}
}
Here is an example working with jquery: https://jsfiddle.net/p87qeL7f/
Here is the example in pure javascript: https://jsfiddle.net/g7oxmhon/
Note: the function checkEmpty still be the same for both
this work for me
$(document).ready(function() {
$('#Description').bind('input', function() {
var c = this.selectionStart,
r = /[^a-z0-9 .]/gi,
v = $(this).val();
if (r.test(v)) {
$(this).val(v.replace(r, ''));
c--;
}
this.setSelectionRange(c, c);
});
});
function checkEmpty(field) { //1Apr2022 new code
if (field == "" ||
field == null ||
field == "undefinied") {
return false;
} else if (/^\s*$/.test(field)) {
return false;
} else {
return true;
}
}

Regex form checking with Javascript

I'm having some real difficulty with javascript.
What I'm trying to do is validate user input from an HTML form.
I have two events for html:
<form action="attendproc.asp" method="post" onSubmit="return validateForm(this)">
<input type="submit" id="submit" value="Submit" class="button" onClick="return submitForm()">
Here is my javascript:
//Confirm form submission
function submitForm() {
if (confirm("Are you sure you want to submit this form?") == false) {return false}
else {return true}
}
//Validate form input
function validateForm(form) {
fail = validDate(form.date.value)
fail += validNum(form.jsia.value)
fail += validNum(form.jsga.value)
fail += validNum(form.yvcia.value)
fail += validNum(form.yvcga.value)
if (fail == "") {return true}
else {alert(fail) return false}
}
function validDate(field) {
if (/^\d{2}\/\d{2}\/\d{4}$/.test(field) == false) {return "Invalid date format. Please enter a valid date.\n"}
else {return ""}
}
function validNum(field) {
if (isNaN(field)) {return "Invalid input. Please enter a valid integer.\n"}
else {return ""}
}
Notice that I'm using RegEx to validate my desired date format. I know for certain the submitForm() function works. My pain is from the other three functions. Please help!
Shaun
I finally fixed it.
//Confirm form submission
function submitForm() {
if (confirm("Are you sure you want to submit this form?") == false) {return false;}
else {return true;}
}
//Validate attendance form input
function validateAttendForm(form) {
fail = validDate(form.date.value);
fail += validNum(form.jsia.value);
fail += validNum(form.jsga.value);
fail += validNum(form.yvcia.value);
fail += validNum(form.yvcga.value);
if (fail == "") {return true;}
else {alert(fail); return false;}
}
function validDate(field) {
re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
if (re.test(field) == false) {return "Invalid date format. Please enter a valid date.\n";}
else {return "";}
}
function validNum(field) {
if (isNaN(field) || field != parseInt(field)) {return "Invalid input. Please enter a valid interger.\n";}
else {return "";}
}
It was an issue with the syntax I used for my validDate() function. It was pretty much a plug and play fix.
Apart from shady formating, there's definately one thing that will cause problems.
isNaN(field)
should be: isNaN(parseInt(field))
IsNaN evaluates to true only with NaN, and string is not a NaN. ParseInt attempts to parse an int from a string, and returns either a number, or a NaN.

jQuery Use Loop for Validation?

I have rather large form and along with PHP validation (ofc) I would like to use jQuery. I am a novice with jQuery, but after looking around I have some code working well. It is checking the length of a Text Box and will not allow submission if it is under a certain length. If the entry is lower the colour of the text box changes Red.
The problem I have is as the form is so large it is going to take a long time, and a lot of code to validate each and every box. I therefore wondered is there a way I can loop through all my variables rather than creating a function each time.
Here is what I have:
var form = $("#frmReferral");
var companyname = $("#frm_companyName");
var companynameInfo = $("#companyNameInfo");
var hrmanagername = $("#frm_hrManager");
var hrmanagernameInfo = $("#hrManagerInfo");
form.submit(function(){
if(validateCompanyName() & validateHrmanagerName())
return true
else
return false;
});
Validation Functions
function validateCompanyName(){
// NOT valid
if(companyname.val().length < 4){
companyname.removeClass("complete");
companyname.addClass("error");
companynameInfo.text("Too Short. Please Enter Full Company Name.");
companynameInfo.removeClass("complete");
companynameInfo.addClass("error");
return false;
}
//valid
else{
companyname.removeClass("error");
companyname.addClass("complete");
companynameInfo.text("Valid");
companynameInfo.removeClass("error");
companynameInfo.addClass("complete");
return true;
}
}
function validateHrmanagerName(){
// NOT Valid
if(hrmanagername.val().length < 4){
hrmanagername.removeClass("complete");
hrmanagername.addClass("error");
hrmanagernameInfo.text("Too Short. Please Enter Full Name.");
hrmanagernameInfo.removeClass("complete");
hrmanagernameInfo.addClass("error");
return false;
}
//valid
else{
hrmanagername.removeClass("error");
hrmanagername.addClass("complete");
hrmanagernameInfo.text("Valid");
hrmanagernameInfo.removeClass("error");
hrmanagernameInfo.addClass("complete");
return true;
}
}
As you can see for 50+ input boxes this is going to be getting huge. I thought maybe a loop would work but not sure which way to go about it. Possibly Array containing all the variables? Any help would be great.
This is what I would do and is a simplified version of how jQuery validator plugins work.
Instead of selecting individual inputs via id, you append an attribute data-validation in this case to indicate which fields to validate.
<form id='frmReferral'>
<input type='text' name='company_name' data-validation='required' data-min-length='4'>
<input type='text' name='company_info' data-validation='required' data-min-length='4'>
<input type='text' name='hr_manager' data-validation='required' data-min-length='4'>
<input type='text' name='hr_manager_info' data-validation='required' data-min-length='4'>
<button type='submit'>Submit</button>
</form>
Then you write a little jQuery plugin to catch the submit event of the form, loop through all the elements selected by $form.find('[data-validation]') and execute a generic pass/fail validation function on them. Here's a quick version of what that plugin might look like:
$.fn.validate = function() {
function pass($input) {
$input.removeClass("error");
$input.addClass("complete");
$input.next('.error, .complete').remove();
$input.after($('<p>', {
class: 'complete',
text: 'Valid'
}));
}
function fail($input) {
var formattedFieldName = $input.attr('name').split('_').join(' ');
$input.removeClass("complete");
$input.addClass("error");
$input.next('.error, .complete').remove();
$input.after($('<p>', {
class: 'error',
text: 'Too Short, Please Enter ' + formattedFieldName + '.'
}));
}
function validateRequired($input) {
var minLength = $input.data('min-length') || 1;
return $input.val().length >= minLength;
}
return $(this).each(function(i, form) {
var $form = $(form);
var inputs = $form.find('[data-validation]');
$form.submit(function(e) {
inputs.each(function(i, input) {
var $input = $(input);
var validation = $input.data('validation');
if (validation == 'required') {
if (validateRequired($input)) {
pass($input);
}
else {
fail($input);
e.preventDefault();
}
}
})
});
});
}
Then you call the plugin like:
$(function() {
$('#frmReferral').validate();
});
You could give them all a class for jQuery use through a single selector. Then use your validation function to loop through and handle every case.
$(".validate").each(//do stuff);
form.submit(function(){
if(validateCompanyName() && validateHrmanagerName()) // Its logical AND not bitwise
return true
else
return false;
You can do this.
var x = $("input[name^='test-form']").toArray();
for(var i = 0; i < x.length; i++){
validateCompanyName(x[i]);
validateHrmanagerName(x[i]);
}

JavaScript code returns false, but still the form is submittted

I have a form with JavaScript validation. Upon there being an error, the submit button should 'grey-out' and the form should not be submitted. However, the last couple of functions seem to submit the form even though they pop the alert box. Why?
Button code:
<input type="submit" name="button" id="button"
onclick='return formvalidation();' value="Next" />
Non-working function example:
function BlankSite() {
var SiteNum= document.getElementsByName("sitesinput")[0].value;
if ((SiteNum == "") || (SiteNum == 0))
{
alert("You have not selected an amount of sites.")
document.forms[0].button.disabled = true;
return false;
}
}
Function initiator:
function formvalidation()
{
ZeroPhones();
BlankPC();
BlankSite();
BlankSeats();
phone_change();
} // End of formvalidation
This is very strange and I have tried various workarounds all to no avail!
You need to have return false; in the function called by the onclick, in this case formvalidation.
Having some function called by the "root" function return false has no effect whatsoever. The return value is lost.
They are returning false (and breaking, which is actually unreachable code) but the results are never returned to parent validation function. Your validator, assuming it's bound to the form action, should look like:
function formvalidation(){
{
if (!ZeroPhones())
return false;
if (!BlankPC())
return false;
//
// keep checking for false and return false.
//
// default to return true
return true;
}
So when the functions do in-fact return false, the false return is carried back up through to the bound function.
BlankPC() is called by formvalidation so false is returned into the method formvalidation().
Your formvalidation() is always falling off the end which is the same as returning true.
If you want it to return false when one of your validations fails, it should be:
function formvalidation()
{
retval = true;
retval &= ZeroPhones();
retval &= BlankPC();
retval &= BlankSite();
retval &= BlankSeats();
retval &= phone_change();
return retval;
} // End
This can be optimized a bunch, but you can get the gist of it.
Call the JavaScript function onSubmit of the form instead of calling at button onClick.
JavaScript code
function validate()
{
alert('test');
return false;
}
<form action="test" method="post" onsubmit="return validate();">
This is working fine for me.
formvalidation() isn't returning false.
Maybe you want something like:
function formvalidation()
{
if(!ZeroPhones() ||
!BlankPC() ||
!BlankSite() ||
!BlankSeats() ||
!phone_change())
return false;
}
My solution to this problem was to disable the submit button until the validation was successful. Something along these lines:
function checkPassword() {
// This is my submit button
document.getElementById('nextBtn').setAttribute('disabled', 'disabled');
password1 = document.getElementsByName("pwd1")[0].value;
password2 = document.getElementsByName("pwd2")[0].value;
if (password1 == '') {
// If password not entered
alert ("Please enter Password");
return false;
} else if (password2 == ''){
// If confirmation password not entered
alert ("Please enter confirm password");
return false;
} else if (password1 != password2) {
// If NOT the same, return false.
alert ("\nPassword did not match: Please try again...");
return false;
} else {
document.getElementById('nextBtn').removeAttribute('disabled');
return true;
}
}

[JavaScript]: How to define a variable as object type?

I am using following code to check whether a check box on my website page is checked or not. But there are several check boxes and I want to use this same function. I want to call this function from a Submit button click and pass the check box name as argument. It should than validate that check box.
function CheckTermsAcceptance()
{
try
{
if (!document.getElementById('chkStudent').checked)
alert("You need to accept the terms by checking the box.")
return false;
}
catch(err)
{
alert(err.description);
}
}
Just pass a parameter to CheckTermsAcceptance(). You also missed a brace after the alert -- there are two statements in that if block, and you'll always execute the return false without it.
function CheckTermsAcceptance(checkboxName)
{
try
{
if (!document.getElementById(checkboxName).checked) {
alert("You need to accept the terms by checking the box.")
return false;
}
}
catch(err)
{
alert(err.description);
}
}
To call this from your submit button, have a function like validateForm that's called on submit. Then simply construct a list of the checkboxes and pass in their IDs to CheckTermsAcceptance.
Note that this sort of validation is handled very smoothly by jQuery and its ilk. For example, here's the jQuery validation plugin.
function CheckTermsAcceptance(element){
try{
if (!element.checked){
alert("You need to accept the terms by checking the box.")
return false;
}
}catch(err){
alert(err.description);
}
}
and you call it like:
CheckTermsAcceptance(document.getElementById('chkStudent'));
is that it?
Sorry for not answering your questions. But you should seriously consider using jQuery and jQuery validate.
You could also use more arguments to allow for different options as well.
function CheckTermsAcceptance()
{
var ctrl = arguments[0];
var valueExpected = arguments[1];
var outputMessage = arguments[2];
if(valueExpected == null) valueExpected = true;
if(outputMessage == null) outputMessage = "You need to accept the terms by checking the box.";
try
{
if(ctrl.checked == valueExpected)
{
Log.Message(outputMessage);
}
}
catch(err)
{
alert(err.description);
}
}
this function will work with a bit of fix up, pass argument and make sure you do both the alert and the return false in the if statement
function CheckTermsAcceptance(checkBox) //added argument
{
try
{
if (!checkBox.checked) { //added block to group alert and fail case
alert("You need to accept the terms by checking the box.")
return false;
}
return true; //added success case
}
catch(err)
{
alert(err.description);
}
}
once you have this in place you can then use it on your form validation like so
<form id="formid" action="" onsubmit="return validate('formid');">
<input type=checkbox name="name" id="name"><label for="name">Name</label>
<input type=checkbox name="name2" id="name2"><label for="name2">Name2</label>
<input type=submit>
</form>
<script>
function validate(formid) {
var form = document.getElementById(formid);
for (var i = 0; i < form.elements.length; i++) {
var elem = form.elements[i];
if (elem.type == 'checkbox' && !CheckTermsAcceptance(elem)) {
return false;
}
}
return true;
}
</script>
i can confirm that this works in firefox 3.5
also jQuery and jQuery.validate make this very easy to implement in a very declarative way.

Categories

Resources