Javascript form validation - javascript

I'm trying to figure out what would be the simplest way to validate required fields without having to do an if statement for each element's name. Perhaps just with a loop and verify its class.
What I'm trying to accomplish is to check only the ones that have the class name as "required"
<input name="a1" class="required" type="text" />
<input name="a2" class="" type="text" />
<input name="a3" class="required" type="text" />
Thanks

I'm not at all against the libraries suggested by others, but I thought that you may want some samples of how you could do it on your own, I hope it helps.
This should work:
function validate() {
var inputs = document.getElementsByTagName("input");
for (inputName in inputs) {
if (inputs[inputName].className == 'required' && inputs[inputName].value.length == 0) {
inputs[inputName].focus();
return false;
}
}
return true;
}
Also lets say your inputs are in a form named "theForm":
function validate() {
for (var i = 0; i < theForm.elements.length; i++) {
if (theForm.elements[i].className == "required" && theForm.elements[i].value.length == 0) {
theForm.elements[i].focus();
return false;
}
}
return true;
}
Of course you would trim the value and/or add the appropriate validation logic for the application, but I'm sure you can get the idea from the sample.
You can also store arbitrary data on the input itself and read it using the getAttribute() method on the element. For example you could have this element in your html (regex requires a 3 digit number):
<input name="a1" validate="true" regex="[0-9]{3}" type="text" />
you could use this method to run the regex in the validation routine.
function validate() {
for (var i = 0; i < theForm.elements.length; i++) {
var elem = theForm.elements[i];
if (elem.getAttribute("validate") == "true") {
if (!elem.value.match(elem.getAttribute("regex"))) {
elem.select();
return false;
}
}
}
return true;
}
Hope this helps.

I use the jQuery validation plugin. Works really well and fits your stated desire to only need class attributes.
$(document).ready( function() {
$('form').validate();
});
Is all it takes to set up the validation once you have your required fields marked.

I would recommend you to use this javascript based css selector wich will get all elements of a specific class. Validating the form just like the way you mentioned.

A pattern for this that I have been using for a long time and has served me well is wrapping the control with a DIV, or P and marking that as required.
<div class="form-text required">
<label for="fieldId">Your name</label>
<input type="text" name="fieldName" id="fieldId" value="" />
</div>
This means that I can pick out the required fields to validate easily with a CSS selector.
.required input, .required select
In jQuery, you can test input with something like this:
$('form').submit(function(){
var fields = $(this).find('input, textarea, select'); // get all controls
fields.removeClass('invalid'); // remove
var inv = $(this).find('input[value=""], select[value=""]'); // select controls that have no value
if (inv.length > 0) {
inv.addClass('invalid'); // tag wrapper
return false; // stop form from submitting
}
// else we may submit
});
In plain Javascript it would be more than I care to type out, but along the lines of:
var badfields = [];
var fields = theForm.getElementsByTagName('input');
for (var i=0; i< fields.length; i++ ) {
if ( fields[i] && fields[i].parentNode && fields.value == '' &&
/(^| )required( |$)/.test( fields[i].parentNode.className ) ) {
badfields.push( fields[i] );
}
}
// badfields.length > 0 == form is invalid
The most immediate benefit of wrapping the label and input (and optionally: hint text, error...) as a control "set" in this way is that you can apply CSS styles on the input and label together.
.required input, .required select {
border : 1px solid red;
}
.required label {
color : #800;
}
.invalid input, .invalid select {
background-color : #f88;
}
I recommend using a ready made solution for your form validation as things can quickly add on: How will you validate checkboxes? Can checkboxes be required? (EULA?) What about radio buttons, how will you check those?
Most validation solutions will also provide sugar such as verifying correct data (say, email addresses) rather than just checking if it's there.

I'm a little surprised that no one mentioned YUI.
You can easily use getElementsByClassName method of Dom class in the following manner:
var aElements = YAHOO.util.Dom.getElementsByClassName('required', 'input');
for (var i = 0; i < aElements.length; i++)
{
// Validate
}
More method information is available here and more general info is here

Related

Jquery - How to check if all inputs in a div are not empty?

Looking for a simple way to validate all required inputs, in a certain div.
In other words make sure all required inputs within a certain div are not empty.
This following code which was found here, shows a way to check all inputs and make sure they aren't empty (including inputs with only spaces in them) on a given page.
I am trying to do the same thing. Just within a certain div and for all required inputs.
$("input").filter(function () {
return $.trim($(this).val()).length == 0
}).length == 0;
You could do the same thing, but you should change the selector to target just the input's inside a given div and add [required] selector to select just those who have required attribute :
$("div_selector input[required]").filter(function () {
return $.trim($(this).val()).length == 0
}).length == 0;
Hope this helps.
$('button').on('click',function(){
var result = $("#div_selector input[required]").filter(function () {
return $.trim($(this).val()).length == 0
}).length == 0;
console.log(result);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name='first' required> Required input out of the div
<div id='div_selector'>
<input name='second' required> Required input
<br>
<input name='Third'>
<br>
<input name='Fourth' required> Required input
</div>
<br>
<button>Check</button>
Here's a simple one-liner using Array.reduce():
$(".your-div input").reduce((allFilled, input) =>
allFilled && $.trim($(input).val()) !== "", true)
This approach will match any input be it input, select, textarea etc
var canSubmit = true;
$.each($('.div-in-question').find(':input'), function(element, index){
canSubmit = canSubmit && ($(element).val() !== '');
});
// at this point canSubmit will be true or false and you can act upon it

Javascript select all HTML input fields with array style name

I have a form that I am building and would like to have a javascript to select and manipulate all of the fields that are within the named array:
<input type="text" name="location[street]" value required />
<input type="text" name="location[city]" value required />
<input type="text" name="location[zip]" value required />
<input type="text" name="location[state]" value required />
How can I build a selector for javascript to toggle all of the elements disabled state?
Jquery is possible but not preferred. I would prefer a method that would work without libraries - such as document.getElementsByName().
I believe that querySelectorAll doesn't have support for a selector to get an element by an attribute, like jQuery would be input[name^="location"](docs). So, try this:
var els = document.querySelectorAll('input');
for (var i = 0; i < els.length; i++)
{
if (els[i].name.indexOf("location") > -1)
{
els[i].disabled = true;
}
}
Fiddle. I will be glad to hear that I'm wrong and there is a way for doing this only using a selector.
Anyway, you can use the fieldset and make your code more semantic by disabling only the fieldset, if you like: Fiddle.
UPDATE
In order to disable all textarea and select elements as well, just include those tags on the selector:
var els = document.querySelectorAll('input, textarea, select');
Fiddle
Alternative to queryselector would be getElementsByTagName
var i;
var inputs = document.getElementsByTagName("input");
for (i = 0; i < inputs.length; ++i) {
var name = inputs[i].getAttribute("name");
if(name.indexOf("location") > -1)
{
inputs[i].disabled = true;
console.log(name);
}
}
link to JSFIddle

Javascript/jQuery: Get specific elements from form

I have an extense form with around 25 inputs (text, radio and checkboxes). I want that when I click the button that opens the jQuery dialog, loads the form and set all fields except 5 of them disabled. Seems so easy, but I want that into a "generic" function. I mean, that I have this method:
function disableInputs(jQueryElement, exceptions, booleanClean) {
//Some stuff
}
I want to get all the inputs from the jQueryElement, but ignoring all the elements with the ids that have exceptions. Exceptions is an Object like this one:
var exceptions = {
0: 'clientId',
1: 'clientName',
2: 'clientFirstSurname',
3: 'clientSecondSurname',
4: 'clientAlias'
}
This is my full code and what I've tested, but this is the only way to make it work and, if I have recieved the third parameter (booleanClean), It will set value='' to all inputs, instead to the elements that weren't excluded from being disabled. That boolean works to check if you want to clean inputs when this function is called:
function disableInputs(jQueryElement, exceptions, booleanClean) {
var inputs = jQueryElement.find('input');
for (var i = 0; i < inputs.length; i++) {
inputs[i].setAttribute('disabled', true);
for (var attr in exceptions) {
if (inputs[i].getAttribute('id') === exceptions[attr]) {
inputs[i].removeAttribute('disabled');
} else {
if (booleanClean === true) {
inputs[i].value = null;
}
}
}
}
}
I know why is not working the clean "option". What I want is where I have to put that to do it properly or if I can set a condition when I get the inputs to get only the inputs that are not excluded (preferible second option for optimization and not set an attribute to each input and remove them if are excluded. Seems much easier to work).
I'd suggest changing the exceptions object to be a conventional array:
var exceptions = ['clientId',
'clientName',
'clientFirstSurname',
'clientSecondSurname',
'clientAlias'];
...because then you can simplify your function a lot:
function disableInputs(jQueryElement, exceptions, booleanClean) {
var inputs = jQueryElement.find('input');
if (exceptions.length > 0) {
exceptions = "#" + exceptions.join(",#");
inputs = inputs.not(exceptions);
}
inputs.prop("disabled",true);
if (booleanClean)
inputs.val("");
}
I'm a bit confused about whether you want to clean all inputs or just the ones not on the exceptions list. My code above just cleans those not on the list. To clean them all move that if(booleanClean) inputs.val(""); to before the other if statement.
Try
function disableInputs(jQueryElement, exceptions, booleanClean) {
var not = jQuery.map(exceptions, function(item, index){
return '#' + item;
}).join(',')
var inputs = jQueryElement.find(':input').not(not).prop('disabled', true);
if(booleanClean){
inputs.val('')
}
}
Are you able to give a class name to the items that are exceptions? That's what I would do.
<input class="exception" />
$( "input:not(.exception)" ).prop("disabled", true);
Try this one:
HTML
<form>
<input type="text" name="input1" value="val1" />
<input type="text" name="input2" value="val2" />
<input type="text" name="input3" value="val3" />
</form>
JS
function disableInputs(jQueryElement, exceptions, booleanClean) {
jQueryElement.find('input').not( exceptions.join(', ') ).each(function(){
if( booleanClean ){
$(this).val('');
}
$(this).prop('disabled', true);
});
}
var exceptions = ['input[name=input1]', 'input[name=input3]'];
disableInputs( $('form'), exceptions, true );
Here is working sample: http://jsfiddle.net/4Dwwk/

validate a dynamicnumber of checkboxes using javascript

I have some ASP code which presents any where from 1-any number of checkboxes (which are named the same) on the page. This validation does work however I think its a bit weak:
if (document.getElementById('selectedDocs').checked)
{
//this is here to handle the situation where there is only one checkbox being displayed
}
else
{
var checked = false;
var field = myForm.selectedDocs;
for(var j = 0; j < field.length; j++)
{
if(field[j].checked == true)
{
checked = true;
break;
}
}
if(!checked)
{
alert("You have not ticked any options. At least one must be selected to proceed!")
return false;
}
}
I was working with the code in the else block but this only works when there is more than one checkbox. It ignores the fact I have ticked the one single option when there is only one. So I placed the code inside the if section......Although it woks its a bit of a hack, can someone kindly improve it for me?
Thanking you...
Use:
var field = myForm.getElementsByName('selectedDocs');
This always returns a NodeList that you can iterate over.
If they are in a form and all have the same name, they can be accessed as a collection that is a property of the form. So given:
<form id="f0" ...>
<input type="checkbox" name="cb0" ...>
<input type="checkbox" name="cb0" ...>
<input type="checkbox" name="cb0" ...>
...
</form>
All the following return a reference to the form:
var form = document.getElementById('f0');
var form = document.forms['f0'];
var form = document.forms[0]; // if first form in document
and and all the following return a collection of the checkboxes named "cb0":
var checkboxes = form.cb0
var checkboxes = form['cb0'];
var checkboxes = form.elements.['cb0'];

Clearing Input Fields with JavaScript

I've been looking at this for the last few hours, and can't really achieve what I'm looking for. I currently have the following two inputs:
<input type="text" id="username" value="USERNAME" onfocus="inputFocused(this)" onblur="inputBlurred(this)" />
<input type="password" id="password" value="PASSWORD" onfocus="inputFocused(this)" onblur="inputBlurred(this)" />
Initially, the inputs text is grey, and I have the following JavaScript functions onfocus and onblur:
var defaultInput = "";
function inputFocused(obj){
defaultInput = obj.value;
obj.value = "";
obj.style.color = "#000";
}
function inputBlurred(obj){
if(obj.value == ""){
obj.style.color = "#AAA";
obj.value = defaultInput;
}
}
I'm trying to devise a way so that once I start typing into a field, leave the field, then return, it will not clear the input again (since it will then contain something the user typed in it). I've thought of achieving this with some kind of variable that I can alternate between 1 and 0 depending on the state, but that seemed sloppy. Any insight for this JS novice is greatly appreciated.
In inputFocused, you are clearing the input field's value regardless of any state. Maybe I am misunderstanding your intention, but why would you ditch the value when focusing the control?
Updated: Adding a 'defaultTextValue' attribute to each element allows you to capture the input's default value on the first focus event. The alternative is to use your document's onLoad event to capture the default values. The snippet below clears the textboxes when they are focused and their value is the same as the default values they were initialized with. You might annoy users that have either a username of 'username' or a password of 'password', but you probably should anyways 8-)
function inputFocused(obj) {
if (obj.defaultTextValue == undefined || obj.value == obj.defaultTextValue) {
obj.defaultTextValue = obj.value;
obj.value = "";
}
}
function inputBlurred(obj) {
if (obj.value == "" && obj.defaultTextValue != undefined) {
obj.value = obj.defaultTextValue;
}
}
Adding to jscharf's code, you can use the title attribute of the input field to store the default value of each input. This has the usability advantage of letting people know what the input field should contain when they hover over it:
<input type="text" id="username" value="USERNAME" title="USERNAME" onfocus="inputFocused(this)" onblur="inputBlurred(this)" />
<input type="password" id="password" value="PASSWORD" title="PASSWORD" onfocus="inputFocused(this)" onblur="inputBlurred(this)" />
And in the js:
function inputFocused(obj){
if(obj.title != obj.value){
obj.value = '';
obj.style.color = '#000';
}
}
function inputBlurred(obj){
if(obj.value == '' || obj.title == obj.value){
obj.value = obj.title;
obj.style.color = '#AAA';
}
}
Also, not sure if you've considered doing it, but you can control the focus colour of the input in CSS if you want (doesn't work in IE6 of course... but you can override in an IE6 only stylesheet):
input {
color: #AAA;
}
input:focus {
color: #000;
}
You can add any customized attributes to your HTML page's DOM as you like, gives you a lot of flexibility.
You could do a check to see if the value in the field currently is the initial value.

Categories

Resources