JavaScript Regular Expression Validation Code

JavaScript Validate the value by regular expression

1

Username validation

starting with [a-z] and [a-z0-9_] letters only. min-max 5-20
JavaScript
function validateUsername(username) {
    var regex = /^[a-z][a-z0-9_]{4,20}$/gi;
    return regex.test(username);
}
HTML
<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>
2

Email validation

3

Date validation

4

Strong password validation

5

URL link validation

6

Mobile number validation

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>
  function validateUsername(username) {
      var regex = /^[a-z][a-z0-9_]{4,20}$/gi;
      return regex.test(username);
  }

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

  document.getElementById("demo-form").addEventListener("submit", function (event) {
      var username = document.getElementById("username").value;
      var email = document.getElementById("email").value;
    
      var email_valid_label = document.getElementById("email-valid-label");
      var 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';
          event.preventDefault();
          return false;
      }
      if (!validateEmail(email)) {
          email_valid_label.innerText = 'Invalid Email Address';
          event.preventDefault();
          return false;
      }
    
     // ajax()
     // ...........
     // event.preventDefault();
  });
</script>