Reputation: 23
Without using JQuery, I have multiple forms on a page, without re-writing loads of functions, can you help me with this?
<html><head>
<script type="text/javascript">
function validPhone() {
if(document.all.[phoneVar].value.length <= 7)
alert("You must enter a valid phone number");
document.all.[phoneVar].focus() ;
return false;
}
</script>
</head><body>
<script type="text/javascript">
function checkThisParticularForm() {
var phoneVar = document.GetElementById('phone').value; //set element id
validPhone(); //this calls the validPhone function
}
</script>
<form action="./logging.php" method="post" enctype="multipart/form-data" name="NewCallForm" onsubmit="checkThisParticularForm();">
<input type="text" class="textbox" id="phoneNumber" name="phoneNumber" value="" />
<input type="submit" value="Submit Details">
</form>
</body></html>
On submitting each form, I'm wanting it to validate certain fields, in this example, the phone number, but I'm wanting to create 1 main function that can be called on by other forms so it contains a variable [phoneVar]
which I'm trying to declare before that function is called.
Sorry if this is simple, I'm not good with JavaScript, any help/pointers appreciated.
Upvotes: 1
Views: 102
Reputation: 23396
Here's a simple way to do this, but at first you've to wrap all the forms within a div id="allforms"
.
window.onload = function () {
document.getElementById('allforms').addEventListener('submit', function (e) {
var pn = e.target.phoneNumber;
if (pn.value.length <= 7) {
alert("You must enter a valid phone number");
pn.focus() ;
e.preventDefault();
}
});
}
The idea is, that submit
event bubbles to the div
, and only you need to do, is to listen submit
events on that div
. This is called event delegation.
e.target
in the listener function refers to an element, which triggered the event. In this case it is the form
element which is meant to be sumitted.
Since e.target
is a form
, you can refer directly to the named form
elements. document.all
is IE-specific, and obsoleted in IE11.
e.preventDefault()
prevents the default action after event, in this case it prevents the form to be submitted.
If you need support for IE<9 too, please let me know, I'll add the code.
Upvotes: 1
Reputation: 18783
Consider writing a validation library and using HTML5 data-foo
attributes to do all the dirty work:
<form ...>
<input type="text" name="foo"
data-validation-required="true">
<input type="text" name="phone"
data-validation-required="true"
data-validation-required-message="The phone number is required"
data-validation-format="^\\d{3}-\\d{3}-\\d{4}"
data-validation-format-message="Please enter a valid phone number">
</form>
And create a JavaScript library to do the validation:
var Validator = {
init: function() {
document.documentElement.addEventListener("submit", this.handleSubmit.bind(this), false);
},
handleSubmit: function(event) {
var form = event.target.form || event.target,
requiredFields = form.querySelectorAll("[data-validation-required=true"),
formattedFields = form.querySelectorAll("[data-validation-format]");
if (!this.validateRequiredFields(requiredFields)) {
event.preventDefault();
}
else if (!this.validateFormats(formattedFields)) {
event.preventDefault();
}
},
validateRequiredFields: function(fields) {
var regex = /^\s*%/, i = 0,
success = true;
for (i; i < fields.length; i++) {
if (regex.test(fields[i].value)) {
this.showMessage(fields[i].getAttribute("data-valiation-required-message") || "This field is required", fields[i]);
success = false;
}
}
}
validateFormats: function(fields) {
var format, field,
i = 0, length = fields.length,
success = true;
for (i; i < length; i++) {
field = fields[i];
format = new RegExp(field.getAttribute("data-validation-format"));
if (!format.test(field.value)) {
this.showMessage(field.getAttribute("data-validation-format-message"), field);
success = false;
}
}
return success;
},
showMessage: function(message, field) {
field.classList.add("invalid");
var span = document.createElement("span");
span.className = "validation-error";
span.innerHTML = message;
field.parentNode.insertBefore(span, field);
}
};
Validator.init();
That's all you need for the whole page because document.documentElement
is the <html>
tag. And since submit
events bubble up the document tree, you only need one submit handler.
(Note: this is untested code, but should give you the basic idea)
Upvotes: 0