I have a simple form with a couple of dropdowns a multi-select and an editor.
The dropdowns both have an initial item which has a text value of Please Select and a value of ''. On submission I have the following bit of Javascript/JQuery that checks that I have values in my dropdowns, multi-select and editor.
var validFlag = true;
var dropdownlist = $("#addNew_dTeam").data("kendoDropDownList");
if (dropdownlist.value() == "") {
validFlag = false;
errorMsg = "<li>Select Team</li>"
}
dropdownlist = $("#addNew_dType").data("kendoDropDownList");
if (dropdownlist.value() == "") {
validFlag = false;
errorMsg += "<li>Select Entry Type</li>"
}
var multiSelect = $("#msServers").data("kendoMultiSelect");
if (multiSelect.value() == "") {
validFlag = false;
errorMsg += "<li>Add at least one Server or select N/A</li>"
}
var editor = $("#diaryComments").data("kendoEditor");
if (editor.value() == "") {
validFlag = false;
errorMsg += "<li>A comment is mandatory</li>"
}
The code works fine for the dropdowns and multi-select, but the check for empty editor content does not work. My editor is empty yet the if (editor.value() == "") is not true.
While editor is empty, consider one blank space so your condition will be like if (editor.value() == ' ') (there is one space between single quote)...
Demo
hope so it will work for you...
Related
I tried to use JavaScript for a control mechanism inside a pdf form. There are many fields, checkboxes etc. some of them are required, some of them don't and some of the required only shows when you check a certain box.
My problem now is: some of the required fields are dropdown menus or option fields and the javascript don't show that they are "missing" when I click the button. If I erase the (f.value.length<1)) part it is showing all required fields but don't recognize the ones who are filled e.g. with a dropdown element, text or similiar 'cause the condition is missing.
I need a code which finds all required fields and sees if they are empty or filled with ANYTHING and a way to exclude some fields, cause some are only visible when a certain checkbox is activated or a way to include those fields only when the certain box is activated.
Thank you!
kontrollieren();
function kontrollieren() {
var feld;
feld = ""
for (var i = 0; i < this.numFields; i++) {
var fName = this.getNthFieldName(i);
var f = this.getField(fName);
if ((f.type != "button") && f.required && (f.value.length < 1)) {
feld = feld + fName + "\n";
}
}
if (feld == ""){
app.doc.print();
}
else {
app.alert("Bitte füllen sie vor dem Drucken alle Pflichtfelder aus.\nFehlende Felder:\n\n" + feld);
}
}
all of the inputs should have a name as well as a value field. You may need to identify the input (and thus validation method employed) this way.
In situations such as these, where there are multiple inputs, and multiple conditionals determining what's required, try to catch the false. I'd employ something similar to this:
for (var i = 0; i < this.numFields; i++) {
var fName = this.getNthFieldName(i);
var f = this.getField(fName);
if ((f.type != "button") && f.required) {
// For a Select Input
if (f.name === 'selectInputName') {
// Or whatever the 'default' value is that represents not selecting a value
if (f.value !== 'Select One') {
feld = feld + fName + '\n';
}
}
// For a checkbox
if (f.name === 'checkboxInputName' && f.checked) {
feld = feld + fName + '\n';
}
// For an input
if (f.name === 'textInputName' && f.length.value > 0) {
feld = feld + fName + '\n';
}
}
}
I'm not 100% how your structure works - getNthFieldName() && getField() are two functions I am not familiar with, but hopefully, the idea above is still relatable.
I am using this library https://github.com/asimism/native-validations in a form validation, it's working fine but I have an error message in the checkboxes group validation when I try to submit the group of checkboxes empty it appears: "null"
this is the demo link: you have to click "submit" without clicking any field in order to see the "null" message https://www.cssscript.com/demo/custom-html5-form-validator-native-validations/
https://codesandbox.io/s/8xr6vx5nnj?fontsize=14
apparentely, there is an error in this function
function checkBoxGroupValidate(event) {
//get all checked checkboxes for a group and if its null then mark it invalid or valid
var totalChecked = event.target.parentNode.querySelector("input[name$='[]']:checked");
if (totalChecked === null) {
var errorMessage = '';
if(event.target.dataset.requireError){
errorMessage = event.target.dataset.requireError;
}else if(event.target.parentNode.dataset.requireError){
errorMessage = event.target.parentNode.dataset.requireError;
}else {
errorMessage = OptionGroupMessage;
}
event.target.parentNode.classList.remove(SuccessClass);
event.target.parentNode.classList.add(ErrorClass);
if (event.target.parentNode.querySelector(HelpBlockSelector) === null) {
event.target.parentNode.insertAdjacentHTML("afterbegin", MessageTag.replace("{0}", errorMessage));
}
} else {
event.target.parentNode.classList.remove(ErrorClass);
event.target.parentNode.classList.add(SuccessClass);
var spanError = event.target.parentNode.querySelector(HelpBlockSelector);
if (spanError !== null) {
event.target.parentNode.removeChild(spanError)
}
}
}
The querySelector is returning null because is searching the error message on the childs elements in this case checkbox but they don't have data-require-error attribute the first time to get the error.
var errorMessage = groupParent.querySelector("input[name$='[]']").getAttribute('data-require-error');
instead use the parent directly
var errorMessage = groupParent.getAttribute("data-require-error");
I am trying to make a javascript validating form, and am a bit stuck on validating drop down inputs (select)
I have been using this so far but am unsure on how to implement the validation to the select options, if anyone could give me some tips that would be great.
Edit: Also, how would I implement email validation, e.g containing #, thanks
Thanks
<input id="firstname" onblur="validate('firstname')"></input>
Please enter your first name
Thanks
http://jsfiddle.net/ww2grozz/13/
you need to handle select as follow
var validated = {};
function validate(field) {
// Get the value of the input field being submitted
value = document.getElementById(field).value;
// Set the error field tag in the html
errorField = field + 'Error';
// Set the success field
successField = field + 'Success';
if (value != '') {
document.getElementById(successField).style.display = 'block';
document.getElementById(errorField).style.display = 'none';
validated[field] = true;
} else {
document.getElementById(successField).style.display = 'none';
document.getElementById(errorField).style.display = 'block';
validated[field] = false;
}
}
function SimulateSubmit() {
// Query your elements
var inputs = document.getElementsByTagName('input');
// Loop your elements
for (i = 0, len = inputs.length; i < len; i++) {
var name = inputs[i].id;
if (!validated[name]) {
// Call validate
validate(name);
// Prevent default
}
}
var all_select = document.getElementsByTagName("select"); // get al select box from the dom to validate
for (i = 0, len = all_select.length; i < len; i++) {
var name = all_select[i].id;
if (!validated[name]) {
// Call validate
validate(name);
// Prevent default
}
}
}
here the Working fiddle
using jQuery function
$('input').on('keyup', function() {
var isValid = $.trim($(this).val()) ? true : false;
// show result field is Valid
});
You must use <form> tag and set your action to it I have done that check this link and I have added select tag and set it to -1 by default for checking purpose while validating
I need to check if there are blank input text fields in my < form >. Instead of doing this multiple times
$.trim($('#myMessage').val()) == '' || $.trim($('#myage').val()) == '' .//so on...
What is the best way to check multiple blank text fields?
use:
if($('input:text[value=""]').length);
try
$("form input[type=text]").filter(function () {
return $.trim(this.value) != "";
}).length;
Note: You have to use any form id or class instead of form
Here is the code ,
// Validate form fields in Sign up form
$(".signup-form").submit(function(){
var isFormValid = true;
$(".signup-form .required input:text").each(function(){ // Note the :text
if ($.trim($(this).val()).length == 0){
$(this).parent().addClass("highlight");
isFormValid = false;
} else {
$(this).parent().removeClass("highlight");
}
});
if (!isFormValid) alert("Please fill in all the required fields (highlighted in red)");
return isFormValid;
});
I am having trouble displaying strings depending on the if/else statements in my validation.
If you look at the code below, if the if statement is met, then it displays the message which is fine, but then when I make sure the if statement is met and deliberately fail the else if statement, instead of displaying a message, it just displays a blank. Why is it not displaying a message for when else if statement is met in javascript validation below:
function editvalidation() {
var isDataValid = true;
var currentAssesO = document.getElementById("currentAssessment");
var noStudentsO = document.getElementById("addtextarea");
var studentAssesMsgO = document.getElementById("studentAlert");
studentAssesMsgO.innerHTML = "";
if (currentAssesO.value == ""){
$('#targetdiv').hide();
studentAssesMsgO.innerHTML = "Please Select an Assessment to edit from the Assessment Drop Down Menu";
isDataValid = false;
}else if (noStudentsO.value == ""){
$('#targetdiv').hide();
studentAssesMsgO.innerHTML = "You have not Selected any Students you wish to Add into Assessment";
isDataValid = false;
}
else{
studentAssesMsgO.innerHTML = "";
}
return isDataValid;
}
UPDATE:
HTML:
SELECT BOX (Options are appended into this box):
<select multiple="multiple" name="addtextarea" id="studentadd" size="10">
</select>
DROP DOWN MENU:
<select name="session" id="sessionsDrop">
<option value="">Please Select</option>
<option value='20'>EWYGC - 10-01-2013 - 09:00</option>
<option value='22'>WDFRK - 11-01-2013 - 10:05</option>
<option value='23'>XJJVS - 12-01-2013 - 10:00</option>
</select> </p>
ALERT MESSAGE:
<div id='studentAlert'></div>
Reuirements for validation:
If drop down menu is empty, then display message that assessment needs to be select from drop down menu in alert message div.
If drop down menu is not empty, then check to see if the select box contains any options, if select box contains no options, then replace div alert message stating no students have been selected to add to assessment
If drop down menu is not empty and select box is not empty (or in other words contains an option), then div alert message is just an empty string ""
Rephrase your JavaScript this way:
function editvalidation() {
var isDataValid = true;
var currentAssesO = document.getElementById("currentAssessment");
var noStudentsO = document.getElementById("addtextarea");
var studentAssesMsgO = document.getElementById("studentAlert");
var errorMsg = "";
studentAssesMsgO.innerHTML = "";
if (currentAssesO.value == "" || noStudentsO.value == "") {
$('#targetdiv').hide();
isDataValid = false;
if (currentAssesO.value == "") {
errorMsg += "Please Select an Assessment to edit from the Assessment Drop Down Menu";
}
if (noStudentsO.value == "") {
errorMsg += "You have not Selected any Students you wish to Add into Assessment";
}
studentAssesMsgO.innerHTML = errorMsg; // Plus whatever styling for messages.
}
return isDataValid;
}
Updated answer
Please include jQuery by putting this in the <head> section.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Update your script:
function editvalidation()
{
if ($("#sessionsDrop").val()=="")
$("#studentAlert").html("Assessment needs to be filled.");
if ($("#sessionsDrop").val()!="" && $("#studentadd").children().length==0)
$("#studentAlert").html("No students have been selected to add to assessment.");
if ($("#sessionsDrop").val()!="" && $("#studentadd").children().length!=0)
return true;
return false;
}
Here is the magic:
else {
studentAssesMsgO.innerHTML = "";
alert(noStudentsO.value); // tell me why I'm in this block
}