I found a couple of validation codes, and I made a mix and match, (this is the 'shortest' way to validate fields I have found online, I would love to see a shorter version even!)
I currently put all of the below on each form, I find that if I put it too low, the set required won't be seen by Javascript and I then place it a bit too high, but it then hides the functions underneath, I tried removing semicolons, brackets, but I can't seem to win, at some point Javascript stops running and it doesn't read the whole .js code
I believe I might be able to add it as a content snippet, but it would be painful to have to place it for every page, or is there a way to leave it alone in one place, and pull it for every single page? The code I want to isolate is below
Then on each .js form I'd add whichever fields I required
if(varName !== null){
setRequired('Name', message);
setOptional('Surname', message);
}
setRequired = function (fieldName) {
var $label = $("#" + fieldName + "_label");
$label.parent().addClass("required");
addValidator(fieldName, $label.text());
};
setOptional = function (fieldName) {
var $label = $("#" + fieldName + "_label");
$label.parent().removeClass("required");
removeValidator("RequiredFieldValidator" + fieldName);
};
addValidator = function (fieldName, label) {
var nV = document.createElement("span");
var message = "<span class='font-weight-bold'>" + (typeof label === "string" ? label : fieldName) + "</span> is a required field.";
nV.style.display = "none";
nV.validationGroup = "";
nV.initialvalue = "";
nV.id = "RequiredFieldValidator" + fieldName;
nV.controltovalidate = "#" + fieldName;
nV.errormessage = "<a href=\'#" + fieldName +
"_label\' onclick=\'javascript:scrollToAndFocus(\"" + fieldName + "_label\",\"" +
fieldName + "\");return false;\'>" + message + "</a>";
var $field = $("#" + fieldName);
nV.evaluationfunction = function () {
var value = $field.val();
return typeof value === "string" && value !== "";
};
var $validator = $field.closest("td").find("div.validators");
if ($validator.length === 0) {
var $info = $field.closest("td").find("div.info");
$validator = $("<div class='validators'></div>").appendTo($info);
}
$validator.append(nV);
Page_Validators.push(nV);
};
removeValidator = function (validatorId) {
$.each(Page_Validators, function (index, validator) {
if (validator !== null && validator !== undefined &&
validator.id === validatorId) {
Page_Validators.splice(index, 1);
}
});
};