Restrict a text box to allow special characters at starting - javascript

I need to validate a text box which i am using for search the content which comes from database.Need to restrict special characters at starting but allow after a word.And space also.
Ex: Must allow
java/j2ee
java&servlets
But Not
#java
$java
(space)java
$("#keyvalue").keypress(function (e) {
var regex = new RegExp("^[a-z0-9][a-z0-9_ .-]*$");
var regex1 =new RegExp("[,%_$]");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)){
$("#errormess").html("Please select valid input").show();
}
if(regex1.test(key)) {
e.preventDefault();
} else {
$("#errormess").html("");
}
});

Try something like this
function isValid(){
return !/[#$\s\/&]/g.test(yourString.indexOf(0));
// Returns true if special char not exists at first position
}
You can add more special characters in [#$\s\/&]

Check this snippet
var textbox = document.getElementById('textbox');
var pattern = /^([a-zA-Z0-9]+)([a-zA-Z0-9!##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?\s]+)$/;
if(!pattern.test(textbox.value)){
console.log('Not allowed!');
}
or this one, having less complex regex
var textbox = document.getElementById('textbox');
var pattern = /^([a-zA-Z0-9].*)$/;
if(!pattern.test(textbox.value)){
console.log('Not allowed!');
}

Related

Checking if password contains symbols as well DOES NOT WORK

In Javascript I tried to add a function like this for checking if the entered password contains any symbol (special) character such as !##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?.
So I did this:
function checkpasswordlength(){
var format1 = /^[!##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]*$/;
var e = document.getElementById("password").value;
if(e != "") {
if(e.length >= 12){
if(e.match(format1)){
document.getElementById("passwordstrengthstatus").style.display = "inline";
document.getElementById("passwordstrengthstatus").innerHTML = "strong";
document.getElementById("passwordstrengthstatus").style.setProperty('background-color', '#3cb878', 'important');
}else{
document.getElementById("passwordstrengthstatus").style.display = "inline";
document.getElementById("passwordstrengthstatus").innerHTML = "normal";
document.getElementById("passwordstrengthstatus").style.setProperty('background-color', '#3cb878', 'important');
}
}else{
document.getElementById("passwordstrengthstatus").style.display = "inline";
document.getElementById("passwordstrengthstatus").innerHTML = "weak";
document.getElementById("passwordstrengthstatus").style.setProperty('background-color', 'red', 'important');
}
}else{
document.getElementById("passwordstrengthstatus").style.display = "none";
}
}
As you can see, it will check if the password is not empty and it's length is more than 12 characters, then go ahead and check for e.match(format1).
But the problem is, when I enter those characters as well, it will not return this condition as true and therefore the message strong does not appear and still shows normal message on screen.
So what's going wrong with this?
How can I solve this problem and properly check if the string contains the written symbols or not?
If you just want to check for the presence of at least one symbol character, then remove the ^ and $ anchors and just use:
var format1 = /[!##$%^&*()_+\=\[\]{};':"\\|,.<>\/?-]/;
Note that the hyphen has been moved to the end of the character class. If you want to stick with your original pattern and match the entire password, then modify to this:
var format1 = /^.*[!##$%^&*()_+\=\[\]{};':"\\|,.<>\/?-].*$/;
Your current regex matches only if the password contains nothing but special characters. try adding a-zA-Z0-9 inside too
^[a-zA-Z0-9!##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]*$

Regex for the MAC ID pattern to restrict FF:FF:FF:FF:FF:FF and leading 01-xx-xx-xx-xx-xx,

I tried to construct a working regex for the mentioned scenario but it's not working.
It should restrict the MAC IDs with leading "01" (01-xx-xx-xx-xx-xx). eg
01:AA:BB:05:31:01 <- Not valid.
21:51:51:31:01:AA <- Valid.
It should restrict FF:FF:FF:FF:FF:FF full match.
What I have done so far is here.
^((?!01|FF|88|87|ff|00)[0-9a-fA-F]{2}([:-]|$)){6}$
If you want to escape anything that begins with 01|FF|88|87|ff|00 use this
pattern=/^(?=[^01|FF|88|87|ff|00])([0-9a-fA-F]{2}[:]){5}[0-9a-fA-F]{2}/gm
if you want to escape beginning 01|88|87|00 and only a full patter FF use this one instead
pattern=/^(?!01|88|87|00|FF:FF:FF:FF:FF:FF)([0-9a-fA-F]{2}[:]){5}[0-9a-fA-F]{2}/
You can try something like this:
var macAddressAllowed = function(macAddr) {
// regEX for valid MAC address
var regExp = "^([0-9a-fA-F][0-9a-fA-F]:){5}([0-9a-fA-F][0-9a-fA-F])$";
var regex = new RegExp(regExp);
var validMac = regex.test(macAddr);
if(!validMac){
return false;
}else{
macAddr = macAddr ? macAddr.toLowerCase() : '';
var macAllowed = (macAddr === 'ff:ff:ff:ff:ff:ff' || macAddr.split(':')[0] === '01');
return macAllowed ? false: true;
}
};

Block user from input with regex

I have a function which checks an input box with an regex string for max. 3 words and two spaces.
$('input.words_input__input_field').on("keyup", function(e) {
if (e.keyCode == 13) {
send_message();
}
var re = /^((([\'\-\+\s]\s*[a-zA-Z])?[a-zA-Z]*)){3}$/g;
var str = $('input.words_input__input_field').val();
var m;
while ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
send_text = str;
// View your result using the m-variable.
// eg m[0] etc.
}
console.log(m);
});
When the Regex applies on the input value the send_text will not be edited anymore. But I want to prevent the user from typing anymore into the input box.
Is there any way to create a block for the input so that the user cannot type in more than as "allowed" by the regex?
EDIT: I have some problems with this regex, so it works too perfect it should only prevent the user from typing in after three words and two spaces are in the input field. I have a code like this:
var test = /^((([\'\-\+\s]\s*[a-zA-Z])?[a-zA-Z]*)){3}$/g;
if (test.test($(this).val())) {
$(".input").val($(".input").val().replace(/\s/g, ""));
}
But it "kills" all whitespaces. And I only want to delete the whitespaces at the end. Any ideas?
Set the input to disabled with
$('input.words_input__input_field').prop('disabled', true);
Or store the .val() in a variable or a data object as long as it's valid and regenerate it from there if the regex is not met anymore.
EDIT:
The code below will let the user type 3 words, separated by commas. If anything is added that violates the regex, the input will be reset to the last value.
var p;
var f;
$(".inp").on('keyup',function(e){
var k = e.which;
var i = $(".inp").val();
if(k != 8 && k != 46){ // allow backspace and delete
if(i.search(/^[A-Za-z]+ [A-Za-z]+ [A-Za-z]+$/) >= 0){
f = true;
p = i;
}
else{
if(f){
$(".inp").val(p);
}
}
}
});
<input type="text" class="inp">
Fiddle

Checking regex expression on keypress

I would like to create my own plugin (without use any external libraries - it's for learning purpose) to validate text typed by user dynamically in regex test function.
In example I have regex pattern:
^.{2}$
And javascript function
$('#textbox').bind("keypress", function (event) {
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
Now, I want to type two dots into textbox, but after first keypress is fired, one dot doesn't match to the pattern and nothing happens because event is prevented.
My question: Is it possible to check if currently typed text matches with regex pattern?
Your regex only accept two dots (..), but you're testing a single character!
var regex = new RegExp("^.{2}$");
$('#textbox').bind("keypress", function (event) {
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
Wanna check current typed text when users finished typing? .. Look HERE
var alpha = /[ A-Za-z]/;
var numeric = /[0-9]/;
var alphanumeric = /[ A-Za-z0-9]/;
function validateKeypress(validChars) {
var keyChar = String.fromCharCode(event.which || event.keyCode);
return validChars.test(keyChar) ? keyChar : false;
}
The HTML will have to change to onkeypress="validateKeypress(alpha);"
You can try keydown as it will trigger as soon as you press a key and before character is displayed in textbox. So if it doesnot match with the pattern you can return out.
$('#textbox').bind("keyup", function (event) {
var user_input = getElementById ("your_input_id_here");
if (!regex.test(user_input)) {
return false;
}
});
So, essentially you should use onkeyup instead and you should check the whole user input, not just the last key
var in_put = document.getElementById("in_put"),
key = null;
in_put.addEventListener("keydown", match_input);
function match_input(e){
console.log("Key: "+e.key);
key = e.key;
console.log("Match: "+key.match(/a/i));//return array of match
if(key.match(/a/i)){
//code on succession.
}else{
//code on failure.
}
}
Note: Change /a/i with your /pattern/ig. It only check for input is
a/A.

allow space between two word using regular expression

I need to block special character except comma. So I am using code given below. Its is working but it is also removing space between two words. fiddle
var chars =/[(,\/\w)]/i;
$('input').keyup(function(e) {
var value = this.value;
var char = value[value.length-1];
if(char !== ' ' || value.length==1 || (value[value.length-2]!==' ' )){
if (!chars.test(char)) {
$(this).val(value.substring(0, value.length-1));
}
}
});
In terms of usability, manipulating the user's input as they're typing can be very frustrating. In addition, if the user types fast enough it doesn't work anyway (as mentioned by Daniel Knippers, above)
A better bet would be to validate the user's input and let them know in real-time if the input is invalid.
Try this code:
var regex =/^[\w\s\,]*$/i;
$('input').keyup(function(e) {
var message = regex.test(this.value) ? "" : "Error";
$('#message').html(message);
});
jsFiddle version
as far as i am understood, you wants that space should be allowed in txt box
so,
here is your ANSWER
you need to add space after \w
var chars =/[(,\/\w )]/i;
$('input').keyup(function(e) {
var value = this.value;
var char = value[value.length-1];
if(char !== ' ' || value.length==1 || (value[value.length-2]!==' ' )){
if (!chars.test(char)) {
$(this).val(value.substring(0, value.length-1));
}
}
});
please note that i have added space after \w, so the regexp is var chars =/[(,\/\w )]/i;

Categories

Resources