JS set input value by regex - javascript

I have simple input on my html and i want to when user putting text value in the input value was automatically set by my regex pattern
Example: I have time picker input
and I want the user when he enters numbers, the value is automatically formatted in the input.
How to do it with regex and replace function ?
I tried to do it this way, but in the end I just get the string that I enter.
console.log(value.replace(/^(([0-9]{1})|([0-1]{1}[0-9]{1})|([2]{1}[0-3]{1}))(([:]{1})?)(([0-5]{1}[0-9]?)?)$/g, ''));

If you are using a UI framework, refer to their documentation they would probably have a plugin to do it for you. Or if you want to do it on your own:
From the HTML side you can use type="time" attribute (please check the browser support for this).
And from JavaScript you can use something like ^([01]\d|2[0-3]):?([0-5]\d)$ on form submission for example.
const TIME_REGEX = /([01]\d|2[0-3]):?([0-5]\d)$/;
const myTimeElm = document.getElementById('myTime');
const outputElm = document.getElementById('output');
let timer;
outputElm.addEventListener('click', () => {
if (TIME_REGEX.test(myTimeElm.value)) {
outputElm.innerText = myTimeElm.value;
} else {
outputElm.innerText = "Error!"
}
});
#output {
cursor: pointer;
}
<input type="time" id="myTime" value="00:00">
<span id="output">click here!</span>
If you don't want to use HTML's type="time", consider using a mask for your input where you record the user's input and render the formatted output in a different component.
Since using the RegEx alone won't achieve the same user experience as you may want to workout the input's cursor position.
Or simple use a library that does that for you (Cleave.js for example)

Related

How to manually report an input tag to the user via JS?

Basically I want to create an effect like the one you get with required attributes:
(example from w3schools.com)
But since I'm not able to use something like type="email", because my patterns differ (and sometimes the input is used to add elements to an array), I want to check the validity manually via JavaScript and, if the inputted data isn't right, report it to the user as shown above.
Any ideas how to do it are highly appreciated!
Something like this might work.
const button = document.getElementById('btn') //use id of the button
button.addEventListener('click', handleButtonClick);
function handleButtonClick() {
const inputValue = document.getElementById('input').value
if (inputValue != null || inputValue !== '') {
//do your logic here
}
}
You can use oninvalid and onvalid
<input id="username" type="text" required="required"
oninvalid="this.setCustomValidity('Your alert')"
onvalid="this.setCustomValidity('')">

javascript : check if <input> is input-field

HTML5 comes with a lot of new types for
<input />
How can I detect if an input field is "a text field" (date, time, email, text, everything)
I do not want to write input[type='text'],input[type='xxx'] ...
You can use getAttribute to get whatever attribute you want (this includes type)
var input = document.getElementById('myinput');
var inputTYpe = input.getAttribute('type');
var isText = inputTYpe === 'text' || inputTYpe === '';
console.log('type is ', input.getAttribute('type'), ' is text = ', isText)
<input type="hey" id="myinput" />
CSS3 comes with a lot of new types for <input />
HTML5, not CSS3.
I do not want to write input[type='text'],input[type='xxx']
Unfortunately, I don't think you get a choice. But since the vast majority of them are text-like, you probably want to just call out the ones that aren't (like range, checkbox, radio, file, submit, image, reset, button — only one of which is new with HTML5).
Where possible, you'll want to isolate that to a single spot. You've mentioned CSS, which may make it difficult, but for instance if you were doing this in JavaScript, you'd want a single reusable function so you could update it as necessary.
function unameit(el) {
var words=['button','checkbox','hidden','image','radio','range','reset','submit'],tp=el.type.toLowerCase();
return words.indexOf(tp)<0;
}
If you want to differenciate between tags, you can check the tag by using
elementTag.tagName
For example, if you have a Input, you will get the text "INPUT"
And if you want to know what kind of imput is being used, you can check by looking at the attribute
elementTag.type

Display tooltip/message while input is invalid HTML/JS/CSS/Angularjs

