Validate regex string

by Ben Clayton

HTML

<input class="redirect-match" size=40 />

CSS

input.regex-syntax-error {
  color: red;
 }
 
input {
  font-size: 24px;

}

JavaScript

$(document).on('keyup','.redirect-match',function(){


	console.log( $(this).val() );
  
  var str = $(this).val();
  
  $(this).removeClass("regex-syntax-error");
  $(this).attr('title','');
  
  // is it a valid regex expression?
  try {
  	var reg = new RegExp(str);
  } catch(e) {
		$(this).attr('title',e);
		$(this).addClass("regex-syntax-error");
  }
  // Also don't allow spaces
  if ( / /.test(str) ){
  	$(this).attr('title','No spaces allowed anywhere');
    $(this).addClass("regex-syntax-error");
  }

});