Can I mark a field invalid from javascript?

Edit: Someone clarified that you're looking for "valid" "invalid" attributes for DOM.

I would add attributes to each tag using dom_object.setAttribute("isvalid", "true"). You could also have a central validation function which updates these attributes each time (and use dom_object.getAttribute("isvalid") each time).

You could run this function each time an element loses focus, or whenever you want.

Not exactly elegant, but unfortunately there's no "pseudo" support with javascript and HTML5 now.


If I understand your question, you can do validation with Javascript. However, be warned that it is very easy to circumvent client side validation, especially javascript validation. You should never trust client data and always do checking on the server side.

For example, I could easily find element IDs by inspecting the source code, then do document.getElementById('some_id').setAttribute('max', new_number) to change the max value (this was one of the entries from your link).

There are various ways to do it, so I'll try to give you the general idiom.

You can grab the value by doing document.getElementById('form_element_id').value (make sure you give the form a name which is sent to the server, and an id which is used by javascript). For textareas, you can use .innerHTML.

Then you have the value in a variable, there are various ways to check it.

For example, you could do if (parseInt(my_value) < 0) //error. You could also use regular expressions, I won't explain it all but you could start here http://www.w3schools.com/jsref/jsref_obj_regexp.asp . I know w3schools isn't the best source but I find it an okay place to start.

Now for the validation part: add onsubmit="return validateForm() to your form tag where validateForm() is the function which does all the checking. And the function just returns true if valid and false otherwise. This overrides the default validation function (which by default does nothing).

So in the above example, //error would be replaced by return false. You can do other things too; such as alert the error then return false. You could also use javascript to highlight the invalid fields (not sure if this is what you mean by "mark an input field as invalid/valid from javascript")

Of course, if you don't want to check all the fields you only have to return true if the certain ones pass. Again, you shouldn't rely on this, but if you're only out to deter average people then it's an easy solution.


You could use the customValidity function for this purpose.

If you add a customValidity message to the field, it becomes invalid. When you set the message as an empty string, it becomes valid again (unless it is invalid because of other reasons).

field.setCustomValidity("Invalid field."); will make the field invalid.

field.setCustomValidity(""); will make the field valid unless it fails an HTML5 constraint.