Regex pattern for preventing leading whitespace in HTML input - html

<input type="text" pattern="^[a-zA-Z1-9].*">
How can I restrict the following input element from having leading whitespace, ie, it should always start with a character except a whitespace.
This answer suggested I use pattern="^[a-zA-Z1-9].*" but it doesn't seem to work.
EDIT:
It works only if I wrap it in a form tag and a submit button. Clicking the button triggers the error. But I want to be able to restrict users from entering whitespace on the input box itself.

To achieve this without a form-tag we can use a JavaScript live input filter like this:
var noLeadingSpace = /^\w.*$/;
$("input")
.data("oldValue", "")
.bind("input propertychange", function() {
var $this = $(this);
var newValue = $this.val();
if (!noLeadingSpace.test(newValue))
return $this.val($this.data("oldValue"));
return $this.data("oldValue", newValue);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />

It does work, but it will be validated if you try to send a form.
function myValidator(v){
var input = document.getElementById('uglyWay')
if(input){
input.value = input.value.replace(/ /g, '')
}
}
<form>
<input id="uglyWay" oninput='myValidator()' type="text" pattern="^[a-zA-Z1-9].*">
<button type="submit">Send</button>
</form>

The Following Regex mentioned in question Works without wrapping inside form tag
input[type="text"]:valid{
background:green;
}
input[type="text"]:invalid{
background:red;
}
<input type="text" pattern="^[a-zA-Z1-9].*">

Related

Form button not working in IE11

I have created a form with a submit button, the submit button is outside the actual form but its targeting the form using the form attribute for example.
<form id="myform">
</form>
<button form="myform"></button>
I apologize for the week example. This is working accross all browsers except IE 11. IE 8-10 is working 100%. Any ideas on how I can fix this. I prefer not writing scripts. I can do this with jQuery but I prefer to just keep it clean if possible
This is a solution with just a click event and a line of css. ( Minimal )
If your button has to be outside the form due to User Interface design.
I would suggest you add an input submit/button inside the form:
<form id="myform">
<input type="button" value="Submit" class="myButton" />
</form>
<button id="outerBtn">Submit</button>
Hide the input:
.myButton {display:none;} OR {visibility:none;}
Use jQuery to trigger click the input button inside the form:
$('#outerBtn').on('click', function(e){
e.preventDefault();
$('.myButton').trigger('click');
});
Just some quick answer. Should be alright.
If you do not want to write script, I would suggest you just keep your input button/submit inside the form.
<form id="form-any-name">
<input type="button" value="Submit" class="myButton" />
</form>
<button type="submit">Submit</button>
<script type="text/javascript">
$(document).ready(function() {
$('button[type=\'submit\']').on('click', function() {
$("form[id*='form-']").submit();
});
});
</script>
Simply include document on ready submit catcher you can place that code in main js file since we catching dinamicaly form id starting with form- so in other pages you can have the different foms:)
I would like to post my answer as this post helped me a lot and I came with an idea that works if you want to add the "button outside the form" functionality on older browsers.
I use JQuery but I dont think I would be a major problem to use pure JS as it's not complicated code.
Just create a class just as some of the answers suggested here
.hiddenSubmitButton {
display: none;
}
$("body").on("click", "button[form]", function () {
/*This will get the clicks when make on buttons with form attribute
* it's useful as we commonly use this property when we place buttons that submit forms outside the form itself
*/
let form, formProperty, formAttribute, code, newButtonID;
formProperty = $(this).prop("form");
if (!(formProperty === null || formProperty === "")) {//Most browsers that don't wsupport form property will return null others ""
return; //Browsers that support the form property won't continue
}
formAttribute = $(this).attr("form");
form = $("#" + formAttribute);
newButtonID = formAttribute + "_hiddenButton";
if (document.getElementById(newButtonID) !== null) {
$("#" + newButtonID).click();
return;
}
code = '<input id="' + newButtonID + '" class="hiddenSubmitButton" type="submit" value="Submit" />';
$(form).append(code);
setTimeout(function () {
$("#" + newButtonID).click();
}, 50);
});
One thing I like about creating buttons outside the form is that they allow us to custom the design more easily and we can use this code and it will work on old browsers and also, the browser will use its HTML form validator.
IE understands 'for', you can use "label for=''".
<label for="form_one_submit">Button one</label>
<form action="" id="form_one">
<span></span>
<input type="submit" id="form_one_submit" style="visibility:hidden;">
</form>

Form upper case input

I have a form where users enter a surname. In case if they type it in all small case letters i want it to show up properly E.g. the user types in the word 'smith' but the response page will show 'Smith' instead?
<p>Name: <input type="text" name="surname"></p>
All you need to do is capitalize your input, look snippet below:
P.S. - I edited your p class so you don't get confused when you apply the style to input. Because it could affect every input you may have in your site if was applied to input itself.
.surname input {
text-transform: capitalize
}
<p class="surname">Name:
<input type="text" name="surname">
</p>
EDIT: here is jQuery solution, that will solve your problem with response page.
jQuery.fn.capitalize = function() {
$(this[0]).keyup(function(event) {
var box = event.target;
var txt = $(this).val();
var start = box.selectionStart;
var end = box.selectionEnd;
$(this).val(txt.replace(/^(.)|(\s|\-)(.)/g, function($1) {
return $1.toUpperCase();
}));
box.setSelectionRange(start, end);
});
return this;
}
$('.surname input').capitalize();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<p class="surname">Name:
<input type="text" name="surname">
</p>
You could check the input value in the browser using Javascript and modify the value if the first character is not upper case. I'd recommend JQuery for that. Or use CSS to capitalize it.
Also note that browser-side Javascript or CSS transformations don't guarantee that a POST of your form will only send capitalized input; whatever happens in the browser can be bypassed. Hence, server-side you will want to do the same (capitalize if necessary).
Speaking of surnames, would you capitalize "van der Vaart"?
CSS:
text-transform: capitalize;
<p>Name: <input type="text" style="text-transform: capitalize;" name="surname"></p>

Making 'file' input element mandatory (required)

I want to make (an HTML) 'file' input element mandatory: something like
<input type='file' required = 'required' .../>
But it is not working.
I saw this WW3 manual which states 'required' attribute is new to HTML 5. But I am not using HTML 5 in the project I am working which doesn't support the new feature.
Any idea?
Thanks to HTML5, it is as easy as this:
<input type='file' required />
Example:
<form>
<input type='file' required />
<button type="submit"> Submit </button>
</form>
You can do it using Jquery like this:-
<script type="text/javascript">
$(document).ready(function() {
$('#upload').bind("click",function()
{
var imgVal = $('#uploadfile').val();
if(imgVal=='')
{
alert("empty input file");
return false;
}
});
});
</script>
<input type="file" name="image" id="uploadfile" size="30" />
<input type="submit" name="upload" id="upload" class="send_upload" value="upload" />
As of now in 2017, I am able to do this-
<input type='file' required />
and when you submit the form, it asks for file.
You could create a polyfill that executes on the form submit. For example:
/* Attach the form event when jQuery loads. */
$(document).ready(function(e){
/* Handle any form's submit event. */
$("form").submit(function(e){
e.preventDefault(); /* Stop the form from submitting immediately. */
var continueInvoke = true; /* Variable used to avoid $(this) scope confusion with .each() function. */
/* Loop through each form element that has the required="" attribute. */
$("form input[required]").each(function(){
/* If the element has no value. */
if($(this).val() == ""){
continueInvoke = false; /* Set the variable to false, to indicate that the form should not be submited. */
}
});
/* Read the variable. Detect any items with no value. */
if(continueInvoke == true){
$(this).submit(); /* Submit the form. */
}
});
});
This script waits for the form to be submitted, then loops though each form element that has the required attribute has a value entered. If everything has a value, it submits the form.
An example element to be checked could be:
<input type="file" name="file_input" required="true" />
(You can remove the comments & minify this code when using it on your website)
var imgVal = $('[type=file]').val();
Similar to Vivek's suggestion, but now you have a more generic selector of the input file and you don't rely on specific ID or class.
See this demo.
Some times the input field is not bound with the form.
I might seem within the <form> and </form> tags but it is outside these tags.
You can try applying the form attribute to the input field to make sure it is related to your form.
<input type="file" name="" required="" form="YOUR-FORM-ID-HERE" />
I hope it helps.
All statements above are entirely correct. However, it is possible for a malicious user to send a POST request without using your form in order to generate errors. Thus, HTML and JS, while offering a user-friendly approach, will not prevent these sorts of attacks. To do so, make sure that your server double checks request data to make sure nothing is empty.
https://www.geeksforgeeks.org/form-required-attribute-with-a-custom-validation-message-in-html5/
<button onclick="myFunction()">Try it</button>
<p id="geeks"></p>
<script>
function myFunction() {
var inpObj = document.getElementById("gfg");
if (!inpObj.checkValidity()) {
document.getElementById("geeks")
.innerHTML = inpObj.validationMessage;
} else {
document.getElementById("geeks")
.innerHTML = "Input is ALL RIGHT";
}
}
</script>

Make an html number input always display 2 decimal places

I'm making a form where the user can enter a dollar amount using an html number input tag. Is there a way to have the input box always display 2 decimal places?
So if someone else stumbles upon this here is a JavaScript solution to this problem:
Step 1: Hook your HTML number input box to an onchange event
myHTMLNumberInput.onchange = setTwoNumberDecimal;
or in the html code if you so prefer
<input type="number" onchange="setTwoNumberDecimal" min="0" max="10" step="0.25" value="0.00" />
Step 2: Write the setTwoDecimalPlace method
function setTwoNumberDecimal(event) {
this.value = parseFloat(this.value).toFixed(2);
}
By changing the '2' in toFixed you can get more or less decimal places if you so prefer.
an inline solution combines Groot and Ivaylo suggestions in the format below:
onchange="(function(el){el.value=parseFloat(el.value).toFixed(2);})(this)"
An even simpler solution would be this (IF you are targeting ALL number inputs in a particular form):
//limit number input decimal places to two
$(':input[type="number"]').change(function(){
this.value = parseFloat(this.value).toFixed(2);
});
What other folks posted here mainly worked, but using onchange doesn't work when I change the number using arrows in the same direction more than once. What did work was oninput. My code (mainly borrowing from MC9000):
HTML
<input class="form-control" oninput="setTwoNumberDecimal(this)" step="0.01" value="0.00" type="number" name="item[amount]" id="item_amount">
JS
function setTwoNumberDecimal(el) {
el.value = parseFloat(el.value).toFixed(2);
};
The accepted solution here is incorrect.
Try this in the HTML:
onchange="setTwoNumberDecimal(this)"
and the function to look like:
function setTwoNumberDecimal(el) {
el.value = parseFloat(el.value).toFixed(2);
};
Pure html is not able to do what you want. My suggestion would be to write a simple javascript function to do the roudning for you.
You can use Telerik's numerictextbox for a lot of functionality:
<input id="account_rate" data-role="numerictextbox" data-format="#.00" data-min="0.01" data-max="100" data-decimals="2" data-spinners="false" data-bind="value: account_rate_value" onchange="APP.models.rates.buttons_state(true);" />
The core code is free to download
I used #carpetofgreenness's answer in which you listen for input event instead of change as in the accepted one, but discovered that in any case deleting characters isn't handled properly.
Let's say we've got an input with the value of "0.25". The user hits "Backspace", the value turns into "0.20", and it appears impossible to delete any more characters, because "0" is always added at the end by the function.
To take care of that, I added a guard clause for when the user deletes a character:
if (e.inputType == "deleteContentBackward") {
return;
}
This fixes the bug, but there's still one extra thing to cover - now when the user hits "Backspace" the value "0.25" changes to "0.2", but we still need the two digits to be present in the input when we leave it. To do that we can listen for the blur event and attach the same callback to it.
I ended up with this solution:
const setTwoNumberDecimal = (el) => {
el.value = parseFloat(el.value).toFixed(2);
};
const handleInput = (e) => {
if (e.inputType == "deleteContentBackward") {
return;
}
setTwoNumberDecimal(e.target);
};
const handleBlur = (e) => {
if (e.target.value !== "") {
setTwoNumberDecimal(e.target);
}
};
myHTMLNumberInput.addEventListener("input", handleInput);
myHTMLNumberInput.addEventListener("blur", handleBlur);
Look into toFixed for Javascript numbers. You could write an onChange function for your number field that calls toFixed on the input and sets the new value.
What I didn't like about all these solutions, is that they only work when a form is submitted or input field is blurred. I wanted Javascript to just prevent me from even typing more than two decimal places.
I've found the perfect solution for this:
<!DOCTYPE html>
<html>
<head>
<script>
var validate = function(e) {
var t = e.value;
e.value = (t.indexOf(".") >= 0) ? (t.substr(0, t.indexOf(".")) + t.substr(t.indexOf("."), 3)) : t;
}
</script>
</head>
<body>
<p> Enter the number</p>
<input type="text" id="resultText" oninput="validate(this)" />
</body>
https://tutorial.eyehunts.com/js/javascript-limit-input-to-2-decimal-places-restrict-input-example/
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js" integrity="sha512-pHVGpX7F/27yZ0ISY+VVjyULApbDlD0/X0rgGbTqCE7WFW5MezNTWG/dnhtbBuICzsd0WQPgpE4REBLv+UqChw==" crossorigin="anonymous"></script>
<input type="text" class = 'item_price' name="price" min="1.00" placeholder="Enter Price" value="{{ old('price') }}" step="">
<script>
$(document).ready(function() {
$('.item_price').mask('00000.00', { reverse: true });
});
</script>
give out is 99999.99

Can div with contenteditable=true be passed through form?

Can <div contenteditable="true">Some Text</div> be used instead of texarea and then passed trough form somehow?
Ideally without JS
Using HTML5, how do I use contenteditable fields in a form submission?
Content Editable does not work as a form element. Only javascript can allow it to work.
EDIT: In response to your comment... This should work.
<script>
function getContent(){
document.getElementById("my-textarea").value = document.getElementById("my-content").innerHTML;
}
</script>
<div id="my-content" contenteditable="true">Some Text</div>
<form action="some-page.php" onsubmit="return getContent()">
<textarea id="my-textarea" style="display:none"></textarea>
<input type="submit" />
</form>
I have tested and verified that this does work in FF and IE9.
You could better use:
<script>
function getContent(){
document.getElementById("my-textarea").value = document.getElementById("my-content").innerText;
}
</script>
NOTE: I changed innerHTML to innerText. This way you don't get HTML elements and text but only text.
Example: I submited "text", innerHTML gives the value: "\r\n text". It filters out "text" but it's longer then 4 characters.
innerText gives the value "text".
This is useful if you want to count the characters.
Try out this
document.getElementById('formtextarea').value=document.getElementById('editable_div').innerHTML;
a full example:-
<script>
function getContent() {
var div_val = document.getElementById("editablediv").innerHTML;
document.getElementById("formtextarea").value = div_val;
if (div_val == '') {
//alert("option alert or show error message")
return false;
//empty form will not be submitted. You can also alert this message like this.
}
}
</script>
`
<div id="editablediv" contenteditable="true">
Some Text</div>
<form id="form" action="action.php" onsubmit="return getContent()">
<textarea id="formtextarea" style="display:none"></textarea>
<input type="submit" />
</form>
`
Instead of this, you can use JQuery (if there is boundation to use JQuery for auto-resizing textarea or any WYSIWYG text editor)
Without JS it doesn't seem possible unfortunately.
If anyone is interested I patched up a solution with VueJS for a similar problem. In my case I have:
<h2 #focusout="updateMainMessage" v-html="mainMessage" contenteditable="true"></h2>
<textarea class="d-none" name="gift[main_message]" :value="mainMessage"></textarea>
In "data" you can set a default value for mainMessage, and in methods I have:
methods: {
updateMainMessage: function(e) {
this.mainMessage = e.target.innerText;
}
}
"d-none" is a Boostrap 4 class for display none.
Simple as that, and then you can get the value of the contenteditable field inside "gift[main_message]" during a normal form submit for example. I'm not interested in formatting, therefore "innerText" works better than "innerHTML" for me.