简体   繁体   中英

Regex which should not allow any special characters except ,

I am trying to create a regular expression which does not allow any special characters except , , . and they should not come side by side.

For example: STax.sdn,skm should be accepted whereas SDs,.Hnj should throw an error message. I have used the below code, however it is accepting , and . side by side which I don't want.

function validateAnnouncementTags(){
  var announcementTags = document.getElementById("announcementTags").value;
  if (announcementTags.search(/[<>'+\"\/`\\\[\]^={}%;@#!$&*()?:|]/)>-1 ) {
    $('#announcementTagsSpecialCharError').addClass('show');
  } else {
    $('#announcementTagsSpecialCharError').addClass('hide');
    $('#announcementTagsSpecialCharError').removeClass('show');
  }
}

使用此模式:

/^(?!.*[\.,])/

Based on your comments, I am assuming that you want to accept any letters separated by periods or commas. How about we:

  1. Check for valid characters, and
  2. Ensure that no "special" chars occur adjacent?

we can use

function validateAnnouncementTags() {
   var announcementTags=document.getElementById("announcementTags").value;

   if (announcementTags.match(/[a-zA-Z\.,]*/)[0] != annoucementTags
       || announcementTags.search(/[\.,][\.,]/) >= 0 
      ) {
      $('#announcementTagsSpecialCharError').addClass('show');
   } else {
      $('#announcementTagsSpecialCharError').addClass('hide');
      $('#announcementTagsSpecialCharError').removeClass('show');
   }
}

But, if I may be so bold as to assume more structure to your acceptable syntax:

  1. Accept any sequence of letters separated by a comma or period
  2. The sequence will not start with a comma or period
  3. The sequence can end with a comma or period

Then we can use:

function validateAnnouncementTags() {
   var announcementTags=document.getElementById("announcementTags").value;

   if (announcementTags.match(/([a-z0-9]+[\.,]?)*/)[0] != annoucementTags ) {
      $('#announcementTagsSpecialCharError').addClass('show');
   } else {
      $('#announcementTagsSpecialCharError').addClass('hide');
      $('#announcementTagsSpecialCharError').removeClass('show');
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM