I'm working with a repository application where users can submit articles, files, links, etc. I'm creating some javascript validation but my issue is that I have multiple partials (template files) and each partial uses different IDs and names for each type of submitted work. I have written a simple javascript validation for our main work type, articles. My problem is that I have to replicate this feature sustainably for the other types and any other that we may add later.
My code at the moment is doing this:
html form:
<form onsubmit="event.preventDefault(); return validateRequiredTitleByID()">
<textarea id="article-title" name="article[title]"></textarea>
<textarea id="article-abstract" name="article[abstract]"></textarea>
<a href="action/something" class="btn btn-primary btn-link">Submit</a>
</form>
validator.js:
function isValid(requiredField) {
if (requiredField === null || requiredField === " ") {
return false;
}
else return true;
}
function validateRequiredTitleById() {
var inpObj = document.getElementById("article_title").value;
if (!isValid(inpObj)) {
document.getElementById("invalid-input-alert").style.visibility = "visible";
return false;
}
alert('validations passed');
document.forms['new_work_form'].submit();
return true;
}
The validator works fine for a single field, but I'm having trouble figuring out how I'm going to apply this validator to every single required field for every work type in a concise manner without manually defining each and every method for every field.
I was thinking to write something that would pull every element with a class of 'required' (a preexisting helper class in the application) into an array and then validating each one in a for loop, but I'm not sure at how I can actually scan the elements in the html to pull them into the script.
UPDATE: I tried using getElementsByClassName('no-space') where no-space is the class I'm using to select each value. By validator.js is now this:
function isValid(requiredField) {
if (requiredField === null || requiredField === " ") {
return false;
}
else {
return true;
}
}
function validateAllFields() {
var inputs = document.getElementsByClassName('no-space');
for (var i = 0; i < inputs.length; i+=1) {
if(!isValid(inputs[i])) {
alert('no!');
}
else {
alert('yes!');
console.log(inputs[i]);
}
}
}
At this point the inputs array is collecting both input elements into the array where I need the actual input values. I tried inputs = document.getElementsByClassName('no-space').value; but it raises a function not defined error.
Answered! For anyone else that has a problem with this, this was my final solution:
function isValid(requiredField) {
if (requiredField === null || requiredField === " ") {
return false;
}
else {
return true;
}
}
function validateAllFields() {
var inputs = document.getElementsByClassName('no-space');
for (var i = 0; i < inputs.length; i+=1) {
if(!isValid(inputs[i].value)) {
alert('no!');
}
else {
alert('yes!');
console.log(inputs[i].value);
}
}
}