I have a Form which has 2 fields to validate, Radio buttons and Textarea.
The rules for validation are
At least 1 radio must be checked
The textarea should not be empty.
Here is the DEMO of my code.
The issue is that the visibility of "Radio" buttons are conditional and they might be hidden in some scenario.
So. currently if the Radio buttons are hidden I'm not able to submit the <form>.
Should I do the Form validation twice as shown below? Or is there a better and shorter way of doing this validation?
if (Radio is : visible){
Here goes the validation for both form fields
} else{
Do the Validation again only for Textarea
}
Following is my code:
HTML
<input class="redButton" id="openDialogButton" type="button" value="Open Dialog">
<div id="sessionReason" title="End Transaction">
<p class="validation-summary-errors marginBottom10">Provide the following information to proceed:</p>
<div class="marginBottom" id="sessionDocumentMessage">
<label class="marginBottom5 marginTop10">Return the document?</label>
<br>
<label>
<input type="radio" name="sessionDocuments" />Return</label>
<br>
<label>
<input type="radio" name="sessionDocuments" />Keep</label>
<br>
</div>
<p class="marginBottom5" id="sessionReasonMessage">Reason for ending the transaction:</p>
<textarea id="sessionReasonBox" class="reasonBox"></textarea>
</div>
JQuery
function showValidationError() {
$('#sessionReason .validation-summary-errors').show();
}
function hideValidationError() {
$('#sessionReason .validation-summary-errors').hide();
}
function addRadioError() {
$("#sessionDocumentMessage label").addClass("redtext");
}
function removeRadioError() {
$("#sessionDocumentMessage label").removeClass("redtext");
}
function addReasonBoxError() {
$("#sessionReasonMessage").addClass("redtext");
}
function removeReasonBoxError() {
$("#sessionReasonMessage").removeClass("redtext");
}
$('#sessionReason .validation-summary-errors').hide();
$("#sessionReason").dialog({
autoOpen: false,
buttons: {
"Submit": function () {
var enteredReason = $('#sessionReasonBox').val();
var radioChecked = $("#sessionReason input:radio[name='sessionDocuments']:checked");
if ((enteredReason.length <= 0) && (radioChecked.length == 0)) {
//Show Error
showValidationError();
addReasonBoxError();
addRadioError();
//Hide Validation Error
} else if ((enteredReason.length > 0) && (radioChecked.length == 0)) {
//Show Validation Error
showValidationError();
addRadioError();
//Hide Validation Error
removeReasonBoxError();
} else if ((enteredReason.length <= 0) && (radioChecked.length > 0)) {
//Show Validation Error
showValidationError();
addReasonBoxError();
//Hide Validation Error
removeRadioError();
} else {
$(this).dialog("close");
//Hide Validation Error
hideValidationError();
removeRadioError();
removeReasonBoxError();
}
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
$("#openDialogButton").click(function () {
$('#sessionReasonBox').val("");
$('#sessionDocumentMessage input:radio').removeAttr('checked');
$("#sessionReason").dialog("open");
//Hide Validation Error
hideValidationError();
removeRadioError();
removeReasonBoxError();
});
Let me know if you need any other information.
Please suggest.
Try something like the following, this should give you an idea.
"Submit": function () {
var enteredReason = $('#sessionReasonBox').val();
var radioVisible = $("#sessionReason input:radio[name='sessionDocuments']:visible");
var radioChecked = $("#sessionReason input:radio[name='sessionDocuments']:checked");
var validationError = false;
if(enteredReason.length <= 0) {
validationError = true; // validation failure
addReasonBoxError(); //add validation error for textarea
}
else
removeReasonBoxError(); //remove validation error for textarea
if(radioVisible.length){
if (radioChecked.length == 0) {
validationError = true; // validation failure
addRadioError(); //add validation error for radio
}
else
removeRadioError(); //remove validation error for radio
}
if(validationError)
showValidationError(); //add validation error
else
hideValidationError() //remove validation error
}
Yes, you can check the css-property.
if (!($('button').css('display') === "hidden"))
The css-function, if given a single argument, just returns the value rather than setting it. Also, you would of course have to refine the selector to select the correct button.
Read more: http://api.jquery.com/css/
Related
Im still fairly new to JS and would like to be able to remove the event listener that stops the form submitting. I have tried multiple different solutions to do it in JS rather than jquery with no luck. The form currently does not submit, but i cannot get it to reverse should my 'if' conditions be false.
var element = document.querySelector('form');
element.addEventListener('submit', event => {
event.preventDefault();
});
function validateForm() {
var error = "";
if (document.getElementById("name").value == "") {
error += "<p>Name field required</p>"
}
if (document.getElementById("email").value == "") {
error += "<p>Email field required</p>"
}
if (document.getElementById("subject").value == "") {
error += "<p>Subject field required</p>"
}
if (document.getElementById("question").value == "") {
error += "<p>Question field required</p>"
}
if (error != "") {
document.getElementById("errorDiv").style.display = "block";
document.getElementById("errorDiv").innerHTML = "<b>There wer error(s) in the form, please complete all required fields</b>" + error;
} else {
var element = document.querySelector('form');
element.removeEventListener('submit', event => {
event.preventDefault();
});
}
}
<div id="errorDiv"></div>
<form id="contact_form" onsubmit="validateForm();">
<button type="submit"></button>
Thanks in advance if anybody can help.
I think you should return true/false from your validateForm() function to prevent/submit the form.
1. You have to return value from the function in the html markup:
<form id="contact_form" onsubmit="return validateForm();">
2. Return true/false from your validateForm() based on validation.
function validateForm() {
var error = "";
................
................
................
if (error != "") {
document.getElementById("errorDiv").style.display = "block";
document.getElementById("errorDiv").innerHTML = "<b>There wer error(s) in the form, please complete all required fields</b>" + error;
return false;
} else {
return true;
}
}
Does not required to prevent form submit so remove this code.
var element = document.querySelector('form');
element.addEventListener('submit', event => {
event.preventDefault();
});
I'm building a tabbed for using a mixture of JavaScript and CSS. So far I have validation on my text inputs that ensure a user can't progress unless data has been input.
I have got it working so that my script detected unchecked radios, but the problem is that I want the user to only select one. At the moment even when one gets selected the script won't let you progress because it's seeing the other three as unchecked. How could I add a rule to look at the radios and set valid = true if one is selected - if more or less than 1 then fail?
my function:
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
// If a field is empty...
if (y[i].type === "text") {
if (y[i].value == "") {
// add an "invalid" class to the field:
y[i].classList.add('invalid');
// and set the current valid status to false:
valid = false;
} else if (!y[i].value == "") {
y[i].classList.remove('invalid');
valid = true;
}
}
if (y[i].type === 'radio') {
//y[i].classList.remove('invalid');
//valid = true;
if (!y[i].checked) {
y[i].classList.add('invalid');
valid = false;
} else {
y[i].classList.remove('invalid');
valid = true;
}
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
Do I need to split the validation down into further functions to separate validating different field types?
I think that radio buttons are the way to go. Especially from a UI point of view. Why would you let the user pick more than one item only to tell them later they can't?
Having said that, you can do what you're trying to do with something like this:
function validateForm() {
var checkBoxHolders = document.querySelectorAll(".checkboxholder");
var valid = true;
for (var i = 0; i < checkBoxHolders.length; i++) {
var numChecked = checkBoxHolders[i].querySelectorAll("input[type='checkbox']:checked").length;
if (numChecked === 1) {
checkBoxHolders[i].classList.remove('invalid');
} else {
checkBoxHolders[i].classList.add('invalid');
}
valid = valid && numChecked === 1;
}
document.getElementById('valid').innerHTML = 'I am valid: ' + valid;
}
.invalid {
background-color: orange;
}
<input type="text" id='foo'>
<input type="text" id='bar'>
<div class='checkboxholder'>
First group
<input type="checkbox" id='check1'>
<input type="checkbox" id='check2'>
</div>
<div class='checkboxholder'>
Second group
<input type="checkbox" id='check3'>
<input type="checkbox" id='check4'>
</div>
<button type='button' onclick='validateForm()'>Validate me</button>
<div id='valid'>
</div>
With jQuery, it'd be something like:
if (jQuery('input[name=RadiosGroupName]:checked').length === 0) {
valid = false;
}
When i post form only the title validation is working, the other two fields are not validated.
HTML
<form name="qaform" class="nice" method="POST" onsubmit="validateForm()" action="/ask/ask-question/">
<input type="hidden" id="id_selected_tags" name="tags">
<p>
<label for="id_title" class="inline-block">Title</label>
<input type="text" class="input-text inline-block" id="id_title" name="question_title">
</p>
<span id="error_title"></span>
<textarea id="id_question" name="question_description" class="full-width"></textarea>
<span id="error_body"></span>
<p>
<label for="id_tags" class="inline-block">Tags</label>
<input type="text" id="id_newstagbox" name="question_tags"/>
</p>
<span id="error_tags"></span>
<button class="btn btn-success" type="submit">Post your question</button>
</form>
JS
function validateForm()
{
//title validation
if (document.qaform.question_title.value == "") {
document.getElementById('error_title').innerHTML="*Please add a title*";
return false;
}
//body validation
if (document.qaform.question_description.value == "") {
document.getElementById('error_body').innerHTML="*Please add a description*";
return false;
}
//tag validation
if (document.qaform.question_tags.value == "") {
document.getElementById('error_tags').innerHTML="*Please add a description*";
return false;
}
}
After submitting the forms post successfully if title is present.
The stackoverflow form validation forced me to do this, its constantly saying me to add more text because my question contains mostly code.I know its good to provide more information about question but there are times when you can ask a question in few words without being too broad and then you have to rant about it to pass the FORM VALIDATION.
Just remove return false.modify it like below
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
var y=document.forms["myForm"]["farea"].value;
var z=document.forms["myForm"]["ftag"].value;
if (x==null || x=="")
{
document.getElementById('ern').innerHTML="*Please add a title*";
}
if (y==null || y=="")
{
document.getElementById('era').innerHTML="*Please add a desxription*";
}
if (z==null || z=="")
{
document.getElementById('ert').innerHTML="*Please add a tag*";
}
}
</script>
I prefer using jQuery:
$('#form').submit(function(e) {
var validated = true;
e.preventDefault();
//title validation
if ($('#id_title').val() == "") {
$('#error_title').html("*Please add a title*");
validated = false;
}
//body validation
if ($('#id_question').val() == "") {
$('#error_body').html("*Please add a description*");
validated = false;
}
//tag validation
if ($('#id_newstagbox').val() == "") {
$('#error_tags').html("*Please add a description*");
validated = false;
}
if(validated) {
$(this).unbind('submit').submit();
}
});
You just remove your return false inside each condition,
check this jsfiddle how it works if you remove return false line.
Note:Return false will stop your execution there
Remove the "return false" in the if clauses. This stops your function and the other if clauses wouldn´t get called.
just add 'return' keyword before validateform()
like this
<form name="qaform" class="nice" method="POST" onsubmit="return validateForm()" action="/ask/ask-question/">
Try making these 5 small changes to your validateForm method -
function validateForm() {
var valid = true; // 1
//title validation
if (document.qaform.question_title.value == "") {
document.getElementById('error_title').innerHTML="*Please add a title*";
valid = false; // 2
}
//body validation
if (document.qaform.question_description.value == "") {
document.getElementById('error_body').innerHTML="*Please add a description*";
valid = false; // 3
}
//tag validation
if (document.qaform.question_tags.value == "") {
document.getElementById('error_tags').innerHTML="*Please add a description*";
valid = false; // 4
}
return valid; // 5
}
i think the reason why it only validates the first one, is because you return false to exit the validate function, if you do the return false after all the if loops i think it will do what you want.
How do I make a script in javascript to output an error and prevent form submission with empty fields in the form? Say the form name is "form" and the input name is "name". I have been having some trouble with PHP not always handling the empty fields correctly, so I would like this as a backup. Any help is appreciated, thanks.
HTML Code :-
<form name='form'>
<input type="button" onclick="runMyFunction()" value="Submit form">
</form>
Javascript Code :-
function runMyFunction()
{
if (document.getElementsByName("name")[0].value == "")
{
alert("Please enter value");
}
else
{
var form= document.getElementsByName("form")[0];
form.submit();
}
}
Claudio's answer is great. Here's a plain js option for you. Just says to do nothing if field is empty - and to submit if not.
If you need to validate more than one, just add an && operator in the if statement and add the same syntax for OtherFieldName
function checkForm(form1)
{
if (form1.elements['FieldName'].value == "")
{
alert("You didn't fill out FieldName - please do so before submitting");
return false;
}
else
{
form1.submit();
return false;
}
}
This is untested code but it demonstrates my method.
It will check any text field in 'form' for empty values, and cancel the submit action if there are any.
Of course, you will still have to check for empty fields in PHP for security reasons, but this should reduce the overhead of querying your server with empty fields.
window.onload = function (event) {
var form = document.getElementsByName('form')[0];
form.addEventListener('submit', function (event) {
var inputs = form.getElementsByTagName('input'), input, i;
for (i = 0; i < inputs.length; i += 1) {
input = inputs[i];
if (input.type === 'text' && input.value.trim() === '') {
event.preventDefault();
alert('You have empty fields remaining.');
return false;
}
}
}, false);
};
Attach an event handler to the submit event, check if a value is set (DEMO).
var form = document.getElementById('test');
if (!form.addEventListener) {
form.attachEvent("onsubmit", checkForm); //IE8 and below
}
else {
form.addEventListener("submit", checkForm, false);
}
function checkForm(e) {
if(form.elements['name'].value == "") {
e.preventDefault();
alert("Invalid name!");
}
}
I'm trying to use tinymce's getContent() to make a custom validation rule, how can I do this with jquery validation? I need to apply the rule to a textarea formatted with tinymce.
Validation: http://bassistance.de/jquery-plugins/jquery-plugin-validation/
$("#element").click( function(e) {
console.log(tinyMCE.activeEditor.getContent());
$("#someForm").validate({
rules: {
title: {
required: true
}
}
});
});
I'm thinking of just using a little bit of javascript with getContent() because it looks like there's just as much effort creating a workaround to get jquery validation working with tinymce. Thoughts on possible solutions?
The following stackoverflow questions should help you on that issue:
validating multiple TinyMCE Editor
Jquery validation form with TinyMCE field who gives no error by empty value
Hi if your are not getting client side validation on form submit time when you are with tinymce try this code
suppose your have two html editor 1 is txtAboutCompanyand 2 is txtProductinfo
this is client side code
<div class="divclass">
#Html.LabelFor(model => model.txtAboutCompany, new { #class = "required" })
#Html.EditorFor(model => model.txtAboutCompany)
<span class="field-validation-error" id="AC" style="margin:9px 0 0 157px;"></span>
</div>
this is jquery
$("#BusinessProfile").click(function () {
var aboutC = $("#txtAboutCompany").val()
var pinfo = $("#txtProductinfo").val();
if (aboutC == "" && pinfo == "") {
$("#AC").append("").val("").html("Please enter about company")
$("#PI").append("").val("").html("Please enter product information")
$("#bpform").valid();
return false;
} else if (aboutC == "") {
$("#PI").append("").val("").html("")
$("#AC").append("").val("").html("Please enter about company")
$("#txtAboutCompany").focus();
$("#bpform").valid();
return false;
} else if (pinfo == "") {
$("#AC").append("").val("").html("")
$("#PI").append("").val("").html("Please enter product information")
$("#txtProductinfo").focus();
$("#bpform").valid();
return false;
}
else {
$("#AC").append("").val("").html("");
$("#PI").append("").val("").html("");
//return true;
$("#bpform").validate();
}
});
you can get your all required validation on form submit time
I know this is not proper way but you can do it .
function tinymceValidation() {
var content = tinyMCE.activeEditor.getContent();
if (content === "" || content === null) {
$("#questionValid").html("<span>Please enter question statement</span>");
} else {
$("#questionValid").html("");
}
}
tinymce.activeEditor.on('keyup', function (e) {
debugger;
tinymceValidation();
});
$(form).submit(function (e) {
tinymceValidation();
});