Forms & Validation

Standard Form Validation

It is a good idea to perform basic tests on user-inputted data before sending it to the server just to make sure 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 away from the browser. We can, though, make 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 only a number from one through 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;

Enter a number from 1 to 10


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);

Test using the following boolean: pattern.test("STRING")

Reg Ex Cheat Sheet

Reg Ex Samples/Templates

↓ 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; } }

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

↑ Back to Top