Using JavaScript Object Oriented Approach to Validate Form - javascript

I have been trying to use JS OOP to do form validation; I tested the code in Firefox and chrome :both browsers were just frozen. they did not submit regardless of whether or not the inputs matched the prescribed regular expression. So, who knows where I got it wrong? Pls: I know jQuery validator exists and I can also use plain JS to go as far as circumstances permit. Here, my interest is connecting JS OOP to the DOM. Blogs and textbooks I have read so far have not really shown me how to connect jS OOP to DOM scripting.So, I am just scavenging through rubble, looking for my way out.This code has taken a toll on my battery so I decided to share it here.
<form method = 'post' action ='somewhere.com' onsubmit = 'return formApp.validateInputs.apply(formApp);'>
<p>
Name: <input type = 'text' name = 'userName' id = 'userName'>
</p>
<p>
Phone: <input type = 'text' name = 'userPhone' id = 'userPhone'>
</p>
<input type = 'submit' id = 'sub' value = 'Submit Data'>
</form>
var formApp = {
userNameReg: /[a-z0-9 ' _ ]+/gi,
onlySpaceReg: /\s+/,
phoneReg: /\d{3}/,
userName: document.getElementById('userName').value,
userPhone: document.getElementById('userPhone').value,
error: [],
reportError: function () {
for (var i = 0; i < this.error.length; i++) {
alert(this.error[i] + '\n')
}
},
validateInputs: function () {
if (!this.userNameReg.test(this.userName) || this.onlySpaceReg.test(this.userName)) {
this.error.push['Name contains illegal character'];
return false
} // end name validation
if (!this.phoneReg.test(this.userPhone)) {
this.error.push['Only a three-digit number'];
return false;
} // end phone validation
if (this.error.length > 0) {
this.reportError();
return false;
}
return true;
} // end validateInputs
}; // end formApp obj

One of the problems is that you will never get an alert, because you return from the function in all the if blocks where you add an error. So the "this.reportError();" can never be executed. Remove the "return false" statements from ifs.
validateInputs: function () {
if (!this.userNameReg.test(this.userName) || this.onlySpaceReg.test(this.userName)) {
this.error.push['Name contains illegal character'];
}// end name validation
if (!this.phoneReg.test(this.userPhone)) {
this.error.push['Only a three-digit number'];
}// end phone validation
if (this.error.length > 0) {
this.reportError();
return false;
}
return true;
}

Related

simple Form validation with 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.

Having difficulty getting Javascript form to validate

Been looking for an answer for hours now and I still haven't come up with a solution. I've tried looking for similar question, but none have helped, really.
So basically, what doesn't work is that the form submits without any error messages even if there are mistakes on the form. Basically, I could leave the name field empty and the form will still submit once I press the button. Hope this made sense. Any help is appreciated
Code:
function validateFinale()
{
var emailOne = document.getElementById("em1").value;
var emailTwo = document.getElementById("em2").value;
var name = document.getElementById("name1").value;
if (compare())
{
if (name, 'Please enter name'))
{
if (validEmail(getElementById('em1'), 'Email invalid'))
{
}
}
}
return false;
}
function validName(elem, helpmsg) {
if (elem.value.length == 0) {
alert(helpmsg);
return false;
} else {
return true;
}
}
function validEmail(elem, msg) {
var wrongem = /^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]+$/;
if (elem.value.match(wrongem)) {
return true;
} else {
alert(msg);
return false;
}
}
function compare() {
if (emailOne != emailTwo) {
alert("Emails not the same");
submitOk = "false";
Document.getElementById("em1").value = " ";
Document.getElementById("em2").value = " ";
Document.getElementById("em1").focus();
} else {
alert("form complete, thank you");
}
}
http://jsfiddle.net/aj240/qgmt5yr8/
you made syntax mistake, first you declare emailOne as local variable, than try reach it in global scope. You should declare variables emailOne and emailTwo in global scope.
var emailOne;
var emailTwo;
function validateFinale()
{
emailOne = document.getElementById("em1").value;
emailTwo = document.getElementById("em2").value;
var name = document.getElementById("name1").value;
One gold tip, try press F12 in your browser and all errors messages would appear in console.
Try setting required ="true" in the input elems:
<input type="text" required ="true"...
Also, if you set type="email" in the e-mail field it will ask for an e-mail address (not at all, though, it just will accept anything with an "#")
And the code validName(getElementById('name1'), ...) should be validName(getElementById('name1').value, ...), or else you'll get all the HTML element

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 form validation not doing anything

i am trying to ensure an in put the contents of an input field is within an allowable number of character and if it is not print out an error message after the input field. the bellow js is contained in an external js file.
function validateForm()
{
var err_msg = getElementById('feedback_msg_first_name').value;
var first_name = getElementById('first_name').value;
if(first_name.length < 2)
{
err_msg.innerHTML = 'first name cannot contain less than 2 characters';
return false;
}
if(first_name.length > 20)
{
err_msg.innerHTML = 'first name cannot contain more than 20 characters';
err_msg.style.color = 'red';
}
}
The basic markup
<script type="text/javascript" language="javascript" src="client_form_val.js"></script>
</head>
<body>
<form id="register" name="register" action="includes/register.inc.php" method="post" onsubmit ="return validateForm();">
<label class="label">First Name:</label> <input type="text" name="first_name" id="first_name" /><br />
<span id="feedback_msg_first_name"></span>
the form is simply submitting without anything happening. where an I going wrong? any help would be appreciated.
Have a look at the following http://jsfiddle.net/VL7dc/2/
Rather than explaining where your going wrong, think you need to try and understand why this works and your doesnt.
function validateForm() {
var err_msg = document.getElementById('feedback_msg_first_name');
var first_name = document.getElementById('first_name').value;
if(first_name.length < 2) {
err_msg.innerHTML = 'first name cannot contain less than 2 characters';
return false;
} else {
err_msg.innerHTML = '';
}
if(first_name.length > 20)
{
err_msg.innerHTML = 'first name cannot contain more than 20 characters';
err_msg.style.color = 'red';
}
}
You are calling the function when keyup event is fired in form. As a result when a user start typing his/her name after typing a single character this will show the error message.
Instead of calling the function when keyup event is fired, call the function when some button click happens (When the whole first name is typed).
You are forgetting to do document.getElementById. Firebug is giving errors on that
Getting errors:
Uncaught ReferenceError: getElementById is not defined
When you fix the missing documents you get this
Uncaught TypeError: Cannot set property 'innerHTML' of undefined
Reason for the second is this
var err_msg = getElementById('feedback_msg_first_name').value; <-- string
err_msg.innerHTML = 'first name cannot contain less than 2 characters'; <--performing innerHTML on string
Try this
function validateForm()
{
var err_msg = document.getElementById('feedback_msg_first_name');
var first_name = document.getElementById('first_name').value;
if(first_name.length < 2)
{
err_msg.innerHTML = 'first name cannot contain less than 2 characters';
return false;
}
if(first_name.length > 20)
{
err_msg.innerHTML = 'first name cannot contain more than 20 characters';
err_msg.style.color = 'red';
}
}

[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