Standard Form Validation
It is a good idea to perform basic tests on user-inputted data before sending it to the server to ensure it meets basic standards. This is not, in any way, a substitute for actual security tests that must be performed on the server before consuming the data. Any code running in the browser can be altered, so truly protecting the server from malicious code sent via form data can only be done outside of the browser. However, we can perform a few basic checks in the browser to avoid sending unusable data to the server.
Below is a common approach to basic form validation using JavaScript. This will test to ensure that only a number from 1 to 10 is entered.
function validate() {
const x = document.valform1.num.value;
if (isNaN(x) || x < 1 || x > 10) {
alert('Please enter a number between 1 and 10.');
return false;
} else {
alert('Validation Successful!');
return true;
}
}
Regular Expression Validation
Regular Expressions can be used to set a pattern for user input.
There are two ways to do this:
- const pattern = pattern / attributes;
- const pattern = new RegExp(pattern, attributes);
pattern.test("STRING")
↓ Examples ↓
RegEx validation: - Letters only →
function regexValTest(elm) {
const exp = /^[A-Za-z]+$/;
let errorBox= '';
let textInputVal = elm.regexTextInput.value;
let theValTest = exp.test(textInputVal);
if (theValTest) {
errorBox = document.getElementById('errorbox');
errorBox.innerHTML = 'Success! You did it!
';
alert('Validation Sucessful');
alert('Validation Sucessful');
} else {
errorBox = document.getElementById('errorbox');
errorBox.innerHTML = 'VALIDATION FAILED - ↓ Try again ↓
';
elm.regexTextInput.focus();
return false;
}
}
More RegEx Validation: - /^[3-7]{7,10}$/ (Numbers only 3-7) →
function regexValTest2(elm) {
// Range numbers 3-7 and a minimum of 7-10 characters long
const exp = /^[3-7]{7,10}$/;
let errorBox = ''
let textInputVal = elm.regexTextInput2.value;
let theValTest = exp.test(textInputVal);
if (theValTest) {errorBox = document.getElementById('errorbox2');
errorBox.innerHTML = 'Success! You did it!
';
alert('Validation Sucessful');
} else {
errorBox = document.getElementById('errorbox2');
errorBox.innerHTML = 'VALIDATION FAILED - ↓ Try again (a minimum of 7-10 charaters that are only numbers 3-7 and.) ↓
';
elm.regexTextInput2.focus();
return false;
}
}