1

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);
        }
    }
}

2 Answers 2

2

One solution would be to apply a class to all of your input fields then create an array of elements by type, which is how I've done this and was able to better iterate things that previously needed a unique ID. Example:

var elementArray = document.getElementsByClassName('unique-class');

You can also create the array using the Tag Name as follow:

var inputs = document.getElementsByTagName('input');

For more information about getElementsByTagName() you can check here for further details and examples:

https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName

Sign up to request clarification or add additional context in comments.

5 Comments

If every required field has a pre existing class required already on them, could I use var elementArray = document.getElementsByClassName('required'); you think?
I'll try it and get back to you. Thank you :).
I tried this fix (ill update original post in a sec, but the getElementsByClassName() is pulling the actual element, html and all. I tried putting getElementsByClassName('required').value and then it raised a function is not defined error.
Fixed it by instead specifying the value of the input in the part where you select which input in the array. Selected answer, nice and simple. Thanks!
Sorry for the slow reply, I was away from my computer. I'm really glad the answer was helpful!
2

There are many solutions.

:input Selector

If you want to grab all inputs inside your form tag you can do that with the :input selector:

jQuery

var $inputs = jQuery('form').find(':input');

Native Javascript

var $form = document.getElementById('my-form');
var $inputs = $form.getElementsByTagName('input');

Note: the select tag will be ignored for the native solution


Add extra class

As Kyle L. wrote, you can do it, if you add an extra class to all you inputs, that you want to select:

HTML

<input type="text" name="my-input" class="input-field" />

jQuery

var $inputs = jQuery('form).find('.input-field');

Native Javascript

var $form = document.getElementById('my-form');
var $inputs = $form.getElementsByClassName('input-field');

aria-required

You can do the same with aria-required for validating required fields.

HTML

<input type="text" name="my-input" aria-required="true" />

jQuery

var $inputs = jQuery('form').find('[aria-required]');

1 Comment

Good answer! was looking for something that didn't involve jQuery but I'm sure that these answers will come in handy for someone else! +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.