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/
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 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));
}
});
I am being frustrated by a regular expression to mask the input field. I want to Limit input to hh:mm AM|PM format and I can't get this regex to work.
I use this regex in conjunction with a jquery tool from www.ThimbleOpenSource.com. It was the filter_input.js tool or whatever.
It seems to work for a simple regular expression but the one I came up with doesn't seem to work. This is my jsFiddle test link below.
jsFiddle
I have made a jsfiddle example, based on the regular expression of the answer von Yuri:
http://jsfiddle.net/Evaqk/
$('#test1, #test2').blur(function(){
var validTime = $(this).val().match(/^(0?[1-9]|1[012])(:[0-5]\d) [APap][mM]$/);
if (!validTime) {
$(this).val('').focus().css('background', '#fdd');
} else {
$(this).css('background', 'transparent');
}
});
First of all, if you using it for input field, you should never let users input date or time information using text fields and hoping it will be in strict format.
But, if you insist:
/^(0?[1-9]|1[012])(:[0-5]\d) [APap][mM]$/
This regex will validate time in AM/PM format.
You can't do that with that plugin because here you need to check each character.
HTML:
<form>
<p>When?</p>
<input type="text" id="test1" placeholder="hh:mm(AM|PM)"/>
</form>
JavaScript:
$("#test1").keypress(function(e) {
var regex = ["[0-2]",
"[0-4]",
":",
"[0-6]",
"[0-9]",
"(A|P)",
"M"],
string = $(this).val() + String.fromCharCode(e.which),
b = true;
for (var i = 0; i < string.length; i++) {
if (!new RegExp("^" + regex[i] + "$").test(string[i])) {
b = false;
}
}
return b;
});
Example
So I'm pretty sure this is solved by now, but I was recently struggling with this and couldn't find an answer fast enough. I'm using Bootstrap Validator (bootstrapvalidator.com by #nghuuphuoc) in conjunction with Eonasdan's DateTimepicker to validate an hour (PS: You can disable the date in Eonasdan's plugin).
Since Bootstrap Validator doesn't yet have a validator for time, you have to use a Regex. This one worked perfectly for me:
^([0-1]?[0-9]|2[0-3]):[0-5][0-9] [APap][mM]$
the follwing function return (true/false) value
function CheckTime(HtmlInputElement) {
var dt = HtmlInputElement.value;
return (/(0?[1-9]|1[0-2]):[0-5][0-9] ?[APap][mM]$/.test(dt));
}
Check this solution too.
<!DOCTYPE html>
<html>
<body>
<p>This demo used to validate time with 12 hours format</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var regexp = /^(0?[1-9]|1[012])(:[0-5]\d) [APap][mM]$/;
var res = regexp.test('12:00 AM'); //try with alphabets or wrong format
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
Basically, i need a code that constantly checks for how many times a particular string appears within a textarea everytime the user keys in a letter.
<textarea name="t_update" cols="50" rows="5" id="t_update" style="width:30%"
onKeyUp="check()" ></textarea>
<script>
function check(){
var cText = document.getElementById('t_update').value;
if (cText.match("abc")){
//Do something
}else{
//Do something else.
}
alert(cText.match("abc").length);
}
</script>
The current code i have only returns one even if i have a more than one match. Any help would be appreciated.
use match with a regular expression and a global
cText.match(/abc/g).length
//test
cText = "aaabbbbcccabcabchalloabc"
Firebug Console
cText = "aaabbbbcccabcabchalloabc" cText.match(/abc/g).length
>> 3
You can simply use split on your string like this:
function check(){
var cText = document.getElementById('t_update').value,
matches = cText.split('abc').length-1;
if (matches){
//Do something
}else{
//Do something else.
}
alert(matches);
}