jQuery validation without "form" tag - javascript

According to http://docs.jquery.com/Plugins/Validation the "form" tag is necessary in order to do validation. In my case I don't have form tag. How can I validate(required field) my textbox on click of "button" type control

Why not just add a form tag? If it's an input, then it should normally be part of a form.

You could always wrap it with a fake form and validate it.
var $textbox = $("#textbox");
$("<form>").append($textbox).validate();
Note, however, that in most cases this should imply that we're going about something wrongly, and I'd consider a form for every element that's submitted in any form (whether it's through standard GET/POST, AJAX, etc.).

I know, it is quite old question, anyway, I had almost the same problem: I had defined form:
<form id="some-form-id"></form>
And than in document I had inputs like this:
<input type="text" form="some-form-id" />
jQuery validator cannot validate this, because elements weren't within the form, so I made small update:
There is method elements which load elements to validate and I edit it into version bellow this text. I add loading items which are not inside form, which I load into variable outForm. This items are loaded only if form has attribute id. I test it and it works. I hope that this will help to someone.
elements: function () {
var validator = this,
rulesCache = {};
// select all valid inputs inside the form (no submit or reset buttons)
var inForm = $(this.currentForm)
.find("input, select, textarea")
.not(":submit, :reset, :image, [disabled], [readonly]")
.not(this.settings.ignore)
.filter(function () {
if (!this.name && validator.settings.debug && window.console) {
console.error("%o has no name assigned", this);
}
// select only the first element for each name, and only those with rules specified
if (this.name in rulesCache || !validator.objectLength($(this).rules())) {
return false;
}
rulesCache[this.name] = true;
return true;
});
var formId = $(this.currentForm).attr('id');
if(typeof formId == 'undefined')
return inForm;
var outForm = $("input[form='"+formId+"'], select[form='"+formId+"'], textarea[form='"+formId+"']")
.not(":submit, :reset, :image, [disabled], [readonly]")
.not(this.settings.ignore)
.filter(function () {
if (!this.name && validator.settings.debug && window.console) {
console.error("%o has no name assigned", this);
}
// select only the first element for each name, and only those with rules specified
if (this.name in rulesCache || !validator.objectLength($(this).rules())) {
return false;
}
rulesCache[this.name] = true;
return true;
});
return $.merge(inForm,outForm);
},

Related

javascript validating the whole form

Friends i am new to javascript, I am trying to write a script to validate the entire form whenever any input field value is changed of input fiels with the data attribute of required.
HTML
<form>
<input type="text" name="FirstName" class="inputField" data-required="true"></input>
<input type="text" name="MiddleName" class="inputField"></input>
<input type="text" name="LastName" class="inputField" data-required="true"></input>
</form>
SCRIPT
var field, required, isValid, fieldVal;
function validatedForm() {
field = document.querySelectorAll('.inputField');
document.getElementById("submitButton").disabled = true;
var isValid = true;
for(var i=0; i < field.length; i++){
required = field[i].dataset.required;
if(required){
field[i].addEventListener('blur', function(e){
fieldVal = this.value;
if(fieldVal == ''){
isValid = false;
}
checkSubmitBtn();
}, true);
}
}
function checkSubmitBtn() {
if(isValid = true) {
console.log(isValid);
document.getElementById("submitButton").disabled = false;
}
}
}
window.addEventListener("load", validatedForm);
PROBLEM 1:
The isValid is not updating hence even an empty blur on the input field makes the button disable to be false.
PROBLEM 2:
In case there are multiple forms on the page then how to validate only the desired forms .. just like in jQuery we add a script tag in the end to initialize the script according to it.
PROBLEM 3:
Is there a way to change the disable state of the button without the GetElementID ... I mean if that can be managed depending on the submit button of that particular form on the page where the script is suppose to work.
Any help will be highly appreciated. Thanks in advance.
I think you need something like the following form validation..
<script type="text/javascript">
var field, fieldVal, required = false;
function validatedForm() {
field = document.querySelectorAll('.inputField');
document.getElementById("submitButton").disabled = true;
field.forEach(function(elem) {
required = elem.dataset.required;
if(required){
elem.addEventListener('blur', function(e) {
checkSubmitBtn(field);
});
}
});
}
function checkSubmitBtn(field) {
var isDisabled = false;
field.forEach(function(elem) {
fieldVal = elem.value.trim();
if(fieldVal == ''){
isDisabled = true;
return false;
}
});
document.getElementById("submitButton").disabled = isDisabled;
}
window.addEventListener("load", validatedForm);
</script>
I hope it helps...
There are quite a few things going on here. First, your checkSubmitBtn function used a single = operator in the if statement. This won't actually check the variable, it instead will set the variable to that value. Here is the fixed function:
function checkSubmitBtn() {
if (isValid == true) {
document.getElementById("submitButton").disabled = false;
}
}
You mentioned not wanting to use getElementById. There are a few ways around this. One way would be to call the function once and store it in a variable to use later, like so:
var button = document.getElementById("submitButton");
...
function checkSubmitBtn() {
button.disabled = !isValid;
}
Another way would be to use jQuery. It still is technically calling getElementById in the backend, but the code is much simpler. If you wanted to avoid that, you also can still combine this with the technique I described above.
$("#submitButton").attr("disabled", !isValid);
I'd also like to point out that your code doesn't account for a situation where a form goes from invalid (starting point) to valid and back to invalid again. Say a user types in all of the fields but then backspaces everything. Your code will fall apart.
Lastly, your <input> HTML tags should not be closed. There are certain tags that are considered "self-closing", i.e. you don't have to write the closing tag, </input>.

