How disable javascript effect on separated input field? - javascript

This is the Javascript that turns on Georgian keyboard in every input and textarea field
But I have one input field with ID user_login which type is text and of course, this javascript takes effect on this field too
I simply want to disable the effect of this javascript only for this field which ID is user_login
Please help me
thank you in advance
HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="jquery.geokbd.css">
<script type="text/javascript" src="/js/jquery_min.js"></script>
<script type="text/javascript" src="jquery.geokbd.js"></script>
</head>
<body>
<div class="gk-switcher">
<input id="kbd-switcher" type="checkbox">
</div>
<form>
<input type="text" placeholder="Title">
<input type="text" placeholder="Description">
<input placeholder="Password" type="password">
<input placeholder="Email" type="email">
</form>
<input placeholder="Email" type="email">
<input placeholder="About me" maxlength="11" type="text">
<input placeholder="Username:" type="text" name="user_login" id="user_login" class="wide">
<script>
$('#kbd-switcher').geokbd();
</script>
</body>
</html>
and code
(function($, undefined) {
$.fn.geokbd = function(options) {
var
isOn,
inputs = $([]),
switchers = $([]),
defaults = {
on: true,
hotkey: '`'
},
settings = (typeof options === 'object' ? $.extend({}, defaults, options) : defaults);
// first come up with affected set of input elements
this.each(function() {
var $this = $(this);
if ($this.is(':text, textarea')) {
inputs = inputs.add($this);
} else if ($this.is('form')) {
inputs = inputs.add($this.find(':text, textarea'));
} else if ($this.is(':checkbox')) {
if (!inputs.length) {
inputs = $(':text, textarea');
}
switchers = switchers.add($this); // store the checkboxes for further manipulation
}
if (typeof settings.exclude === 'string') {
inputs = inputs.not(settings.exclude);
}
});
// mutate switchers
switchers
.click(function() { toggleLang() })
.wrap('<div class="gk-switcher"></div>')
.parent()
.append('<div class="gk-ka" /><div class="gk-us" />');
// turn on/off all switchers
toggleLang(isOn = settings.on);
$(document).keypress(function(e) {
var ch = String.fromCharCode(e.which), kach;
if (settings.hotkey === ch) {
toggleLang();
e.preventDefault();
}
if (!isOn || !inputs.filter(e.target).length) {
return;
}
kach = translateToKa.call(ch);
if (ch != kach) {
if (navigator.appName.indexOf("Internet Explorer")!=-1) {
window.event.keyCode = kach.charCodeAt(0);
} else {
pasteTo.call(kach, e.target);
e.preventDefault();
}
}
});
function toggleLang() {
isOn = arguments[0] !== undefined ? arguments[0] : !isOn;
switchers
.each(function() {
this.checked = isOn;
})
.closest('.gk-switcher')[isOn ? 'addClass' : 'removeClass']('gk-on');
}
// the following functions come directly from Ioseb Dzmanashvili's GeoKBD (https://github.com/ioseb/geokbd)
function translateToKa() {
/**
* Original idea by Irakli Nadareishvili
* http://www.sapikhvno.org/viewtopic.php?t=47&postdays=0&postorder=asc&start=10
*/
var index, chr, text = [], symbols = "abgdevzTiklmnopJrstufqRySCcZwWxjh";
for (var i = 0; i < this.length; i++) {
chr = this.substr(i, 1);
if ((index = symbols.indexOf(chr)) >= 0) {
text.push(String.fromCharCode(index + 4304));
} else {
text.push(chr);
}
}
return text.join('');
}
function pasteTo(field) {
field.focus();
if (document.selection) {
var range = document.selection.createRange();
if (range) {
range.text = this;
}
} else if (field.selectionStart != undefined) {
var scroll = field.scrollTop, start = field.selectionStart, end = field.selectionEnd;
var value = field.value.substr(0, start) + this + field.value.substr(end, field.value.length);
field.value = value;
field.scrollTop = scroll;
field.setSelectionRange(start + this.length, start + this.length);
} else {
field.value += this;
field.setSelectionRange(field.value.length, field.value.length);
}
};
}
}(jQuery));

