Javascript / jQuery form validation - javascript

Hey guys. I am currently using a very inefficient script to validate my forms. The code is massive.
The idea with this is if an input box is blank the input label is highlighted red and a div at the top of the form show's information on the error.
function new_receiver(){
if (document.getElementById("RecieversName").value ==""){ //First Name
var txt=document.getElementById("error_receiver");
txt.innerHTML="<p><font color=\"#FF0000\">You need to enter a Name!</font></p>";
window.document.getElementById("RecieversName_label").style.color = '#FF0000';
//Reset
window.document.getElementById("receiver_check_label").style.color = '#000000';
window.document.getElementById("RecieversNumber_label").style.color = '#000000';
window.document.getElementById("RecieversEmail_label").style.color = '#000000';
}else if (document.getElementById("RecieversNumber").value ==""){ //First Name
var txt=document.getElementById("error_receiver");
txt.innerHTML="<p><font color=\"#FF0000\">You need to enter a Phone Number!</font></p>";
window.document.getElementById("RecieversNumber_label").style.color = '#FF0000';
//Reset
window.document.getElementById("receiver_check_label").style.color = '#000000';
window.document.getElementById("RecieversName_label").style.color = '#000000';
window.document.getElementById("RecieversEmail_label").style.color = '#000000'
}else if (document.getElementById("RecieversNumber").value ==""){ //First Name
var txt=document.getElementById("error_receiver");
txt.innerHTML="<p><font color=\"#FF0000\">You need to enter an Email!</font></p>";
window.document.getElementById("RecieversEmail_label").style.color = '#FF0000';
//Reset
window.document.getElementById("receiver_check_label").style.color = '#000000';
window.document.getElementById("RecieversName_label").style.color = '#000000';
window.document.getElementById("RecieversNumber_label").style.color = '#000000';
}else{
from.receiver.submit();
}'
Any ideas or methods to making this process easy as some of my forms have up to 9 input boxes and this validation method is massive!
Cheers Guys!!!
Samuel.

I suggest something like this:
function new_receiver() {
var inputs = [
{
id: "RecieversName",
name: "a Name"
},
{
id: "RecieversNumber",
name: "a Phone Number"
}
// add more here
],
length = inputs.length,
error = document.getElementById("error_receiver"),
hasError = false,
i;
// reset
for (i = 0; i < length; i++) {
document.getElementById(inputs[i].id + "_label").style.color = "#000000";
}
error.innerHTML = "";
for (i = 0; i < length; i++) {
if (document.getElementById(inputs[i].id).value == "") {
error.innerHTML = "<p><font color=\"#FF0000\">You need to enter " + inputs[i].name + "!</font></p>";
document.getElementById(inputs[i].id + "_label").style.color = "#FF0000";
hasError = true;
break;
}
}
if (!hasError) {
from.receiver.submit();
}
}

You can start by trying something like this
$('input').blur(function() {
if($(this).val()==""){
$("#error_receiver").html("<p><font color=\"#FF0000\">This field is required!");
$("label[for=' + this.attr("id") + ']").css('color', '#FF0000');
}
});

Here is a suggestion without jQuery
<form onsubmit="return new_receiver()">
.
.
var formFields = {
"RecieversName": "You need to enter a Name!",
"RecieversNumber":"You need to enter a Number!",
"RecieversEmail":"You need to enter an Email!"
}
function new_receiver(){
var txt=document.getElementById("error_receiver");
//Reset
txt.innerHTML="";
for (var o in formFields) document.getElementById(o+"_label").style.color = '#000000';
for (var o in formFields) {
if (document.getElementById(o).value ==""){
txt.innerHTML="<p><font color=\"#FF0000\">"+formFields[o]+"</font></p>";
window.document.getElementById(o+"_label").style.color = '#FF0000';
return false;
}
}
return true
}

you can use jquery validation plugin http://bassistance.de/jquery-plugins/jquery-plugin-validation/

Related

Function not running after submitting name into prompt

entering correct student name associated with image within prompt but it is not running the "checkAnswer" function
this is the function
function checkAnswer() {
if (document.getElementById('response').value == personArray[currentId].firstname) {
//NOTE TO STUDENT: apply the class to reduce the opacity of the image,
//takeout the mouse events because they shouldn't be there anymore
document.getElementById(currentId).className = "opClass";
document.getElementById(currentId).removeAttribute("onclick");
document.getElementById(currentId).removeAttribute("onmouseover");
//superimpose name on image
var divVar = document.createElement('div');
divVar.setAttribute('id', currentId + 'name');
document.getElementById('pic-grid').appendChild(divVar);
var textNode = document.createTextNode(personArray[currentId].firstname);
divVar.appendChild(textNode);
document.getElementById(currentId + 'name').style.position = "absolute";
document.getElementById(currentId + 'name').style.top = y;
document.getElementById(currentId + 'name').style.left = x;
//clean up loose ends: hide the prompt, turn the frame white so it doesn't change to aqua on the rollover, erase the response and message
document.getElementById('prompt').style.display = 'none';
document.getElementById(currentId).parentNode.style.backgroundColor = 'white';
document.getElementById('response').value = "";
document.getElementById('message').innerHTML = "";
} else {
if (document.getElementById('message').innerHTML == "Wrong!") {
document.getElementById('message').innerHTML = "Incorrect answer!"
} else {
document.getElementById('message').innerHTML = "Wrong!"
}
}
return false;
}
Basically if the user enters the correct name in the prompt that is associated with the image they selected, the image should fade (opacity) and display the name of the student in the image (style position, top, & left) or if they enter the wrong name they are told within the prompt that they are wrong or incorrect.
As soon as I enter the correct student name, the prompt disappears and nothing happens or if I do the wrong name, it disappears as well.
here is the populateImages function that i forgot to place in here, sorry.
function populateImages() {
for (var i = 0; i < personArray.length; i++) {
var imageContainer = document.createElement("div");
var image = document.createElement("img");
imageContainer.classList.add('frame');
image.src = personArray[i].url;
image.setAttribute('onclick','promptForName(this)');
image.setAttribute('onmouseover','styleIt(this)');
image.setAttribute('onmouseout','unStyleIt(this)');
imageContainer.appendChild(image);
document.getElementById('pic-grid').appendChild(imageContainer);
}
}
Here's my HTML:
<body onload="populateImages()">
<header>
<h2>Class Flashcards</h2>
<h3>Click on a student to guess their name</h3>
<h4>Concepts: Rollovers, Opacity, Showing and Hiding Elements, Arrays of Objects, Adding and Removing Elements/Attributes Dynamically to the DOM,
Accessing Elements using parentnode</h4>
</header>
<div id="pic-grid">
</div>
<div id="prompt">
What is this student's name?<br>
<form onsubmit="return checkAnswer()">
<input type="text" id="response" name="quizInput">
</form>
<div id="message"></div>
</div>
</body>
the form is being submitted through this function and shows up when image is selected:
function promptForName(element) {
document.getElementById('response').value = "";
document.getElementById('message').innerHTML = "";
document.getElementById('prompt').style.display = 'block';
currentId = element.id;
x = element.offsetLeft;
y = element.offsetTop;
x = x + 20;
y = y + 20;
document.getElementById('prompt').style.position = "absolute";
document.getElementById('prompt').style.top = y;
document.getElementById('prompt').style.left = x;
document.getElementById('response').focus();
}
return false cancels submit action. you must insert a return true if everything is ok
try this function
function checkAnswer() {
if (document.getElementById('response').value == personArray[currentId].firstname) {
//NOTE TO STUDENT: apply the class to reduce the opacity of the image,
//takeout the mouse events because they shouldn't be there anymore
document.getElementById(currentId).className = "opClass";
document.getElementById(currentId).removeAttribute("onclick");
document.getElementById(currentId).removeAttribute("onmouseover");
//superimpose name on image
var divVar = document.createElement('div');
divVar.setAttribute('id', currentId + 'name');
document.getElementById('pic-grid').appendChild(divVar);
var textNode = document.createTextNode(personArray[currentId].firstname);
divVar.appendChild(textNode);
document.getElementById(currentId + 'name').style.position = "absolute";
document.getElementById(currentId + 'name').style.top = y;
document.getElementById(currentId + 'name').style.left = x;
//clean up loose ends: hide the prompt, turn the frame white so it doesn't change to aqua on the rollover, erase the response and message
document.getElementById('prompt').style.display = 'none';
document.getElementById(currentId).parentNode.style.backgroundColor = 'white';
document.getElementById('response').value = "";
document.getElementById('message').innerHTML = "";
return true; // return true if everything is ok
} else {
if (document.getElementById('message').innerHTML == "Wrong!") {
document.getElementById('message').innerHTML = "Incorrect answer!"
} else {
document.getElementById('message').innerHTML = "Wrong!"
}
return false; // return false if error
}
}

Kendo Validator always says multi-select is invalid

I have a multiselect that is dynamically created and appended to a template with the following bit of code:
if(fieldMap[i].required == true){
extraString = '<div class="k-edit-label" style="margin-top: -6px;"><label for="'+fieldMap[i].fieldName+'Input">'+fieldMap[i].fieldLabel+'*</label>'+helpText+'</div>\n<div data-container-for="'+fieldMap[i].fieldName+'Input" class="k-edit-field" id="'+fieldMap[i].fieldName+'Container">\n';
dynamicComponent = '\t<input class="multiselect-binder" id="'+fieldMap[i].fieldName+'Input" name="'+fieldMap[i].fieldName.toLowerCase()+'" data-auto-close="false" data-role="multiselect" data-bind="value:'+fieldMap[i].fieldName.toLowerCase()+'" required data-required-msg="Please Select Valid '+fieldMap[i].fieldLabel+'" data-source="[';
//dynamicComponent = '\t<select id="'+fieldMap[i].fieldName+'Input" data-role="dropdownlist" data-bind="value:'+fieldMap[i].fieldName.toLowerCase()+'" required data-required-msg="Please Select Valid '+fieldMap[i].fieldLabel+'">';
} else{
extraString = '<div class="k-edit-label" style="margin-top: -6px;"><label for="'+fieldMap[i].fieldName+'Input">'+fieldMap[i].fieldLabel+'</label>'+helpText+'</div>\n<div data-container-for="'+fieldMap[i].fieldName+'Input" class="k-edit-field" id="'+fieldMap[i].fieldName+'Container">\n';
dynamicComponent = '\t<input class="multiselect-binder" id="'+fieldMap[i].fieldName+'Input" data-auto-close="false" data-role="multiselect" data-bind="value:'+fieldMap[i].fieldName.toLowerCase()+'" data-source="[';
//dynamicComponent = '\t<select id="'+fieldMap[i].fieldName+'Input" data-role="dropdownlist" data-bind="value:'+fieldMap[i].fieldName.toLowerCase()+'">';
}
optString = '';
for(var k = 0; k < fieldMap[i].picklistVals.length; k++){
if(k == 0){
optString += '\''+fieldMap[i].picklistVals[k]+'\'';
}
else{
optString += ',\''+fieldMap[i].picklistVals[k]+'\'';
}
}
//Close the input component as well as the container div
dynamicComponent += optString + ']"/>\n<span class="k-invalid-msg" data-for="'+fieldMap[i].fieldName.toLowerCase()+'"></span></div>\n\n';
I run a validator.validate() on save button click to determine if information should be saved or not, which is dependent on if the multi-select input is required.
This pops up the invalid tooltip message when nothing is selected just fine. The issue is, however, that it will be marked invalid even if a selection is made. I am wondering if anyone has any solutions for how to get a validator to work correctly with the multiselect. Just hiding the pop ups is not really what I am after, as the validate() function will still fail even if the pop up is hidden, and I need the validate() function to pass.
Maybe not the best, but here is what I got.
function Save(){
$("#divTenureContainer .k-invalid").removeClass("k-invalid");
var tenureChecked = $("#chkTenure").prop('checked');
var tenureValid = Configuration_Tenure_Validator.validate();
}
Configuration_ValidateInput = (input) => {
var validationType = $(input).data("validation");
var required = $(input).prop("required") || $(input).hasClass("js-required");
if (!required) return true;
if (validationType) {
if (validationType === "stars") {
return $(input).val() > "0";
}
if (validationType === "hashtags") {
return ($(input).data("kendoMultiSelect").value().length > 0);
}
if (validationType === "required-text") {
return $(input).val() >= "";
}
}
return true;
}
var Configuration_ValidationRules = { rules: { Configuration_ValidateInput }, validationSummary: false };
var Configuration_Tenure_Validator = $("#divTenureContainer").kendoValidator(Configuration_ValidationRules).data("kendoValidator");

Js & Jquery:Understanding a search code with JSON request

i have a js search in my page that i don't get perfectly how does work because i don't know 100% js and jquery. As far as i think the code takes the input and search match with a link to a database that returns a JSON value depending on what name you put on the link (?name="the-input-name-here"), then, the code parse the json and determinates if the name of the input it's a valid surname and if it is the check if it has a running page, if it has redirects you to that page. If the input is a valid surname but doesn't have a running page it redirects you to "landing-page-yes.html". If the input isn't a valid surname it redirects you to "landing-page-no.html".
I need help to understand how the code does this in order to make a simplify version. How that call to another url database is parsed by the js ? How can i think something similar with a backend and ajax ? I need to understand 100% what this code does and i'm kinda lost.
THANKS !
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="srchid" width="100" onkeypress="submitonenter(document.getElementById('srchid').value, event, this)" />
<input onclick="nameCheck(document.getElementById('srchid').value);" value="CLICK HERE" type="button" style="background-color:#990033; color:#fff;border-style:outset;">
<div id="nameresults"></div>
<script >
<!--
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
} return false;
}
function cursor_wait() {
document.body.style.cursor = 'wait';
}
// Returns the cursor to the default pointer
function cursor_clear() {
document.body.style.cursor = 'default';
}
function nameCheck(sName) {
sName = trim(sName);
if(sName == ""){
alert("Please enter a name!");
return false;
}
cursor_wait();
routeToNameLookup(sName);
cursor_clear();
}
function $(id){return document.getElementById(id);}
// Get JSONP
function getJSON(url){
var s = document.createElement('script');
s.setAttribute('src',url);
document.getElementsByTagName('head')[0].appendChild(s);
}
function testcb(data){
//alert(data[0]);
}
function loaded(data) {
var name = document.getElementById('srchid').value;
var xmlhttp2;
//Using innerHTML just once to avoid multi reflow
$("nameresults").innerHTML = data[0];
if($("nameresults").innerHTML == 1){
if(data[1] == 1){
//display name page with content
var sNewName = name.replace (/'/g, ""); //remove any '
sNewName = removeSpaces(sNewName);
sNewName = convertNonAscii(sNewName);
//redirect to name crest
var sUrl = "http://www.heraldicjewelry.com/" + sNewName.toLowerCase() + "-crest-page.html";
//getJSON("http://www.gohapp.com/updatenamesearch.php?id=" + data[2] + "&pageurl=" + sUrl + "&callback=testcb");
//postwith(sUrl,{'pname':name});
window.location=sUrl;
} else {
//post to yes page
//postwith("http://www.heraldicjewelry.com/landing-page-yes.html",{'pname':name});
window.location="http://www.heraldicjewelry.com/landing-page-yes.html";
}
} else {
//post to no page
//postwith("http://www.heraldicjewelry.com/landing-page-no.html",{'pname':name});
window.location="http://www.heraldicjewelry.com/landing-page-no.html";
}
$("nameresults").innerHTML = "";
}
function routeToNameLookup(sSrchName) {
var name = document.getElementById('srchid').value;
if(sSrchName==""){
alert("Please enter your family name.");
} else {
var rn=Math.floor(Math.random()*1000000000000001)
getJSON("http://www.gohapp.com/namesearch_new.php?name="+name+"&rec=1&callback=loaded&rn="+rn);
}
}
function trim (sStr) {
var str = sStr.replace(/^\s+/, '');
for (var i = str.length - 1; i >= 0; i--) {
if (/\S/.test(str.charAt(i))) {
str = str.substring(0, i + 1);
break;
}
}
return str;
}
function postwith (to,p) {
var myForm = document.createElement("form");
myForm.method="post" ;
myForm.action = to ;
for (var k in p) {
var myInput = document.createElement("input") ;
myInput.setAttribute("name", k) ;
myInput.setAttribute("value", p[k]);
myForm.appendChild(myInput) ;
}
document.body.appendChild(myForm) ;
myForm.submit() ;
document.body.removeChild(myForm) ;
}
function removeSpaces(string) {
return string.split(' ').join('');
}
var PLAIN_ASCII =
"AaEeIiOoUu" // grave
+ "AaEeIiOoUuYy" // acute
+ "AaEeIiOoUuYy" // circumflex
+ "AaOoNn" // tilde
+ "AaEeIiOoUuYy" // umlaut
+ "Aa" // ring
+ "Cc" // cedilla
+ "OoUu" // double acute
;
var UNICODE =
"\u00C0\u00E0\u00C8\u00E8\u00CC\u00EC\u00D2\u00F2\u00D9\u00F9"
+ "\u00C1\u00E1\u00C9\u00E9\u00CD\u00ED\u00D3\u00F3\u00DA\u00FA\u00DD\u00FD"
+ "\u00C2\u00E2\u00CA\u00EA\u00CE\u00EE\u00D4\u00F4\u00DB\u00FB\u0176\u0177"
+ "\u00C3\u00E3\u00D5\u00F5\u00D1\u00F1"
+ "\u00C4\u00E4\u00CB\u00EB\u00CF\u00EF\u00D6\u00F6\u00DC\u00FC\u0178\u00FF"
+ "\u00C5\u00E5"
+ "\u00C7\u00E7"
+ "\u0150\u0151\u0170\u0171"
;
// remove accentued from a string and replace with ascii equivalent
function convertNonAscii(s) {
if (s == null)
return null;
var sb = '';
var n = s.length;
for (var i = 0; i < n; i++) {
var c = s.charAt(i);
var pos = UNICODE.indexOf(c);
if (pos > -1) {
sb += PLAIN_ASCII.charAt(pos);
} else {
sb += c;
}
}
return sb;
}
function submitonenter(name, evt,thisObj) {
evt = (evt) ? evt : ((window.event) ? window.event : "")
if (evt) {
// process event here
if ( evt.keyCode==13 || evt.which==13 ) {
thisObj.blur();
nameCheck(name);
//alert("looking for " + name);
}
}
}
//-->
</script>

Combining Javascript Validation Functions

Alright I need help combining the two JavaScript Functions... I have tried multiple times and am not coming up with any luck. There almost identical functions except the fact that I change one number so that it thinks there different textboxes. I tried putting a variable in its place but then it always only validates to the ending number of the loop. Please show me how I may be able to combine these two functions. (Its my only work around and I can not find any examples similar to mine)
First:
<script type="text/javascript">
var QnoText = ['abc_1']; // add IDs here for questions with optional text input
function doSubmit_1() {
var ids_1 = '';
flag_1 = true;
for (i=0; i<QnoText.length; i++) {
CkStatus = document.getElementById(QnoText[i]).checked;
ids_1 = QnoText[i]+'Certificate_1';
if (CkStatus && document.getElementById(ids_1).value == '') {
alert('Please enter certificate number 1.');
document.getElementById(ids_1).focus();
flag_1 = false;
alert('return flag_1');
}
}
return flag_1;
}
</script>
Second:
<script type="text/javascript">
var QnoText = ['abc_2']; // add IDs here for questions with optional text input
function doSubmit_2() {
var ids_2 = '';
flag_2 = true;
for (i=0; i<QnoText.length; i++) {
CkStatus = document.getElementById(QnoText[i]).checked;
ids_2 = QnoText[i]+'Certificate_2';
if (CkStatus && document.getElementById(ids_2).value == '') {
alert('Please enter certificate number 2.');
document.getElementById(ids_2).focus();
flag_2 = false;
alert('return flag_2');
}
}
return flag_2;
}
</script>
You can pass a parameter in your function with the number of the textbox, like this:
var QnoText = ['abc_2']; // add IDs here for questions with optional text input
function doSubmit(n) {
var ids = '';
flag = true;
for (i=0; i<QnoText.length; i++) {
CkStatus = document.getElementById(QnoText[i]).checked;
ids = QnoText[i]+'Certificate_' + n;
if (CkStatus && document.getElementById(ids).value == '') {
alert('Please enter certificate number ' + n + '.');
document.getElementById(ids).focus();
flag = false;
alert('return flag_' + n);
}
}
return flag;
}
doSubmit(1); // for your submit 1
doSubmit(2); // for your submit 2
Is this what you wanted? because is not very clear. If is not feel free to explain.

Toggling case on click of a button

I'm having a text area, user can type in the text area, in start it will be lower case, but once user click on the 'T(toggle)' button, what ever typing after that will change to upper case previous one will be in lower case only . If again user click on the 'T(toggle button)' what ever type after that will appear in lower case and so on. I tried but that was not successful.
<input type="button" name="toggleCase" id="toggleCase" value="T" style="width:40px;" onclick="javascript:changeCase(this);" />
<textarea tabindex="1" cols="39" rows="2" onkeydown="checkTxtCase(this);" name="titleText1"> </textarea>
JS:
function checkTxtCase(elmObj) {
setCursorToTextEnd(elmObj.id);
var txtVal = elmObj.value;
var txtLen = txtVal.length;
prevSize = txtLen;
var txtLast = txtVal.substring(txtLen - 1, txtLen);
if (textCase == 'LOWER') {
elmObj.value = txtVal.substring(0, txtLen - 1) + txtLast.toLowerCase();
} else {
elmObj.value = txtVal.substring(0, txtLen - 1) + txtLast.toUpperCase();
}
return true;
}
function setCursorToTextEnd(textControlID) {
var text = document.getElementById(textControlID);
if (text != null && text.value.length > 0) {
if (text.createTextRange) {
var FieldRange = text.createTextRange();
FieldRange.moveStart('character', text.value.length);
FieldRange.collapse();
FieldRange.select();
} else if (text.setSelectionRange) {
var textLength = text.value.length;
text.setSelectionRange(textLength, textLength);
}
}
}
var textCase = 'UPPER';
var prevSize = 0;
function changeCase() {
document.getElementById('titleText1').focus();
textCase = (textCase == 'LOWER') ? 'UPPER' : 'LOWER';
}
Any suggestion is appreciated.
var textCase = 'toLowerCase';
var pos = 0;
function changeCase() {
var textarea = document.getElementsByName('titleText1')[0];
pos = textarea.value.length;
textCase = (textCase == 'toUpperCase') ? 'toLowerCase' : 'toUpperCase';
textarea.focus();
}
function checkTxtCase(elem) {
var l = elem.value.substr(pos);
elem.value = elem.value.substr(0, pos) + l[textCase]();
}
FIDDLE
I have found out a plugin for you. Its really cool and it really works.
http://jquerybyexample.blogspot.com/2011/12/jquery-plugin-for-uppercase-lowercase.html
This will help you
I have created a fiddle for you. Check It
http://jsfiddle.net/KKX5G/2/
$('#Txt').Setcase({caseValue : 'lower'});

Categories