I am finding a way to make all the text boxes in the website only accept roman characters. Is there any easy way to do it globally.
Thanks in advance.
In modern browsers <input> accepts an attribute called pattern. This allows to restrict the valid characters in a given field.
input:invalid {
background-color:red;
}
<form>
<input type="text" pattern="[a-zA-Z\s\.\-_]+" />
<button type="submit">Submit</button>
</form>
For all other browsers you can find all form field via jQuery, check if a pattern-attribute exists, and check it against the value of a given field. You may also replace disallowed characters:
$('form').on('keyup blur','input',function() {
if ($(this).val() && $(this).attr('pattern')) {
//var pattern = new RegExp('^'+$(this).attr('pattern')+'$', 'g');
//$(this).toggleClass('invalid', pattern.match(!$(this).val()));
var pattern = new RegExp($(this).attr('pattern').replace(/\[/,'[^'), 'g');
$(this).val($(this).val().replace(pattern,''));
}
});
input:invalid {
background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<form>
<input type="text" pattern="[a-zA-Z\s\.\-_]+" />
<button type="submit">Submit</button>
</form>
Oh, you still want to validate form inputs on the server-side. All HTML- or Javascript-stuff does not prevent all visitors of your site to submit broken stuff.
I will refer to the marked answer for the following question for the regex which filters out non-roman characters:
How to detect non-roman characters in JS?
Spoiler: the regex is /[^\u0000-\u024F\u1E00-\u1EFF\u2C60-\u2C7F\uA720-\uA7FF]/g
Now all you need is a little bit of tinkering with jQuery:
var myInputId = "#foo"; // Or whatever you wish to use.
var input = $(myInputId);
var exp = /[^\u0000-\u024F\u1E00-\u1EFF\u2C60-\u2C7F\uA720-\uA7FF]/g;
input.blur(function() {
input.value = input.value.replace(exp, "");
});
Include this snippet into your master page for example:
<script>
$(function(){
$('input[type=text],textarea').keypress(function(e){
var char = String.fromCharCode(e.which || e.charCode);
var rgx = /[\u0000-\u007F]/;
if (rgx.test(char) == false)
return false;
})
})
</script>
Here is my idea based on #fboes answer.
I also needed to show user whats wrong, so there is error message showing but with no redundancy when typing couple of forbidden characters in a row.
//I wanted first to assign pattern attr to every input in form but when it's happening, all "\" chars are removed from regex therefore - it doesn't work, so I had to add it in templates for every input.
let isIncorrect = false;
scope.checkPattern = function(e) {
// I don't want to allow Chineese, cyrylic chars but some other special - yes
var pattern = new RegExp('[a-zA-Z\s\.\-_äÄöÖüÜßąćęłńóśźżĄĆĘŁŃÓŚŹŻ]+', "g");
if ($(e).is(':valid')){
return true
} else {
$(e).val($(e).val().replace(pattern,''));
return false
}
};
scope.removeAlert = function (e){
$(e).parent().find('.text-danger').remove();
isIncorrect = false;
}
// unallowed characters in order inputs
$('.my-form').on('keyup blur','input',function(e) {
if (!scope.checkPattern($(this))) {
if (!isIncorrect){
// show this error message but only once (!) and for specified period of time
$(this).parent().append('<p class="text-danger">Only latin characters allowed</p>');
isIncorrect = true;
}
setTimeout(scope.removeAlert, 3000, $(this));
}
});
Related
I have a problem that I want to validate input field using RegExp(). Allows entering digits, characters and special character "_" to get the last string: regex3_example. When pressing the space key, "_" will be displayed. Hope everybody help please. Thank you!
document.querySelector('#input').addEventListener('input', function () {
var text = this.value;
if (re.test(text)) {
console.log("Valid");
} else {
console.log("Invalid");
}
$(document).keypress(function (event) {
if (event.keyCode === 32) {
var re = new RegExp("^[a-zA-Z_]");
var insert_string = text+'_';
let insert_text = insert_string.trim();
$('#key').val(insert_string);
}
});
});
I don't use jquery, but i can help. If you don't need to process your input data but only validade for user, you can use the prop pattern in your HTML tag.
<input
type="text"
pattern="\w*_\w{1,}"
title="Try the pattern test_test"/>
In this case, when you click on Button submit, the page will prenvent this action and show in this input the message passed on the prop title.
Hope help you, see ya!
I have found some code for a chat system. I am going to be using it as a child-friendly (so I can't be blamed for anything) global chat. The way the code works is by checking the input to see if it contains any word from an array, if it does then the program will display something to a <ol> tag, for me to see if it works. Otherwise is does nothing.
JQUERY
var banned_words = {
'songs': ['hello', 'sorry', 'blame'],
'music': ['tempo', 'blues', 'rhythm']
};
function contains(words) {
return function(word) {
return (words.indexOf(word) > -1);
};
};
function getTags(input, banned_words) {
var words = input.match(/\w+/g);
return Object.keys(banned_words).reduce(function(tags, classification) {
var keywords = banned_words[classification];
if (words.some(contains(keywords)))
tags.push(classification);
return tags;
}, []);
};
// watch textarea for release of key press
$('#sendie').keyup(function(e) {
$('#tags').empty();
var tags = getTags($(this).val().toLowerCase(), banned_words);
var children = tags.forEach(function(tag) {
$('#tags').append($('<li>').text(tag));
});
if (e.keyCode == 13) {
var text = $(this).val();
var maxLength = $(this).attr("maxlength");
var length = text.length;
// send
if (length <= maxLength + 1) {
chat.send(text, name);
$(this).val("");
} else {
$(this).val(text.substring(0, maxLength));
}
}
});
HTML
<form id="send-message-area">
<p style="text-align:center">Your message: </p>
<input id="sendie" maxlength = '100' />
</form>
<ol id="tags">
</ol>
But, what I'm also wanting to do is check if the input value contains phrases from the array so I can ban phrases that are too sensitive for children. How can I add this in, or is there another more efficient way to check the input?
UPDATE
I have already tried to place the phrase directly into the banned_words (I changed them as this post would get flagged for inappropriate language) and using the hexadecimal character for the space-bar. None of these worked.
You can try either of the following since the space is also a known charachter:
test 1:
Just put your phrase between quotes such as 'cry baby','red apple' etc.
sometimes it does not work, you can try
test 2:
replace the space with the hexidecimal character \x20 such as 'cry\x20baby','red\x20apple'
I hope one or both of these works for you.
I have done some more research and have found a cool plugin for JQuery. It's called jQuery.profanityFilter. It uses a json file filled with sensative words.
Link to github download: https://github.com/ChaseFlorell/jQuery.ProfanityFilter
I have a form in which is a field (#domain).
Here I want the customer to add their own domain name. Often I see that they input wrong, even thought the instructions are short and clear.
To make it more user friendly, and to avoid errors - I'd like to add a validator or auto corrector.
This is a jquery and bootstrap environment.
This is the solution I have made for now:
http://jsfiddle.net/Preben/ew1qoky9/1/
<form>
<input placeholder="input your domain (WITHOUT http:// and www.)" class="form-control" name="domain" type="text" autocomplete="off" id="domain" style="max-width:320px">
</form>
and the javascript:
$('#domain').keypress(function (e) {
var regex = new RegExp("^[a-zA-Z0-9\-_.]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
});
This removes all special caracters and spaces on the fly. However without telling the customer.
Customers still input http:// and http://www. - and I'd like to auto-remove these too.
Can I add something in the regex or js to make this happen? - Or what is a suggested working solution?
Is there a way to show a message/ alert if the customer enters a special caracter? Like "Please use only a-z, 0-9 and dots. If your domain has special caracters, please enter the ACE-version of your domain name." - Either a bootstrap alarm, or a standard js alert?
PS: I found this: Regex for dropping http:// and www. from URLs about removing the above from urls, but I don't understand how to use this in my code. I am very thankful for suggestions. Please play with the fiddle :-)
Per your code, user cannot type special characters like :// but user can paste it. To handle such cases, you can validate it on blur event. Following is the fiddle depicting same. Also I have added a simple check for"http", and will show error if http is entered. You can configure per your requirement.
Code
(function() {
var regex = new RegExp("^[a-zA-Z0-9\-_.]+$");
$('#domain').keypress(function(e) {
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
$("#lblError").text("Please use only a-z, 0-9 and dots.").fadeIn();
e.preventDefault();
return false;
});
$("#domain").on("blur", function(e) {
var str = $(this).val();
if (regex.test(str)) {
if (str.indexOf("http") >= 0) {
$("#lblError").text("Domain name cannot have HTTP in it.").fadeIn();
return false;
}
$("#lblError").fadeOut();
} else {
$("#lblError").text("Please use only a-z, 0-9 and dots.").fadeIn();
return false
}
});
})()
.error {
color: red;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<input placeholder="input your domain (WITHOUT http:// and www.)" class="form-control" name="domain" type="text" autocomplete="off" id="domain" style="max-width:320px">
<p class="error" id="lblError"></p>
</form>
Here you go:
$('#domain').on('input', function() {
rawInput = $(this).val();
console.log(rawInput);
cleanInput = rawInput.replace('www.', '');
cleanInput = cleanInput.replace('http://', '');
cleanInput = cleanInput.replace('https://', '');
console.log(cleanInput);
$(this).val(cleanInput);
});
See it in action here:
https://jsbin.com/birunuyeso/edit?html,js,console,output
Look at your JavaScript console and you'll see what it's doing. In production you can obviously remove any of the lines that use console.log().
so i have been looking all over the internet for some simple javascript code that will let me give an alert when a field is empty and a different one when a # is not present. I keep finding regex, html and different plugins. I however need to do this in pure Javascript code. Any ideas how this could be done in a simple way?
And please, if you think this question doesn't belong here or is stupid, please point me to somewhere where i can find this information instead of insulting me. I have little to no experience with javascript.
function test(email, name) {
}
Here if you want to validate Email, use following code with given regex :
<input type="text" name="email" id="emailId" value="" >
<button onclick = "return ValidateEmail(document.getElementById('emailId').value)">Validate</button>
<script>
function ValidateEmail(inputText){
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(inputText.match(mailformat)) {
return true;
}
else {
alert("You have entered an invalid email address!");
return false;
}
}
</script>
Or if you want to check the empty field, use following :
if(trim(document.getElementById('emailId').value)== ""){
alert("Field is empty")
}
// For #
var textVal = document.getElementById('emailId').value
if(textVal.indexOf("#") == -1){
alert(" # doesn't exist in input value");
}
Here is the fiddle : http://jsfiddle.net/TgNC5/
You have to find an object of element you want check (textbox etc).
<input type="text" name="email" id="email" />
In JS:
if(document.getElementById("email").value == "") { // test if it is empty
alert("E-mail empty");
}
This is really basic. Using regexp you can test, if it is real e-mail, or some garbage. I recommend reading something about JS and HTML.
function test_email(field_id, field_size) {
var field_value = $('#'+field_id+'').val();
error = false;
var pattern=/^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if(!pattern.test(field_value)){
error = true;
$('#'+field_id+'').attr('class','error_email');
}
return error;
}
This will check for empty string as well as for # symbol:
if(a=="")
alert("a is empty");
else if(a.indexOf("#")<0)
alert("a does not contain #");
You can do something like this:
var input = document.getElementById('email');
input.onblur = function() {
var value = input.value
if (value == "") {
alert("empty");
}
if (value.indexOf("#") == -1) {
alert("No # symbol");
}
}
see fiddle
Although this is not a solid soltuion for checking email addresses, please see the references below for a more detailed solution:
http://www.regular-expressions.info/email.html
http://www.codeproject.com/Tips/492632/Email-Validation-in-JavaScript
---- UPDATE ----
I have been made aware that there is no IE available to target, so the input field needs to be targeted like so:
document.getElementsByTagName("input")
Using this code will select all input fields present on the page. This is not what are looking for, we want to target a specific input field. The only way to do this without a class or ID is to selected it by key, like so:
document.getElementsByTagName("input")[0]
Without seeing all of your HTML it is impossible for me to know the correct key to use so you will need to count the amount of input fields on the page and the location of which your input field exists.
1st input filed = document.getElementsByTagName("input")[0]
2nd input filed = document.getElementsByTagName("input")[1]
3rd input filed = document.getElementsByTagName("input")[2]
4th input filed = document.getElementsByTagName("input")[3]
etc...
Hope this helps.
So I have a textbox which allows a max entry of 5 characters.
The user should enter the time in the format hh:mm or hhmm , into the textbox.
Supposing the user enters 1:2:3 or 1::2 etc, then it should show an alert message('Incorrect time format')
Is there any way I can check all other occurences of : EXCEPT for the first : , and alert the user?
(This needs to be done within a javascript function)
This is what I used to check for non-digit values(excluding :) entered into textbox:
<script type='text/javascript'>
function getClks(){
...
var re=":";
var found = clks.match(re);
if (clks.match(/^[0-9:]/)){
alert('Invalid time value');
}
if (found=:){
var splitime = clks.split(":");
var hours = splitime[0];
var mins = splitime[1];
......
}
}
</script>
Unless you have a very good reason to change the user's input. I would recommend only alerting the user that their input doesn't match the correct format.
If you really want to remove characters, you can use the replace function with some regex to remove the extra : chars.
You can use search or match to test whether the input is in the correct format.
Something like /^\d{1,2}:\d{2}$/ should work.
try to use this jquery plugin: http://digitalbush.com/projects/masked-input-plugin/
It will mask your textbox:
$("#hour").mask("99:99");
#alexl's jQuery plugin is probably enough, but for completeness sake..
Outside jQuery contexts I'd use a RegExp, /([0-9][0-9]):([0-9][0-9])/, and test the number string like so:
var timestr = /* .. get the text .. */
if(timestr.match(/([0-9][0-9]):([0-9][0-9])/) {
console.log('Good number string');
} else {
console.log('Bad number string');
}
Everyone else explained what to do. Here's a more concrete example of how to use it.
var regex = new RegExp("\\d{2}[:]\\d{2}");
if (regex.test(input)) {
var array = input.split(":");
var hours = array[0];
var minutes = array[1];
} else {
alert("malformed input");
}
You could do something like this
markup
<input id="myinput" maxlength="5" type="text" />
<input type="button" onclick="test()" value="test" id="testbtn" />
js
var re = new RegExp("^([0-1][0-9]|[2][0-3])(:([0-5][0-9])){1,2}$");
var myInput = document.getElementById('myinput');
function test(){
alert(re.test(myInput.value)); //alerts true if the input is well-formed
}
example => http://jsfiddle.net/steweb/rRZLx/