If you call your plugin on the form element, instead of the checkbox and then search the document for all desired element types except the one with the id of user_login, your inputs JQuery wrapper will only contain the elements you want.
(function($, undefined) {
$.fn.geokbd = function(options) {
var
isOn,
inputs = $([]),
switchers = $([]),
defaults = {
on: true,
hotkey: '`'
},
settings = (typeof options === 'object' ? $.extend({}, defaults, options) : defaults);
// first come up with affected set of input elements
// Using the standard DOM API, search the document for all `input` and
// 'textarea' elements, except for the one with an id of: "user_login"
document.querySelectorAll("input:not(#user_login), textarea").forEach(function(item) {
var $this = $(item);
// You had the selector for an input incorrect
if ($this.is('input[type="text"], textarea')) {
inputs = inputs.add($this);
} else if ($this.is('form')) {
inputs = inputs.add($this.find('input[type="text"], textarea'));
} else if ($this.is(':checkbox')) {
if (!inputs.length) {
inputs = $('input[type="text"], textarea');
}
switchers = switchers.add($this); // store the checkboxes for further manipulation
}
if (typeof settings.exclude === 'string') {
inputs = inputs.not(settings.exclude);
}
});
// mutate switchers
switchers
.click(function() { toggleLang() })
.wrap('<div class="gk-switcher"></div>')
.parent()
.append('<div class="gk-ka" /><div class="gk-us" />');
// turn on/off all switchers
toggleLang(isOn = settings.on);
$(document).keypress(function(e) {
var ch = String.fromCharCode(e.which), kach;
if (settings.hotkey === ch) {
toggleLang();
e.preventDefault();
}
if (!isOn || !inputs.filter(e.target).length) {
return;
}
kach = translateToKa.call(ch);
if (ch != kach) {
if (navigator.appName.indexOf("Internet Explorer")!=-1) {
window.event.keyCode = kach.charCodeAt(0);
} else {
pasteTo.call(kach, e.target);
e.preventDefault();
}
}
});
function toggleLang() {
isOn = arguments[0] !== undefined ? arguments[0] : !isOn;
switchers
.each(function() {
this.checked = isOn;
})
.closest('.gk-switcher')[isOn ? 'addClass' : 'removeClass']('gk-on');
}
// the following functions come directly from Ioseb Dzmanashvili's GeoKBD (https://github.com/ioseb/geokbd)
function translateToKa() {
/**
* Original idea by Irakli Nadareishvili
* http://www.sapikhvno.org/viewtopic.php?t=47&postdays=0&postorder=asc&start=10
*/
var index, chr, text = [], symbols = "abgdevzTiklmnopJrstufqRySCcZwWxjh";
for (var i = 0; i < this.length; i++) {
chr = this.substr(i, 1);
if ((index = symbols.indexOf(chr)) >= 0) {
text.push(String.fromCharCode(index + 4304));
} else {
text.push(chr);
}
}
return text.join('');
}
function pasteTo(field) {
field.focus();
if (document.selection) {
var range = document.selection.createRange();
if (range) {
range.text = this;
}
} else if (field.selectionStart != undefined) {
var scroll = field.scrollTop, start = field.selectionStart, end = field.selectionEnd;
var value = field.value.substr(0, start) + this + field.value.substr(end, field.value.length);
field.value = value;
field.scrollTop = scroll;
field.setSelectionRange(start + this.length, start + this.length);
} else {
field.value += this;
field.setSelectionRange(field.value.length, field.value.length);
}
};
}
$('form').geokbd();
}(jQuery));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="jquery.geokbd.css">
</head>
<body>
<div class="gk-switcher">
<input id="kbd-switcher" type="checkbox">
</div>
<form>
<input type="text" placeholder="Title">
<input type="text" placeholder="Description">
<input placeholder="Password" type="password">
<input placeholder="Email" type="email">
</form>
<input placeholder="Email" type="email">
<input placeholder="About me" maxlength="11" type="text">
<input placeholder="Username:" type="text" name="user_login" id="user_login" class="wide">
</body>
</html>

Related

How to toggle a class of an input element when a value is inserted on that element

