I have a Textbox which will only allow user to input date in mm-dd-yyyy format. If the date is valid, the user will be able to move focus out of the textbox but if it's invalid, the focus should remain inside the textbox until the user corrects it. Currently I am using regex to validate the textbox input and I am able to successfully keep focus inside the textbox in case of invalid date. The issue I am facing is, even when I am correcting the invalid date, the focus does not move out of the textbox.
var dateCheck = function() {
var value = $("#txtbox1").val()
if (/^(0[1-9]|1[0-2])-(0[1-9]|1\d|2\d|3[01])-(19|20)\d{2}$/.test(value)) {
$("#txtbox1").blur();
return true;
}
else {
$("#txtbox1").focus().on('blur', function () {
$(this).focus();
return false;
});
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" size="12" class="form-control" onfocusout="dateCheck()" id="txtbox1"/>
P.S : Using Datepicker is not part of the requirement, would have been much easier I know. Any leads regarding this would be appreciated.
Edit: I have found a working solution and have updated the code above, but this code works only in Chrome and not in IE11
This snipped checks if the date is valid and if it is correctly formatted.
var dateMMDDYYYRegex = "^[0-9]{2}/[0-9]{2}/[0-9]{4}$";
/* isValidData source: http://stackoverflow.com/questions/5812220/how-to-validate-a-date */
function isValidDate(s) {
var bits = s.split('/');
var d = new Date(bits[2], bits[0] - 1, bits[1]);
return d && (d.getMonth() + 1) == bits[0] && d.getDate() == Number(bits[1]);
}
var dateCheck = function() {
var value = $("#txtbox1").val();
if(value.match(dateMMDDYYYRegex) && isValidDate(value)){
$("#txtbox1").blur();
return true;
} else {
$("#txtbox1").focus().on('blur', function () {
$(this).focus();
return false;
});
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type="text" size="12" class="form-control" onfocusout="dateCheck()" id="txtbox1"/>
Personally I would consider using an input mask like this one to make it easier for the user to use your code. Also don't forget to validate the date serverside. I would use a libary called Carbon to phrase the date.
Reference to the code: Stackoverflow
You do not need the else part. You can use HTMLElement.blur()
to remove the focus from the element. You can easily pass this element to the function so that you can refer the current element inside the function. I will also suggest you to use oninput event instead of onfocusout.
Try the following way:
var dateCheck = function(el) {
var value = $(el).val();
if (/^(0[1-9]|1[0-2])-(0[1-9]|1\d|2\d|3[01])-(19|20)\d{2}$/.test(value)) {
el.blur();
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" size="12" class="form-control" oninput="dateCheck(this)" id="txtbox1"/>
You could use onblur event, instead of using onfocusout event. Please refer to the following code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
var dateCheck = function () {
var value = $("#txtbox1").val()
if (/^(0[1-9]|1[0-2])-(0[1-9]|1\d|2\d|3[01])-(19|20)\d{2}$/.test(value)) {
$("#txtbox1").blur();
}
else {
$("#txtbox1").focus();
}
};
</script>
<input type="text" size="12" class="form-control" onblur="dateCheck()" id="txtbox1" />
the output as below:
Related
I have multiple input fields and I want to limit them to accept numbers only in Vue.js.
I want do disable user from typing any characters except digits from 0-9.
I already did that successfully by doing this(this solution copy-paste proof):
Code in Vue.js template:
<input type="text" name="priceMax" class="input" #input="correctNumberInput" />
Method that removes everything except numbers:
correctNumberInput: function(event){
event.target.value = event.target.value.replace(/[^0-9]/g, "");
}
This worked perfectly fine on multiple fields.
Here comes the problem: For different reason, I needed to use v-model on these input fields. After adding v-model my method doesn't work anymore. I guess it's because v-model also uses input event under the hood. So only adding "v-model", stops it from working:
<input type="text" name="priceMax" class="input" #input="correctNumberInput" v-model="priceMax" />
I have few possible solutions in mind, but all of them include a lot of repeated code.
For example, I could add watchers for every input field, but that would be a lot of repeated code (because I would need to do it for every input field). I have 5 input fields, so basically I would need to write 5 almost identical watchers. I would like to avoid that if that is possible... For example:
watch:{
number(){
this.priceMax = this.priceMax.replace(/[^0-9]/g, "");
}
}
Is there any way I can solve it and make it as simple as my solution was without repeating code? It would be nice to also have solution that is copy-paste proof. All suggestions are welcome! Thanks in advance!
I've tried to test some code. Here what I have (link to the example):
<template>
<div>
<div>
<input
type="text"
name="priceMin"
class="input"
v-model="priceMin"
#input="correctNumberInput"
>
<label v-html="priceMin"></label>
</div>
<div>
<input
type="text"
name="priceMax"
class="input"
v-model="priceMax"
#input="correctNumberInput"
>
<label v-html="priceMax"></label>
</div>
</div>
</template>
<script>
export default {
name: "MyInput",
data: () => {
return {
priceMin: "",
priceMax: ""
};
},
methods: {
correctNumberInput: function(event, data) {
const name = event.target.name;
let value = String(this[name]).replace(/[^0-9]/g, "");
if (value) {
this[name] = parseInt(value, 10);
} else {
this[name] = "";
}
}
}
};
</script>
<style scoped>
input {
border: 1px solid black;
}
</style>
This is the code:
correctNumberInput: function(event, data) {
const name = event.target.name;
let value = String(this[name]).replace(/[^0-9]/g, "");
if (value) {
this[name] = parseInt(value, 10);
} else {
this[name] = "";
}
}
So I used your function, but I am not changing the event.target.value, I am changing the data. So I need to know the name of that data, that's why I use name attribute from input fields (const name = event.target.name;)
Update
If we have input type=number, then it has strange (empty) value inside #input callback. So it seems, better use keyboard filter (example here):
The main idea to have keyboard filter:
filterDigitKeys: function(event) {
const code = window.Event ? event.which : event.keyCode;
const isSpecial =
code === 37 ||
code === 39 ||
code === 8 ||
code === 46 ||
code === 35 ||
code === 36;
const isDigit = code >= 48 && code <= 57;
const isKeypad = code >= 96 && code <= 105;
if (!isSpecial && !isDigit && !isKeypad) {
// if not number or special (arrows, delete, home, end)
event.preventDefault();
return false;
}
}
And attach it to inputs:
<input type="number" min="0" name="numberInput" class="input"
v-model.number="numberInput" #keydown="filterDigitKeys">
Note: if we keep only #keydown handler, then we will not filter text insert into our inputs (but ctrl+v is not working anyway, only by mouse).
Maybe you can try this:
<input type="number" name="priceMax" class="input" #input="correctNumberInput" v-model.number="priceMax" />
From that site: click.
I would like to change this code to work also when Enter is pressed to be more clear i got an submit form and an text field following with the submit button that has to be clicked to submit but that doesn't help me out as i need the form to recognize when enter is pressed, what would be the change to sort it out?
submitButton.onclick = function() {
index = 0;
results = [];
username = usernameInput.value;
if ( username.length > 0 ) {
window.location.href = '//' + window.location.host + window.location.pathname + '#' + username;
usernameInput.disabled = true;
submitButton.disabled = true;
getExistence();
}
Also i got an issue with input validation, what change should i made to allow the form recognize and accept special characters?
usernameInput.onchange = function() {
this.value = this.value.replace(/[^a-z0-9]+/ig, '').slice(0, 40);
var urlUsername = window.location.href.match(/\#([0-9a-z]{1,40})$/i)
I would ask from you to be more specific as i am new to javascript coding, and my knowledge it's not enough to sort it easily.
First solution is to read this.
https://www.tjvantoll.com/2013/01/01/enter-should-submit-forms-stop-messing-with-that/
You get info why "button type="submit" is better way than adding that into JS.
I think, solution for your problem can be something like that:
<form>
<label for="age">Age:</label>
<input type="number" min="0" max="120" name="age" id="age">
<button id="child">Child</button>
<button id="adult">Adult</button>
</form>
<script>
(function() {
var age = document.getElementById('age');
age.addEventListener('keypress', function(event) {
if (event.keyCode == 13) {
event.preventDefault();
if (age.value > 20) {
document.getElementById('adult').click();
} else {
document.getElementById('child').click();
}
}
});
}());
</script>
In short, commenting your code:
submitButton.onclick = function() { ... your code
This work as you describe, onclick. You can have similar function with :
submitButton.onkeypress = function() { ... same code with checking keyCode as example above
Validation: the simplest way to create any Regex is by doing some real test. I'am personally prefer this site: https://regex101.com/
What "special" character you mean? Because nobody can help right now. More info in this particular example. You just don't need any RegEx for JS. Accept any char and do everything on backend.
I am not any kind of proficient in JavaScript.
So I wrote a simple function to use on HTML SELECT, but it doesn't work.
JavaScript:
<script type="text/javascript" language="JavaScript">
function changeFormAction() {
var value = document.getElementById("format");
if (value == "freeText") {
document.getElementById("regularExpression").setAttribute("disabled", false);
}
}
</script>
HTML:
<select id="format" name="customFieldType" onChange='changeFormAction()'>
...
</select>
<input id="regularExpression" type=text size=5 name="format" disabled="true">
Any help will be highly appreciated
value in your code contains the element "format". Usually, to get the value, you just add .value as suffix. But since this a select/dropdown you'll have to do:
var element = document.getElementById("format");
var value = element.options[element.selectedIndex].value;
var text = element.options[element.selectedIndex].text;
Now value and text will contain the different strings like below:
<option value="thisIsTheValue">thisIsTheText</option>
Use either to compare with. I'll use both below to show as an example:
function changeFormAction() {
var element = document.getElementById("format");
var sValue = element.options[element.selectedIndex].value;
var sText = element.options[element.selectedIndex].text;
if (sValue == "freeText" || sText == "freeText") {
document.getElementById("regularExpression").removeAttribute("disabled");
}
}
The issue is something else.. It does hit changeFormAction function on change of customField select list..
var value = document.getElementById("regularExpression");
is wrong usage..
you should use it as
var value = document.getElementById("regularExpression").value
And adding from comments for disabling it also can be
document.getElementById("regularExpression").removeAttribute("disabled");
This wont work because you are trying to fetch text box value using document.getElementById("regularExpression").value;
But on page load you are not having any thing as default value in text box
You might be needed to fetch value of select box.
I think you need something like this:
http://jsfiddle.net/ew5cwnts/2/
function changeFormAction(value) {
if (value == "freeText") {
document.getElementById("regularExpression").removeAttribute("disabled");
}
}
HTML:
<select name="customFieldType" onchange='changeFormAction(this.value)'>
Need to append a script to a text field in an 'enter postcode' field, which will actively check the content and pop up an alert. Blacklisting postcodes, basically.
Here is what I have:
HTML:
<input type="text" maxlength="20" size="25" value="" name="zipc" id="zipc">
JS:
jQuery("#zipc").ready(function () {
function BFPO(t) {
if (t.value.match(/\"BF1 3AA"/g)) {
alert('We cannot send parcels to BFPO addresses. Ever.');
t.value = t.value.replace(/\s/g,'');
}
}
});
Now, I'm aware that is doesn't work but how do I fully 'ready' an alert like this when you then select the next field to type in? Perhaps the use of indexOf()?
Any help would be great and thanks in advance.
I think you can use focusout function. check this out
Focusout jquery
and also you can use
blur() function as well
$('#textfieldid').blur(function() {
//logic
});
So here's the solution, if anyone was wondering:
jQuery('#zipc').focusout(function () {
var _val = jQuery(this).val();
var _array = ["BF1 3AA", "Some_postcode"];
for (var i = 0; i < _array.length; i++) {
if (_val.indexOf(_array[i]) != -1) {
alert('OH, snap! That\'s a BFPO postcode... We don\'t send stuff there. Bummer.');
jQuery('#zipc').val("");
}
}});
Fiddle:
http://jsfiddle.net/hslincoln/WbDpG/1/
I am looking for some date.parse() help for JavaScript. I have been searching different forums and sites and still have not been able to find a decent example of how to implement this. I am taking a beginning web design class and my instructor has asked for me to do this : "Set the placeholder text for the text box to “Enter a date.” Add an empty paragraph tag set to the document. In a separate JavaScript file code the event handler for the button to set the paragraph text to state whether or not the entered value is a recognizable date format. The Date.parse() method will return a number if passed a valid date string and the special value NaN (not a number) otherwise. NaN can be check for using the built-in function isNaN(). (You may want to refer to your online resources for more information on the Date object, NaN , and isNaN().)" I have been to a ton of websites that show the string but I need a dumbed down example of how to actually use it. here is my html code for the button:
<body>
<form>
<input type="text" id="dateTextInput" size="40" placeholder="Please Enter A Date">
<input type="button" id="addButton" value="Enter a Date">
</form>
<p></p>
</body>
and here is what I have for my .js file:
window.onload = init;
function init() {
var button = document.getElementById("addButton");
button.onclick = handleButtonClick;
}
function handleButtonClick() {
var textInput = document.getElementById("addDateButton");
var dateString = textInput.value;
if (dateString == "") {
alert("Please enter a date");
}
else {
my issue is after my else, if that is even appropriate. I am lost as how to implement the date.parse function. I know it's date.parse(variable) but not sure how to make sure it can be a valid format. Dates can be entered in numerous ways. Should I make an array of possible dates and validate it that way? Or is there a simpler option? A link to a great guide would also be helpful, if an answer cannot be provided here. Thank you for your time.
Update; here is what I am using now. It halfway works. It alerts for an empty set. I just can't get the parse to alert:
function handleButtonClick() {
var textInput = document.getElementById("dateTextInput");
var dateString = textInput.value;
var dateValue = Date.parse(dateString);
var valid = !isNaN(dateValue);
if (dateString == "") {
alert("Please enter a date");
} else {
return(valid);
}
}
I hope everthing is understandable.
<form id="dateForm">
<!-- pattern just allow such format X.X.XXXX Or XX.XX.XXXX Or X.XX.XXXX Or XX.X.XXXX -->
<input type="text" id="dateTextInput" size="40" pattern="^\d{1,2}.\d{1,2}.\d{4,4}$" placeholder="Please Enter A Date">
<input type="submit" id="addButton" value="Enter a Date">
</form>
<script>
// onsubmit ist just called when dateTextInput is empty or has got valid date
document.getElementById('dateForm').onsubmit = function(e){
e.preventDefault(); // avoid to reload page
var date = document.getElementById('dateTextInput').value;
if(date === ''){ // always use === because == is sometimes buggy
alert('Please enter a date');
}
else{
var convertedDate = date.split('.'); // -> ['03','06','1985']
convertedDate = new Date(convertedDate[2],convertedDate[1],convertedDate[0]);
console.log(convertedDate.getTime()); // I think you wanted to get Milliseconds, but this works just as well
}
return false;
};
</script>
When the order of the day, month and year is not right, then just edit the pattern of the input-field and this codeline:
convertedDate = new Date(convertedDate[2],convertedDate[1],convertedDate[0]);
Dates can be entered in numerous ways. Should I make an array of possible dates and validate it that way?
No array. You should just accept what Date.parse does accept:
whether the entered value is a recognizable date format. The Date.parse() method will return a number if passed a valid date string and NaN otherwise.
"recognizable" does refer to Date.parse capatibilites I'd say. It's trivial to implement then:
var dateValue = Date.parse(dateString);
var valid = !isNaN(dateValue);
// grab the paragraph
if (valid)
// set the paragraph text accordingly
else
// output something different