I've created code in JavaScript for a form validation in a variety of different ways, including if the field is empty, if it contains special characters, if it has numbers/letters when it shouldn't have, and if it exceeds a certain limit. There's also some special cases when the field asks for a year/price. My code does exactly what I want already and everything works as intended, however, I am wondering if there is any way to shorten it, as I feel like I have basically hardcoded the functions for each field, and there is probably a better way of doing it, which would shorten my code quite a bit.
The JavaScript is here:
var numbers = /^[0-9]+$/;
var letters = /^[A-Za-z]+$/;
var specialChars = /[^a-zA-Z ]/g;
var special = /^\d{1,3}$/;
var price = /^-?(\d{1,3})(\.\d{1,2})*?$/;
var year = /^\d{1,4}$/;
function ValidateMovSearch() {
const value = document.movSearch.mvTitle.value;
const focusvalue = document.movSearch.mvTitle;
if (value.match(numbers)) {
alert ("Please only use letters!")
focusvalue.focus();
return false;
}
if (value == "") {
alert ("Please do not leave this blank!")
focusvalue.focus();
return false;
}
if (value.length > 50) {
alert ("Maximum of 50 characters allowed!")
focusvalue.focus();
return false;
}
if (value.match(specialChars)) {
alert ("Only characters A-Z, a-z are allowed!")
focusvalue.focus();
return false;
}
return (true);
}
function ValidateMovInsert() {
if (document.movInsert.actID.value.match(letters)) {
alert ("Please only use numbers!")
document.movInsert.actID.focus();
return false;
}
if (document.movInsert.actID.value == "") {
alert ("Please do not leave this blank!")
document.movInsert.actID.focus();
return false;
}
if (document.movInsert.actID.value.length > 50) {
alert ("Maximum of 50 characters allowed!")
document.movInsert.actID.focus();
return false;
}
if (!(document.movInsert.actID.value.match(special))) {
alert ("Only characters 0-9 are allowed!")
document.movInsert.actID.focus();
return false;
}
if (document.movInsert.mvTitle.value.match(numbers)) {
alert ("Please only use letters!")
document.movInsert.mvTitle.focus();
return false;
}
if (document.movInsert.mvTitle.value == "") {
alert ("Please do not leave this blank!")
document.movInsert.mvTitle.focus();
return false;
}
if (document.movInsert.mvTitle.value.length > 50) {
alert ("Maximum of 50 characters allowed!")
document.movInsert.mvTitle.focus();
return false;
}
if (document.movInsert.mvTitle.value.match(specialChars)) {
alert ("Only characters A-Z, a-z are allowed!")
document.movInsert.mvTitle.focus();
return false;
}
if (document.movInsert.mvPrice.value.match(letters)) {
alert ("Please only use numbers!")
document.movInsert.mvPrice.focus();
return false;
}
if (document.movInsert.mvPrice.value == "") {
alert ("Please do not leave this blank!")
document.movInsert.mvPrice.focus();
return false;
}
if (document.movInsert.mvPrice.value.length > 50) {
alert ("Maximum of 50 characters allowed!")
document.movInsert.mvPrice.focus();
return false;
}
if (!(document.movInsert.mvPrice.value.match(price))) {
alert ("Only characters 0-9 and . are allowed!")
document.movInsert.mvPrice.focus();
return false;
}
if (document.movInsert.mvYear.value.match(letters)) {
alert ("Please only use numbers!")
document.movInsert.mvYear.focus();
return false;
}
if (document.movInsert.mvYear.value == "") {
alert ("Please do not leave this blank!")
document.movInsert.mvYear.focus();
return false;
}
if (document.movInsert.mvYear.value.length > 50) {
alert ("Maximum of 50 characters allowed!")
document.movInsert.mvYear.focus();
return false;
}
if (!(document.movInsert.mvYear.value.match(year))) {
alert ("Only characters 0-9 are allowed!")
document.movInsert.mvYear.focus();
return false;
}
if (document.movInsert.mvGenre.value.match(numbers)) {
alert ("Please only use numbers!")
document.movInsert.mvGenre.focus();
return false;
}
if (document.movInsert.mvGenre.value == "") {
alert ("Please do not leave this blank!")
document.movInsert.mvGenre.focus();
return false;
}
if (document.movInsert.mvGenre.value.length > 50) {
alert ("Maximum of 50 characters allowed!")
document.movInsert.mvGenre.focus();
return false;
}
if (document.movInsert.mvGenre.value.match(specialChars)) {
alert ("Only characters A-Z, a-z are allowed!")
document.movInsert.mvGenre.focus();
return false;
}
return (true);
}
function ValidateMovDelete() {
if (document.movDelete.mvTitle.value.match(letters)) {
alert ("Please only use numbers!")
document.movDelete.mvTitle.focus();
return false;
}
if (document.movDelete.mvTitle.value == "") {
alert ("Please do not leave this blank!")
document.movDelete.mvTitle.focus();
return false;
}
if (document.movDelete.mvTitle.value.length > 50) {
alert ("Maximum of 50 characters allowed!")
document.movDelete.mvTitle.focus();
return false;
}
if (!(document.movDelete.mvTitle.value.match(special))) {
alert ("Only characters A-Z, a-z are allowed!")
document.movDelete.mvTitle.focus();
return false;
}
return (true);
}
And my HTML form is here:
<form name = "movInsert" align = "center" action="movieInserting.php"
onSubmit = "return ValidateMovInsert()">
Actor ID:<br>
<input type = "text" name = "actID"
<br><br>
Movie Title:<br>
<input type = "text" name = "mvTitle"
<br><br>
Movie Price:<br>
<input type = "text" name = "mvPrice"
<br><br>
Movie Year:<br>
<input type = "text" name = "mvYear"
<br><br>
Movie Genre:<br>
<input type = "text" name = "mvGenre"
<br><br>
<input type = "submit" value = "Insert">
</form>
1 Answer 1
The technique you are looking for is a dispatch table. You're only dispatching regular expressions, so the table doesn't need to have functions in it at all.
Collect the validating regexes and their corresponding error messages into a data structure. Use HTML classes on the input fields to select which checks apply to each field.
Include the field name (or some other descriptive property) in the error message.
Attach the onsubmit
handler in your code, not in the HTML, so that the page still works even if the JavaScript doesn't get loaded.
const validations = {
number: [ /^\d*$/, "Please only use numbers!" ],
some: [ /./, "Please do not leave this blank!" ],
words: [ /^[a-zA-Z ]*$/, "Please only use letters and spaces!" ],
concise: [ /^.{0.50}$/, "Maximum of 50 characters allowed!" ],
price: [ /^[+-]?\d{1,3}\.?\d{0,2}$/, "Only 0-9 and . are allowed!" ],
year: [ /^\d{1,4}$/, "Please enter a valid year!" ]
}
function ValidateMovSearch(submitted) {
var valid=true;
const fields=Array.from( submitted.target.querySelectorAll("input") );
fields.forEach( field => {
const checks=Array.from( field.classList )
.filter( checkname => validations.hasOwnProperty(checkname) )
.map( checkname => validations[checkname] );
field.value=field.value.trim();
checks.forEach( check => {
const regex=check[0],
message=check[1];
// check if valid-so-far, to limit number of alerts
if (valid && !regex.test( field.value )) {
alert(field.name + ": " + message);
field.focus();
valid=false;
}
});
});
return valid;
}
document.movInsert.onsubmit=ValidateMovSearch;
<form name="movInsert">
Actor ID:<br> <input type="text" name="Actor ID" class="some number">
<br>Movie Title:<br> <input type="text" name="Movie Title" class="some concise words">
<br>Movie Price:<br> <input type="text" name="Movie Price" class="some price">
<br>Movie Year:<br> <input type="text" name="Movie Year" class="some year">
<br>Movie Genre:<br> <input type="text" name="Movie Genre" class="some concise words">
<br><input type = "submit" value = "Insert">
</form>