JQuery MultiPage form.. validation on each step

I have a form which is split up into sections using pagination on each tag. (See Fiddle)
I however have required fields in each section, I'd like to validate it so that fields with the "required" attribute must not be blank before the user moves on to the next section.
http://jsfiddle.net/Azxjt/
I've tried to following but don't think I'm on the right tracks:
$(this).closest("article > :input").each(function() {
if($(this).val == null) {
con = 0;
}
});
if ( con == 0 ) {
alert("All fields must be filled in");
}
else {
}
Your help is appreciated :)
Text input will return a black value if no response has been entered. Try the following
In jQuery, the value is returned by val()
$(this).val() == ""
You could possibly enhance your jQuery selector to test only those input elements with a corresponding required label.
Use each function.
var isEmpty;
$("input").each(function() {
var element = $(this);
if (element.val() == "") {
isEmpty= true;
}
});

Form validation - How to keep track of multiple fields to prevent submit - Global variable?

I have a form with multiple fields (lets say 4 for this example).
I am using javascript functions on each field to validate them, generating an error indication - a red box, or a hint as text next to the box.
like so ..
<input
...
onkeyup="validateName()"
onblur="checkDuplicateName(); validateName()"
>
So what I would like to do is not allow a submit if any of the fields do not validate.
So the question is - what is the best way to set it up so submit is disabled unless all 4 fields are valid?
I will use either
document.getElementById("mySubmit").disabled=true;
or
event.preventDefault()
(..though trying to avoid Jquery) to prevent the submit.
How should I keep track of the condition of the 4 fields?
Should I create a global variable like - window.validFields, so I can access it from each of my validation functions - adding one to the variable for each field that is valid, and subtracting one when invalid? (window.validFields==4 allows a submit)
Not sure the best way to accomplish this.
Any help would be appreciated, thanks.
Assuming a form like this …
<form class="is-invalid" id="form" method="post">
<input type="text" id="lorem">
<input type="text" id="ipsum">
<input type="text" id="dolor">
<input type="text" id="amet">
<button id="submit">Submit</button>
</form>
… you could do the following …
(function () {
var fields = {
lorem: false,
ipsum: false,
dolor: false,
amet: false
},
isValid = false,
form = document.getElementById('form'),
i,
tmpInput;
// Binding submit-event to prevent form-submit
form.addEventListener('submit', onSubmit, false);
// Binding events on input-elements (keyup & blur)
for ( i in fields ) {
tmpInput = document.getElementById(i);
tmpInput.addEventListener('keyup', checkInput, false);
tmpInput.addEventListener('blur', checkInput, false);
}
// Checking form state by iterating over the fields object;
// Adding/removing 'is-valid'-class and setting `isValid`-flag
function checkFormState() {
for ( var j in fields ) {
if ( !fields[j] ) {
isValid = false;
form.className += /\bis-invalid\b/i.test(form.className)
? ''
: 'is-invalid';
return;
}
}
form.className = form.className.replace(/\bis-invalid\b/i, '');
isValid = true;
}
// Abort the submit, if the `isValid`-flag is `false`
function onSubmit(evnt) {
if ( !isValid ) {
evnt.preventDefault();
return false;
}
}
// Setting the corresponding value in the `fields`-object;
// Checking the form state
function checkInput() {
fields[this.id] = this.value.length > 5; // or any other validation rule
checkFormState();
}
})();
There's an object with the IDs of the relevant input-fields that holds each validation state. On keyup and blur each input field is checked. If it passes the validation, the corresponding value in the fields-object is set to true. Additionally the state of the form is checked on each event on an input element.
The checkState-function iterates over the fields-object. If it finds a property, that is false, the 'is-invalid'-class is set on the form-element (if it isn't already set), the isValid-flag is set to false and the function is aborted.
Otherwise — all input-fields are valid —, the isValid-flag is set to true and the 'is-invalid'-class is removed from the form-element. Now, the form can be submitted.
This all works without a single global variable. Mission accomplished!
I made a Fiddle where you can test this.
PS: Have in mind, that the addEventListener-method is only supported by IEs down to version 9. If you have to support version 8 and below, you need a workaround like this.
I hope this helps you.
You can use the forms submit event, like this:
HTML:
<form method="post" onsubmit="return MyValidation(); " ...
JS:
(function() {
var field1Valid = false;
var field2Valid = false;
window.validateField1 = function(elmnt) {
// do some validation...
if(everything == OK) {
field1Valid = true;
setButtonDisabled(false);
}
else {
field1Valid = false;
setButtonDisabled(true);
}
}
window.validateField2 = function(elmnt) {
// do some validation...
if(everything == OK) {
field2Valid = true;
setButtonDisabled(false);
}
else {
field2Valid = false;
setButtonDisabled(true);
}
}
window.checkDuplicateName = function() {
// do some more validation...
}
window.setButtonDisabled = function(disabled) {
document.getElementById('submit').disabled = disabled;
}
window.MyValidation = function() {
return field1Valid && field2Valid;
}
}());
The above example also checks whether to disable the submit button or not.
Another way would be to handle all your validation logic within the form submit event, but validating input immediately is always nicer.
There are also quite some validation plugins available for use with jQuery, if you're interested. Building this yourself can get messy quickly if you have multiple fields that need to be validated in multiple ways...

jquery check values in form

I have two inputs where I am checking to make sure that they are not empty before the form submits.
My issue is that it only validates #from_date. Is the issue that .val will only check the last id in the list?
$('#submitDates').click(function () {
// Get the fields you want to validate
var name = $("#to_date, #from_date");
// Check if field is empty or not
if (name.val()=='') {
alert ('Please Select Dates')
return false;
} ;
});
});
Any specific reason you're hooking on .click and not .submit?
You can iterate through the selected elements and check for a violating element using .each
var found = false;
$("#to_date, #from_date").each(function(i,name){
// Check if field is empty or not
if (!found && $(name).val()=='') {
alert ('Please Select Dates')
found = true;
} ;
});
return !found;
In your example var name = $("#to_date, #from_date"); is giving you a collection of two inputs and by doing if (name.val()=='') jQuery is checking only the first element in the collection, so it's not working. You may try this
$('#submitDates').click(function () {
var name = $("#to_date, #from_date");
if ( name[0].value == '' || name[1].value == '' ) {
alert ('Please Select Dates');
return false;
}
});
In the above example name[0].value refers to the first element and name[1].value refers to the second element. If you want to use jQuery's val() method then you can use it like $(name[0]).val() and $(name[1]).val().
Also you should consider to use submit event of the form instead of button's click event.

