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>.
Related
I'm having an issue with my validation process. I'm not using a standard "submit" button, rather I have <span class="button" id="print">Print</span> and jQuery listens for a click. This is the validation code I have when that "button" is clicked:
var validation = "";
function validate() {
$("#servDetails").find("input").each(function () {
if ($(this).prop("required") && $(this).val() == "") {
validation = false;
}
else {
validation = true;
}
});
$("#checklist").find("input[required]").each(function () {
if ($(this).prop("required") && $(this).val() == "") {
validation = false;
}
else {
validation = true;
}
});
}
$("#print").on("click", function() {
validate();
if (validation == false) {
alert("Please fill out all required inputs!");
return false;
}
else {
window.print();
}
});
If I click the button without filling anything out (all items blank), I get my alert as expected.
If I fill out all of the required elements, it pulls up the print dialouge as expected.
However, if I leave some of the boxes blank while others are correctly filled, it still goes to print instead of giving me the alert like I need. Any thoughts?
The code have to be rewritten, or better replace it with any validation plug-in.
But in your case, I suppose, you just forgot to return, in case you found some not filled field. So if you have any filled input it override your validation variable.
The simplest solution is to remove
else {validation = true;} code blocks, and add
validation = true;
at the beggining of the function.
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...
Im currently trying to do a form that requires the user to enter valid information.
For instance Here's a classic form: jsfiddle
I want the user to put name and address. But I want the button to be unclickable until the user inputs his Name and his Email(in a correct form).
Is there any property that lets me access if a button is unclickable? Something like:
function validateButtonSubmit {
if (validateEmail(email)) {
if (validateName(name)) {
document.getElementById("submitButton").clickable = true;
}
}
}
Whats the best way to accomplish this, am I going in the right direction?
You could probably shorten this up without the nesting if you wanted:
function validateButtonSubmit() {
var btnSubmit = document.getElementById("submitButton");
btnSubmit.disabled = !(validateEmail(email) && validateName(name));
}
Use disabled:
document.getElementById("submitButton").disabled = true;
You could call removeAttribute() on the element and then call setAttribute after you've validated the form:
var button = document.getElementById('submitButton');
button.removeAttribute('click');
// validation stuff
button.setAttribute('click', submitForm());
I am still confused about this. Started learning JQuery about a week now and this is what I have:
var IsValidUserName = false;
$(document).ready(function () {
$('#txtUserName').blur(function () {
if ($('#txtUserName').val().match(isNumberLetter) &&
($('#txtUserName').val().length >= 8)) {
$('#userNameError').removeClass("error").addClass("default");
$('#txtUserName').removeClass("alert");
$('#txtUserName + label').removeAttr("id", "lblUserName");
IsValidUserName = true;
}
else {
$('#userNameError').removeClass("default").addClass("error");
$('#txtUserName').addClass("alert");
$('#txtUserName + label').attr("id", "lblUserName");
}
});
});
Lets say I have another function like above, lets say FirstName:
How do I call this on the submit event? The code works as I need it to when the user leaves a field. Not sure how I can also call this code and also use the variable above to prevent submit if the data entered is invalid.
I need to call the validation above if the user clicks the submit button and stop the submission if the IsValidUserName variable is false.
Somethings just need a little push.
Thanks my friends.
Guy
You could always extract it into a function instead of an anonymous function and pass the reference to the object you want to check. This would give you the added benefit of reusing it for other elements.
function validate(ele) {
var valid;
if (ele.val().match(isNumberLetter)) && (ele.val().length >= 8)) {
valid = true;
// update user here.
} else {
valid = false;
// update user here.
}
return valid;
}
$(function(){
$('#firstName').blur(function(){ validate($(this)); });
$('#lastName').blur(function(){ validate($(this)); });
$("yourFrom").submit(function(){
var firstNameIsValid = validate($('#firstName'));
var lastNameIsValid = validate($('#lastName'));
if (!nameIsValid) && (!lastNameIsValid) {
return false;
// User has already been updated
}
});
});
Also, since you are already heavily using javascript for your validation (hope this is convenience and not the only security), you can also disable the submit button entirely until the form meets the proper requirements.
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();
}
});
);