I have an HTML input field where certain characters shouldn't be allowed. The functional part is solved, but I would like to display a tooltip/message next to the input field while it contains illegal characters.
I have a boolean which keeps track of this, but I've been unable to make a satisfactory tooltip/message.
I've tried tweaking uib-tooltip, but It requires the user to hover over the input area. I've tried making a span/div/label that's hidden/displayed based on the boolean, but my CSS skills aren't strong enough.
The app uses Angularjs and Bootstrap 3.
The input field is not part of a form.
where you catch that boolean just say to display the div next to input like
myDiv.visible = true;
Without knowing your exact Javascript, I can't really answer it directly.
I would do something like
function invalid() {
if (invalid = true) {
document.getElementById("alert").style.visibility = 'visible'
}
}
make sure the error message is set to hidden,
then have the checker function run on focus..
<input type="text" onfocus="invalid()">
https://jsfiddle.net/we67geke/1/
This comment by user Lex solved the problem.
You can manually set the visibility of the uib-tooltip using the
tooltip-is-open attribute. Simply use the same boolean you are using
to keep track of the invalid characters.
As you mentioned
The app uses Angularjs and Bootstrap 3.
I suggest that you should use Boostrap tooltip. Use $('#element').tooltip('show') and $('#element').tooltip('hide') with your flag to handle status of Tooltip.
I don't know how your codes work, my idea seems like:
HTML:
<input type=text (keypress)="eventHandler()"> // angular >= 2
<input type=text ng-keypress="eventHandler()"> // angular 1
Angular code:
eventHandler() {
if (isIllegal) {
$('#element').tooltip('show');
} else {
$('#element').tooltip('hide');
}
}
Something like that.
Bootstrap Tooltip: https://getbootstrap.com/docs/3.3/javascript/#tooltips

Warn on non-ASCII Characters in Django Form

I'm trying to add some client-side Ajax validation of my Django form. I want to warn users, as they are typing in a field, if any of the characters they just inputted are not ascii.
I originally put the basic python to check for ascii characters in my form's clean method. I don't want to do that, though, as I don't want to produce an error but rather just give a warning message and let the user continue with the rest of the form.
try:
field_value.decode('ascii')
except UnicodeEncodeError:
#raise forms.ValidationError("Non-ASCII characters may cause issues in registering your data. Consider removing these characters. You may still submit at your own risk.")
# Just want to show a warning so the user can still submit the form if they wish
I want to show a small warning under the field as the user is typing. I've tried using django-dajax, but am not sure. How can I do this?
EDIT:
To clarify, I want to show the warning before the user submits the form. So, as they are filling out the form...
Use
> <input type="text" pattern="^[\x20-\x7F]+$" id ....>
in html
Use JavaScript to validate that form field.
Example (using jQuery):
<form>
<input name="whatever" id="fieldId">
...
</form>
<script type="text/javascript">
/* Define a function to check the form field value */
function containsAllAscii(str) {
return /^[\000-\177]*$/.test(str); // returns true if all are ASCII characters. false otherwise.
}
/* Now a little jQuery */
$('#fieldId').on('change', function() {
str = $(this).val();
is_valid = containsAllAscii(str);
if (!is_valid) {
window.alert("There are Non-ASCII characters in the input field");
}
});
</script>
The above code will check the given field's value whenever it changes (i.e. loses focus). You can use .on('keyup', ... instead of .on('change', ... which will check the field's value as the user is typing.
Finally, the error message that is shown is just a browser alert. Which is crappy. You can display a beautiful error message, you just need to learn a little more of jQuery. But I hope I've given you a good starting point.
Credits:
The code for containsAllAscii function is taken from this answer by Juan Mendes.
In your django form, create a custom field and take advantage of the media class.
from django import forms
class MyWidget(forms.TextInput):
class Media:
css = {
'all': ('pretty.css',)
}
js = ('animations.js', 'actions.js')
and set the js to the javascript file you will use for validation. something along the lines of the the other answer
https://docs.djangoproject.com/en/1.9/topics/forms/media/

browser auto fill event

I am doing some website where I have a login form. I know people can save their usernames and passwords on these in their web browsers.
I need to show / hide a label (<label></label>). if the field is empty then the label has to appear, if there is any value in the field then the label has to hide,
but this doesn't work with the browser autocomplete, is there anyway I can track this?
I tried with:
jQuery.change();
but that doesn't work.
Is there anything I can do about this rather than turning autocomplete off?
The norm here is to use the placeholder attribute on the relevant input element:
<input type="text" placeholder="username">
username will be displayed within the input when there's no text, and hidden otherwise. If you're using this, then you should probably also use something like Modernizr to detect support and create a normal text label otherwise.
You have to manually trigger the change event:
$("#username")
.change(function () {
// do stuff on change (check for default)
})
.trigger("change");
or use some watermark library if you only want to toggle default text (or the placeholder attribute with Modernizr as aviraldg recommends).
This is very simple.
I use this for my site's text fields.
This coding is in Javascript text.
create a <form> with name and id = "comform" (you can change this later; just for reference).
create an <input type = "text" with name and id = "Message" (you can change this later; just for reference).
create a <div> with id = "ifsend" (you can change this later; just for reference).
Also create a variable to store the length in. var numbering (you can change this later; just for reference).
function counter() {
var numbering;
numbering = document.forms["comform"]["Message"].value.length;
if (numbering == 0) {
label();
}
if (numbering != 0) {
document.getElementById('ifsend').innerHTML="";
}
}
function label() {
document.getElementById('ifsend').innerHTML="Your form value is empty";
}

Categories

Resources