JavaScript Regular expression validation

Validate the form input value with JavaScript regular expression RegEx. Username, strong password, email address, and mobile number regex validation functions

1

Username validation

Demo
starting with[a-z0-9_] letters only. min-max 5-20
JavaScript
const validateUsername = username => {
    let regex = /^[a-z][a-z0-9_]{4,20}$/gi;
    return regex.test(username);
};
HTML usage
<label for="username">username</label>
<div>
    <input id="username" class="input-text" type="text">
    <span id="username-valid-label" style="display: block;color: red"></span>
</div>

<script>
document.getElementById("username").addEventListener("change", function() {
    var username = this.value;
    var result = validateUsername(username);
    var label = document.getElementById("username-valid-label");
    if (result) {
        label.innerText = '';
    } else {
        label.innerText = 'Invalid string. only [a-z0-9_] min-max 5-20';
    }
});
</script>
Edit Code
2

Email validation

Demo
JavaScript
const validateEmail = email => {
    var regex = /^([a-z0-9!#$%&'*+\-/=?^_`{|}~]+(?:\.[a-zA-Z0-9!#$%&'*+\-/=?^_`{|}~]+)*)@((?:[a-z0-9]+(?:[a-z-0-9-]*)\.)+[a-z]{2,})$/gi;
    return regex.test(email);
};
HTML usage
<label for="email">Email</label>
<div>
    <input id="email" class="input-text" type="text">
    <span id="email-valid-label" style="display: block;color: red"></span>
</div>

<script>
document.getElementById("email").addEventListener("change", function() {
    var email = this.value;
    var result = validateEmail(email);
    var label = document.getElementById("email-valid-label");
    if (result) {
        label.innerText = '';
    } else {
        label.innerText = 'Invalid Email Address';
    }
});
</script>
Edit Code
3

Date validation

Demo
JavaScript
const validateDate = date => {
    // date format 2021-12-31 yyyy-mm-dd
    // var regex = /^([1-9]\d{3})-(0[1-9]|1[012])-(0[1-9]|[12]\d|3[01])$/gi;

    // date format 31-12-2021 dd-mm-yyy
    let regex = /^(0[1-9]|[12]\d|3[01])-(0[1-9]|1[012])-([1-9]\d{3})$/gi;
    return regex.test(date);
};
HTML
<label for="date">Date</label>
<div>
    <input id="date" class="input-text" type="text">
    <span id="date-valid-label" style="display: block;color: red"></span>
</div>

<script>
document.getElementById("date").addEventListener("change", function () {
    var date = this.value;
    var result = validateDate(date);
    var label = document.getElementById("date-valid-label");
    if (result) {
        label.innerText = '';
    } else {
        label.innerText = 'Invalid Date [dd-mm-yyy]';
    }
});
</script>
Edit Code
4

Strong password validation

Demo
Minimum 8 chars At least-one small letter [a-z] At least-one upper letter [A-Z] At least-one digit [0-9] At least-one special char [~!@#$%^&*(...)]
JavaScript
const validatePassword = password => {
    if (typeof password != "string") {
        password = "" + password;
    }
    if (password.length < 8) {
        return 'Password length must be 8 chars';
    }
    if (password.search(/[0-9]/) === -1) {
        return 'At least 1 numeric value';
    }
    if (password.search(/[a-z]/) === -1) {
        return 'At least 1 small letter value [a-z]';
    }
    if (password.search(/[A-Z]/) === -1) {
        return 'At least 1 upper letter value [A-Z]';
    }
    if (password.search(/[`~!@#\$%\^&\*\(\)\-_\{\}\=\+'"\>\.\,\?<\/\|\\\:;\]\[]/) === -1) {
        return 'At least 1 special chars [~!@#$%^&*()_+{}":?><...]';
    }
    return true;
};
HTML
<label for="password">Password</label>
<div>
    <input id="password" class="input-text" type="text">
    <span id="pass-valid-label" style="display: block;color: red"></span>
</div>

<script>
document.getElementById("password").addEventListener("change", function () {
    var password = this.value;
    var result = validatePassword(password);
    var label = document.getElementById("pass-valid-label");
    if (result == true) {
        label.innerText = '';
    } else {
        label.innerText = result;
    }
});
</script>
Edit Code
5

URL link validation

Demo
URL starting with http://, https://, or www.
JavaScript
const validateURL = url => {
    //URL starting with http://, https://, or www.
    var regex = /^((https?:\/\/(www\.)?|www\.)[a-zA-Z0-9][\w+\d+&@\-#\/%?=~_|!:,.;+]*)$/gi;
    return regex.test(url);
};
HTML
<label for="url">URL</label>
<div>
    <input id="url" class="input-text" type="text">
    <span id="url-valid-label" style="display: block;color: red"></span>
</div>

<script>
document.getElementById("url").addEventListener("change", function () {
    var url = this.value;
    var result = validateURL(url);
    var label = document.getElementById("url-valid-label");
    if (result == true) {
        label.innerText = '';
    } else {
        label.innerText = 'Invalid URL';
    }
});
</script>
Edit Code
6

Mobile number validation

Demo
JavaScript
const validateMobile = number => {
    // use this regex if only 10 numbers
    // var regex = /^\d{10}$/g;


    // supported number formats
    // (123) 456-7890
    // 123-456-7890
    // 123.456.7890
    // 1234567890
    var regex = /^\(?([0-9]{3})\)?[\-\.\s]?([0-9]{3})[\-\.\s]?([0-9]{4})$/g;
    return regex.test(number);
};
HTML
<label for="mobile">Mobile</label>
<div>
    <input id="mobile" class="input-text" type="text">
    <span id="mobile-valid-label" style="display: block;color: red"></span>
</div>

<script>
document.getElementById("mobile").addEventListener("change", function () {
    var mobile = this.value;
    var result = validateMobile(mobile);
    var label = document.getElementById("mobile-valid-label");
    if (result == true) {
        label.innerText = '';
    } else {
        label.innerText = 'Invalid mobile number';
    }
});
</script>
Edit Code

Form Validation

HTML
<form id="demo-form" action="">
  
  <label for="username">username</label>
  <div>
    <input id="username" class="input-text" type="text">
    <span id="username-valid-label" style="display: block;color: red"></span>
  </div>
  
  <label for="email">email</label>
  <div>
    <input id="email" class="input-text" type="text">
    <span id="email-valid-label" style="display: block;color: red"></span>
  </div>
  <br>
  
  <input type="submit" value="submit">
</form>


<script>
  const validateUsername = username => {
    var regex = /^[a-z][a-z0-9_]{4,20}$/gi
    return regex.test(username)
  }

  const validateEmail = email => {
      var regex = /^([a-z0-9!#$%&'*+\-/=?^_`{|}~]+(?:\.[a-zA-Z0-9!#$%&'*+\-/=?^_`{|}~]+)*)@((?:[a-z0-9]+(?:[a-z-0-9-]*)\.)+[a-z]{2,})$/gi
      return regex.test(email)
  }

  const submitForm = event => {
      event.preventDefault()
      let username = document.getElementById('username').value
      let email = document.getElementById('email').value

      let email_valid_label = document.getElementById('email-valid-label')
      let username_valid_label = document.getElementById('username-valid-label')

      username_valid_label.innerText = ''
      email_valid_label.innerText = ''

      if (!validateUsername(username)) {
          username_valid_label.innerText =
              'Invalid string. only [a-z0-9_] min-max 5-20'
          return false
      }
      if (!validateEmail(email)) {
          email_valid_label.innerText = 'Invalid Email Address'
          return false
      }
      // jquery ajax post
      $.ajax({
          url: 'https://your-domain.com/contact.php',
          data: {
              username: username,
              email: email
          },
          dataType: 'json',
          method: 'POST',
          success: function () {
              alert('success')
          },
          error: function (xhr) {
              alert('error ' + xhr.status + ' ' + xhr.statusText)
          }
      })
  }

  document.getElementById('demo-form').addEventListener('submit', submitForm)

</script>
Edit Code