Accept any character minus $% & | # with RegEx

2

I am something new in web programming and with Regular Expressions (RegEX) . How to allow my TextArea to accept any character except these $%&|<># ?

I'm trying this with my TMForm.js .

regula.custom({
    name:'Special' 
    ,validator:function(){
        return /^[A-Za-z ]-[$%&|<>#]?$/.test(this.value)
    }
})

This is my textarea in my php file.

<label class="message">
    <textarea id="message" class="input" name="cf_message" placeholder="Insert your message:" data-constraints="@Required @Special"> 
       </textarea>
    <span class="empty-message">*This field is required.</span>
    <span class="error-message">*Must have at least 5 characters.</span>
</label>
    
asked by Jorge 10.01.2017 в 16:20
source

2 answers

2

The following regular expression will match any text that contains the characters $%&|<># .

/[$%&|<>#]/
  • [] : group a series of characters (which will match)

Note: thanks to @Mariano for noticing that the /g is over because only the first match is enough.

function validate (e) {
  // valores inválidos
  if(/[$%&|<>#]/.test(e.target.value)) {
    e.target.classList.remove('valid');
    e.target.classList.add('invalid');
  } else {
    e.target.classList.remove('invalid');
    e.target.classList.add('valid');
  }
}
.invalid {
  border: 1px solid #d53400;
}
.valid {
  border: 1px solid #2ecc71;
}
input:focus {
  outline: none;
}
<input type="text" oninput="validate(event)">
    
answered by 10.01.2017 / 16:55
source
2

You can use the following RegExp:

/^[^$%&|<>#]*$/

Description:

/^                 : Empieza con
 [^                : Que no sea uno de los caracteres
   $%&|<>#         : Caracteres a excluir
 ]
 *                 : 0 o mas caracteres
$/                 : Termina en

Demo:

var re = /^[^$%&|<>#]*$/;

document.getElementById('message')
  .addEventListener('input', function () {
    console.log(this.value + ': '+ re.test(this.value));
    this.className = re.test(this.value) ? 'valid' : 'invalid';
  });
.valid {
  border: 1px solid #0f0;
  background-color: #0c0;
}
.invalid {
  border: 1px solid #f00;
  background-color: #c00;
}
<textarea id="message" placeholder="Insert your message:"></textarea>
    
answered by 10.01.2017 в 16:58