I am having a javascript handler on an input html element. The input html elements may be many.. The point is whenever I insert a value on the input html element I would like to add a class on that element in order to change the background-color of the input that has a value. Right now I am doing: **$('this.seat_box').toggleClass('selected');******** but this will affect all the elements that has the class. Is there a way to pass an argument on the handler function in the input element refering somehow to this? I have tried to pass the arguments or argument like:
onchange="bc.seatBoxHandleEvent('input', this) and none of these worked...
Any help appreciated.!
The Html code:
<div class="bus-builder-seat-box-container" id="dynamic-bus-builder-1">
<input id="posA100" type="text" class="seat_box" onchange="bc.seatBoxHandleEvent()">
<input id="posA101" type="text" class="seat_box" onchange="bc.seatBoxHandleEvent()">
</div>
I have the following code for javascript validation:
bc.seatBoxHandleEvent = function () {
bc.checkInput();
var seatNumberFirstFloor = $('#dynamic-bus-builder-1');
if (seatNumberFirstFloor && seatNumberFirstFloor.valueOf()) {
var leftStreaming = (event.target.id);
var rightStreaming = 'posB1' + leftStreaming.substring(5, 7);
document.getElementById(rightStreaming).innerHTML = event.target.value;
}
}
bc.checkInput = function () {
var targetValue = event.target.value;
var id = event.target.id;
var classOfInput = event.target.classList;
if (targetValue !== 8 && targetValue !== 0 && (targetValue < 48 || targetValue > 57)) {
console.log('valid number');
console.log(classOfInput);
**$('this.seat_box').toggleClass('selected');********
}
else {
console.log('invalid character');
}
}
Pass the element to the function from HTML.
bc = [];
bc.seatBoxHandleEvent = function (el) {
bc.checkInput(el);
var seatNumberFirstFloor = $('#dynamic-bus-builder-1');
if (seatNumberFirstFloor && seatNumberFirstFloor.valueOf()) {
var leftStreaming = (event.target.id);
var rightStreaming = 'posB1' + leftStreaming.substring(5, 7);
}
}
bc.checkInput = function (el) {
var targetValue = event.target.value;
var id = event.target.id;
var classOfInput = event.target.classList;
if (targetValue !== 8 && targetValue !== 0 && (targetValue < 48 || targetValue > 57)) {
console.log('valid number');
console.log(classOfInput);
$(el).toggleClass('selected');
}
else {
console.log('invalid character');
}
}
div.class1 {
border: 1px solid #000;
padding: 10px;
background-color: #FFCC00;
}
.selected {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div class="bus-builder-seat-box-container" id="dynamic-bus-builder-1">
<input id="posA100" type="text" class="seat_box" onchange="bc.seatBoxHandleEvent(this)">
<input id="posA101" type="text" class="seat_box" onchange="bc.seatBoxHandleEvent(this)">
</div>
I did just rewrote bc to an object instead, the syntax is apart from that the same. But this one works. Remember that the onchange event is only trigger on blur. So if you want the event to trigger when entering a value then use onkeypress event instead.
JS
var BC = function () {
this.seatBoxHandleEvent = function () {
var checkInput = function () {
var targetValue = event.target.value;
var id = '#' + event.target.id;
if (targetValue !== 8 && targetValue !== 0 && (targetValue < 48 || targetValue > 57)) {
console.log('valid number');
console.log(event.target.classList); // [seat-box] set on the event.target
$(id).toggleClass('selected');
console.log(event.target.classList); // [seat-box, selected] set on the event.target
}
else {
console.log('invalid character');
}
};
checkInput();
};
};
this.bc = new BC();
HTML
<div class="bus-builder-seat-box-container" id="dynamic-bus-builder-1">
<input id="posA100" type="text" class="seat_box" onchange="bc.seatBoxHandleEvent()">
<input id="posA101" type="text" class="seat_box" onchange="bc.seatBoxHandleEvent()">
</div>

How will i prevent duplication of value and empty value

How can I prevent duplicate values being added to a combobox? I also need to prevent the space value. This is my code but its not working.
An entry is entered the first time input but the second time I enter input its alerting me that I have entered a duplicate value even when I enter different values.
Please see this jsFiddle https://jsfiddle.net/adLxoakv/
<HTML>
<HEAD>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<fieldset>
<legend>Combo box</legend>
Add to Combo: <input type="text" name="txtCombo" id="txtCombo"/>
Selected: <input type="text" name="selected" id="selected"/>
IMEI Selected: <input type="text" name="imei" id="imei"/>
<input type="button" id="button" value="Add" onclick="addCombo()">
<br/>
Combobox: <select name="combo" multiple id="combo"></select>
</fieldset>
</BODY>
</HTML>
<script>
$("#txtCombo").on("keydown", function (e) {
return e.which !== 32;
});
$(document).ready(function() {
$('#button').click(function(){
var data = [];
$.each($("#combo option:selected"), function() {
data.push($(this).attr("value"));
});
$('#imei').val(data.join(","));;
var count = $("#combo :selected").length;
$('#selected').val(count);
});
});
$("#combo").on('change', function () {
var count = $("#combo :selected").length;
$('#selected').val(count);
});
var text = $("#text").val();
function addCombo() {
var textb = document.getElementById("txtCombo");
var combo = document.getElementById("combo");
var option = document.createElement("option");
option.text = textb.value;
option.value = textb.value;
option.selected = true;
if (textb.length == 0) {
return false;
}
if (combo.length) {
alert("Duplicate found");
return false;
}
try {
combo.add(option, null ); //Standard
}catch(error) {
combo.add(option); // IE only
}
textb.value = "";
}
// separated by comma to textbox
$(document).ready(function() {
$("#combo").change(function() {
var data = [];
$.each($("#combo option:selected"), function() {
data.push($(this).attr("value"));
});
$('#imei').val(data.join(","));;
});
});
</script>
To find the duplicate you can use following function(using jQuery)
function isDuplicate(value,text){
/*Get text of the option identified by given value form the combobox and then check if its text matches the given text*/
if($('#combo select option[value="' + value + '"]').text() == text)
return true;
else
return false;
}
Update:
function addCombo() {
var textb = document.getElementById("txtCombo");
var combo = document.getElementById("combo");
var option = document.createElement("option");
var value = textb.value.trim();
option.text = value;
option.value = value;
option.selected = true;
if (textb.length == 0) {
return false;
}
if ($('#combo option[value="' + value + '"]').text() == value ) {
alert("Duplicate found");
return false;
}
try {
combo.add(option, null ); //Standard
}catch(error) {
combo.add(option); // IE only
}
textb.value = "";
}

Can I select a multi-dimensional HTML array in JavaScript as a multi-dimensional array?

If I have the following HTML on a page:
<input type="hidden" name=item[0][id]>
<input type="text" name=item[0][title]>
<input type="text" name=item[0][description]>
<input type="hidden" name=item[1][id]>
<input type="text" name=item[1][title]>
<input type="text" name=item[1][description]>
<input type="hidden" name=item[2][id]>
<input type="text" name=item[2][title]>
<input type="text" name=item[2][description]>
I would like to select the items using JavaScript (or JQuery) in such a way that I can loop over the items using the outer array.
Currently I have the following JQuery/JavaScript to handle the items:
var items = ($('[name*="item["]'));
var i = 0;
while (i < items.length) {
if (items[i++].value === '') {
// No ID set.
}
else if (items[i++].value === '') {
// No title set.
}
else if (items[i++].value === '') {
// No description set.
}
}
Is there a way to select the elements so that I can loop over them using notation more like the following (Where items.length is 3)?
for (var i = 0; i < items.length; i++) {
if (items[i][0].value === '') {
// No ID set.
}
else if (items[i][1].value === '') {
// No title set.
}
else if (items[i][2].value === '') {
// No description set.
}
}
Or even more like this?
for (var i = 0; i < items.length; i++) {
if (items[i].id.value === '') {
// No ID set.
}
else if (items[i].title.value === '') {
// No title set.
}
else if (items[i].description.value === '') {
// No description set.
}
}
Or would this require more manipulation and processing to go from selecting from the DOM to creating the data structure to loop over?
I think this is exactly what you are looking for (which is not really related to selectors):
function serialize () {
var serialized = {};
$("[name]").each(function () {
var name = $(this).attr('name');
var value = $(this).val();
var nameBits = name.split('[');
var previousRef = serialized;
for(var i = 0, l = nameBits.length; i < l; i++) {
var nameBit = nameBits[i].replace(']', '');
if(!previousRef[nameBit]) {
previousRef[nameBit] = {};
}
if(i != nameBits.length - 1) {
previousRef = previousRef[nameBit];
} else if(i == nameBits.length - 1) {
previousRef[nameBit] = value;
}
}
});
return serialized;
}
console.log(serialize());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" name=item[0][id]>
<input type="text" name=item[0][title]>
<input type="text" name=item[0][description]>
<input type="hidden" name=item[1][id]>
<input type="text" name=item[1][title]>
<input type="text" name=item[1][description]>
<input type="hidden" name=item[2][id]>
<input type="text" name=item[2][title]>
<input type="text" name=item[2][description]>
See the related JSFiddle sample.
Here's a way to add a custom function into JQuery to get the data structure you're looking for.
$.fn.getMultiArray = function() {
var $items = [];
var index = 0;
$(this).each(function() {
var $this = $(this);
if ($this.attr('name').indexOf('item[' + index + ']') !== 0)
index++;
if (!$items[index])
$items[index] = {};
var key = $this.attr('name').replace('item[' + index + '][', '').replace(']', '');
$items[index][key] = $this;
});
return $items;
};
var $items = $('input[name^="item["]').getMultiArray();
This allows you to have the references in your "ideal" example.
var $items = $('input[name^="item["]').getMultiArray();
$items[0].id;
JS Fiddle: https://jsfiddle.net/apphffus/

Javascript: submit button is not active when enter data to the form

I've picked up this code and it does not seem to work. The problem is the 'submit' button is not active when i try to click after i entered all the data to the form. Any help on where i am lacking? please
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="ourForm">
<label>First Name</label><input type="text" /><br />
<label>Last Name</label><input type="text" /><br />
<label>Email</label><input type="text" /><br />
<input type="submit" value="submit" />
</form>
<script type="text/javascript">
function addEvent(to, type, fn){
if(document.addEventListener){
to.addEventListener(type, fn, false);
} else if(document.attachEvent){
to.attachEvent('on'+type, fn);
} else {
to['on'+type] = fn;
}
};
var Form = {
validClass : 'valid',
fname : {
minLength : 1,
maxLength : 15,
fieldName : 'First Name'
},
lname : {
minLength : 1,
maxLength : 25,
fieldName : 'Last Name'
},
validateLength : function(formEl, type){
if(formEl.value.length > type.maxLength || formEl.value.length < type.minLength ){
formEl.className = formEl.className.replace(' '+Form.validClass, '');
return false;
} else {
if(formEl.className.indexOf(' '+Form.validClass) == -1)
formEl.className += ' '+Form.validClass;
return true;
}
},
validateEmail : function(formEl){
var regEx = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*#([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;
var emailTest = regEx.test(formEl.value);
if (emailTest) {
if(formEl.className.indexOf(' '+Form.validClass) == -1)
formEl.className += ' '+Form.validClass;
return true;
} else {
formEl.className = formEl.className.replace(' '+Form.validClass, '');
return false;
}
},
getSubmit : function(formID){
var inputs = document.getElementById(formID).getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++){
if(inputs[i].type == 'submit'){
return inputs[i];
}
}
return false;
}
};
addEvent(window, 'load', function(){
var ourForm = document.getElementById('ourForm');
var submit_button = Form.getSubmit('ourForm');
submit_button.disabled = 'disabled';
function checkForm(){
var inputs = ourForm.getElementsByTagName('input');
if(Form.validateLength(inputs[0], Form.fname)){
if(Form.validateLength(inputs[1], Form.lname)){
if(Form.validateEmail(inputs[2])){
submit_button.disabled = false;
return true;
}
}
}
submit_button.disabled = 'disabled';
return false;
};
checkForm();
addEvent(ourForm, 'keyup', checkForm);
addEvent(ourForm, 'submit', checkForm);
});
</script>
</body>
</html>
I copied the code and tried the same code. It works. It might be that you filled all the three inputs but you did not put correct EMAIL that fulfills the EMAIL format(regex) in the code.
For example try to fill inputs with these three inputs someone, someone, someone#gmail.com; Submit is enabled

Form Validation with Javascript using window.onload

Hi there I am really stuck on this and since I am a javscript beginner this boggles my mind.
Is there someone who knows how to write the following javascript form validation?
I am sure that it is very simple, but I can not figure this one out to save my life.
Thank you for you sharing your knowledge.
I need to write WITHOUT jquery the following form validation. Whenever an error is encountered, prevent the form from being submitted. I need to use the window.onload function to assign a validation callback function. There are 4 inputs which get validated by the javascript code. Also the javascript needs to be in its own file.
Validation Rules are as follow:
INPUT: Username; Required (yes); Validation (Must be 5-10 characters long).
INPUT: Email; Required (yes); Validation (Must have an # sign, must have a period).
INPUT: Street name; Required (no); Validation (Must start with a number).
INPUT: Year of birth; Required (yes); Validation (must be numeric).
My code looks as follow:
HTML:
<!DOCTYPE html>
<html>
<head>
<script defer="defer" type="text/javascript" src="form.js"></script>
</head>
<body>
<form action="fake.php">
Username*: <input type="text" class="required" name="u"/><br/>
Email*: <input type="text" class="required" name="p"/><br/>
Street address: <input type="text" class="numeric" name="s"/><br/>
Year of birth*: <input type="text" class="required numeric" name="b"/><br/>
<input type="submit"/><br/>
</form>
</body>
</html>
JS
document.forms[0].elements[0].focus();
document.forms[0].onsubmit=function(){
for(var i = 0; i < document.forms[0].elements.length; i++){
var el = document.forms[0].elements[i];
if((el.className.indexOf("required") != -1) &&
(el.value == "")){
alert("missing required field");
el.focus();
el.style.backgroundColor="yellow";
return false;
}
if((el.className.indexOf("numeric") != -1) &&
(isNaN(el.value))){
alert(el.value + " is not a number");
el.focus();
el.style.backgroundColor="pink";
return false;
}
}
}
without changing much of your code ... updated your code for other validation like length (needs a class verifylength to validate length) and so on....
try this
HTML
<form action="fake.php">Username*:
<input type="text" class="required verifylength" name="u" />
<br/>Email*:
<input type="text" class="required email" name="p" />
<br/>Street address:
<input type="text" class="numeric" name="s" />
<br/>Year of birth*:
<input type="text" class="required numeric" name="b" />
<br/>
<input type="submit" />
<br/>
</form>
JAVASCRIPT
document.forms[0].elements[0].focus();
document.forms[0].onsubmit = function () {
for (var i = 0; i < document.forms[0].elements.length; i++) {
var el = document.forms[0].elements[i];
if ((el.className.indexOf("required") != -1) && (el.value == "")) {
alert("missing required field");
el.focus();
el.style.backgroundColor = "yellow";
return false;
} else {
if (el.className.indexOf("verifylength") != -1) {
if (el.value.length < 5 || el.value.length > 10) {
alert("'" + el.value + "' must be 5-10 charater long");
el.focus();
el.style.backgroundColor = "pink";
return false;
}
}
}
if (el.className.indexOf("email") != -1) {
var regEx = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*#([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;
var emailTest = regEx.test(el.value);
if (!emailTest) {
alert("email not valid");
el.focus();
el.style.backgroundColor = "yellow";
return false;
}
};
if ((el.className.indexOf("numeric") != -1) && (isNaN(el.value))) {
alert(el.value + " is not a number");
el.focus();
el.style.backgroundColor = "pink";
return false;
}
}
}
working fiddle
something alongs the lines of...
//username 5-10 chars
var uVal = document.getElementsByTagName("u").value;
if (uVal.length < 5 || uVal.length > 10) return false;
//email needs # and .
var eVal = document.getElementsByTagName("p").value;
if !(eVal.match('/.*#.*\./g')) return false;
//street starts w/ num
var sVal = document.getElementsByTagName("s").value;
if !(sVal.match('/^[0-9]/g')) return false;
i think the regex is off + untested :)
Here is your javascript validation object in work. Hope you can make some modification according to your need.
Style
<style>
.valid {border: #0C0 solid 1px;}
.invalid {border: #F00 solid 1px;}
</style>
HTML Form
<div>
<form id="ourForm">
<label>First Name</label><input type="text" name="firstname" id="firstname" class="" /><br />
<label>Last Name</label><input type="text" name="lastname" id="lastname" class="" /><br />
<label>Username</label><input type="text" name="username" id="username" class="" /><br />
<label>Email</label><input type="text" name="email" id="email" class="" /><br />
<input type="submit" value="submit" class="" />
</form>
</div>
Call script before closing tag
<script src="form_validation_object.js"></script>
form_validation_object.js
/*
to: dom object
type: type of event
fn: function to run when the event is called
*/
function addEvent(to, type, fn) {
if (document.addEventListener) { // FF/Chrome etc and Latest version of IE9+
to.addEventListener(type, fn, false);
} else if (document.attachEvent) { //Old versions of IE. The attachEvent method has been deprecated and samples have been removed.
to.attachEvent('on' + type, fn);
} else { // IE5
to['on' + type] = fn;
}
}
// Your window load event call
addEvent(window, 'load', function() {
/* form validation object */
var Form = {
validClass: 'valid',
inValidClass: 'invalid',
fname: {
minLength: 1,
maxLength: 8,
fieldName: 'First Name'
},
lname: {
minLength: 1,
maxLength: 12,
fieldName: 'Last Name'
},
username: {
minLength: 5,
maxLength: 10,
fieldName: 'Username'
},
validateLength: function(formElm, type) {
//console.log('string = ' + formElm.value);
//console.log('string length = ' + formElm.value.length);
//console.log('max length=' + type.maxLength);
//console.log(Form.validClass);
if (formElm.value.length > type.maxLength || formElm.value.length < type.minLength) {
//console.log('invalid');
//alert(formElm.className);
if (formElm.className.indexOf(Form.inValidClass) == -1) {
if (formElm.className.indexOf(Form.validClass) != -1) {
formElm.className = formElm.className.replace(Form.validClass, Form.inValidClass);
} else {
formElm.className = Form.inValidClass;
}
}
//alert(formElm.className);
return false;
} else {
//console.log('valid');
//alert(formElm.className.indexOf(Form.validClass));
if (formElm.className.indexOf("\\b" + Form.validClass + "\\b") == -1) { // regex boundary to match whole word only http://www.regular-expressions.info/wordboundaries.html
//formElm.className += ' ' + Form.validClass;
//alert(formElm.className);
if (formElm.className.indexOf(Form.inValidClass) != -1)
formElm.className = formElm.className.replace(Form.inValidClass, Form.validClass);
else
formElm.className = Form.validClass;
}
return true;
}
},
validateEmail: function(formElm) {
var regEx = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*#([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;
var emailTest = regEx.test(formElm.value);
if (emailTest) {
if (formElm.className.indexOf(Form.validClass) == -1) {
formElm.className = Form.validClass;
}
return true;
} else {
formElm.className = Form.inValidClass;
return false;
}
},
getSubmit: function(formID) {
var inputs = document.getElementById(formID).getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == 'submit') {
return inputs[i];
}
}
return false;
}
}
/* call validation object */
var ourForm = document.getElementById('ourForm');
var submit_button = Form.getSubmit('ourForm');
submit_button.disabled = 'disabled';
function checkForm() {
var inputs = ourForm.getElementsByTagName('input');
if (Form.validateLength(inputs[0], Form.fname)) {
if (Form.validateLength(inputs[1], Form.lname)) {
if (Form.validateLength(inputs[2], Form.username)) {
if (Form.validateEmail(inputs[3])) {
submit_button.disabled = false;
return true;
}
}
}
}
submit_button.disabled = 'disabled';
return false;
}
checkForm();
addEvent(ourForm, 'keyup', checkForm);
addEvent(ourForm, 'submit', checkForm);
});
Working example at JSBin
http://jsbin.com/ezujog/1

Categories