Onsubmit validate change background requried fields?

Anyone know of a good tutorial/method of using Javascript to, onSubmit, change the background color of all empty fields with class="required" ?
Something like this should do the trick, but it's difficult to know exactly what you're looking for without you posting more details:
document.getElementById("myForm").onsubmit = function() {
var fields = this.getElementsByClassName("required"),
sendForm = true;
for(var i = 0; i < fields.length; i++) {
if(!fields[i].value) {
fields[i].style.backgroundColor = "#ff0000";
sendForm = false;
}
else {
//Else block added due to comments about returning colour to normal
fields[i].style.backgroundColor = "#fff";
}
}
if(!sendForm) {
return false;
}
}
This attaches a listener to the onsubmit event of the form with id "myForm". It then gets all elements within that form with a class of "required" (note that getElementsByClassName is not supported in older versions of IE, so you may want to look into alternatives there), loops through that collection, checks the value of each, and changes the background colour if it finds any empty ones. If there are any empty ones, it prevents the form from being submitted.
Here's a working example.
Perhaps something like this:
$(document).ready(function () {
$('form').submit(function () {
$('input, textarea, select', this).foreach(function () {
if ($(this).val() == '') {
$(this).addClass('required');
}
});
});
});
I quickly became a fan of jQuery. The documentation is amazing.
http://docs.jquery.com/Downloading_jQuery
if You decide to give the library a try, then here is your code:
//on DOM ready event
$(document).ready(
// register a 'submit' event for your form
$("#formId").submit(function(event){
// clear the required fields if this is the second time the user is submitting the form
$('.required', this).removeClass("required");
// snag every field of type 'input'.
// filter them, keeping inputs with a '' value
// add the class 'required' to the blank inputs.
$('input', this).filter( function( index ){
var keepMe = false;
if(this.val() == ''){
keepMe = true;
}
return keepMe;
}).addClass("required");
if($(".required", this).length > 0){
event.preventDefault();
}
});
);

Categories