Forcing form text to be lower-case - javascript

How could I force the text in the "username" text input to be lower-case regardless of what user types?
<div class="register">
<label for="username">Select username:</label>
</div>
<div class="registerform">
<input name="username" class="registerfont" type="text"
id="username" maxlength="15" style="height:35px; width:300px">
</div>

in CSS:
form input[type="text"] {
text-transform: lowercase;
}
otherwise in JS:
var text="this is my text.";
var lowercase=text.toLowerCase();

You have to use javascript. I have an example here: http://jsfiddle.net/xCfdS/3/
HTML:
<input type="text" id="txt" onkeyup="return forceLower(this);"/>​
Javascript:
function forceLower(strInput)
{
strInput.value=strInput.value.toLowerCase();
}​

You can use something as
<input autocapitalize="none" ></input>
and it should work in the latest browsers
For more details check this link

Using jquery assuming that the input ID is username
$(document).ready(function(){
$("#username").on('change keyup paste',function(){
$(this).val($(this).val().toLowerCase());
})
})

#fdiv_bug's answer is good except for the issues mentioned in the comments of their answer. Using the input event instead of the keyup event fixed those issues for me.
HTML:
<input oninput="this.value=this.value.toLowerCase()"/>​
Javascript:
element.addEventListener('input',function(){this.value=this.value.toLowerCase()});​

Combining a bit of everyone's answer to here simplify things.
Use CSS to avoid any flashing and for display purposes.
input[type="username"] {
text-transform: lowercase;
}
Now, because this ONLY effects DISPLAY of the text in the browser, we need to also change the value of the input.
Add an event listener to the input.
const usernameInput = document.querySelector('input[type="username"]');
usernameInput.addEventListener("input", function(e){
e.target.value = e.target.value.toLowerCase();
});
We can send this to the sever like normal and, like others have mentioned, check server-side to make sure a malicious user didn't send us UpPPercaSe input.

This is my suggestion, it's based on the answer from #fdiv-bug & #ali-sheikhpour:
Add text-transform: lowercase; for this field.
input[type="email"] {
text-transform: lowercase;
}
catch "change" event on this field and transform value to lowercase by (String)toLowerCase function.
var upperCaseMatch = /[A-Z]/;
var events = {
CHANGE: 'change'
};
$(function() {
$(document).on('change', 'input[type="email"]', function() {
var value = $(this).val();
if (!upperCaseMatch.test(value)) {
return;
}
$(this).val(value.toLowerCase());
});
});
Hope its useful for you.

I use this simple code :
<input type="text" onkeyup="this.value = this.value.toUpperCase();">

Use onchange instead
<input name="username"
onchange="this.value = this.value.toUpperCase();"
style="text-transform: lowercase; height:35px; width:300px"
class="registerfont"
type="text"
id="username"
maxlength="15"
>

Old question. New answer.
With HTML5 Form Validation now (2021) supported across all major browsers, it is relatively simple to force lowercase text on an input field, client side, using the pattern attribute. (The pattern attribute is supported by all but Opera Mini at the time of writing).
HTML:
<label>Field Name (lowercase letters only)</label>
<input type="text" pattern="[a-z]" placeholder="Field Name (lowercase letters only)">
Note: The below follows from but gets semi out of scope of the question.
Forcing lowercase on an email address field (which is what brought me to this question) seems to be more risky as using pattern/rejex to validate email addresses is fairly complicated and there are potential issues associated with implementing pattern in conjunction with type="email".
The above aside, for my use case, the following pattern was sufficient:
<label>Email Address (lowercase letters only)</label>
<input type="email" pattern="[^A-Z]+" placeholder="Email Address (lowercase letters only)">
The rejex expression [^A-Z]+ allows any characters that aren't capitals. I leave the actual email address validation to the browser via type="email". I tested this on desktop in Chrome, Firefox, Edge and IE11 and all worked fine.

setInterval() will run if the user pastes something in
setInterval(function(){
let myinput = document.getElementById('myinput');
//make lowercase
myinput.value = myinput.value.toString().toLowerCase();
//remove spaces (if you want)
myinput.value = myinput.value.toString().replace(' ', '');
//force specific characters
myinput.value = myinput.value.toString().replace(/[^a-z0-9\/\-_]/, '');
}, 10);
because this is a loop function using .replace(), replacing only first occurrence at a time, but still looping all of them, this appears to animate removing spaces on pasted text.

Using jquery assuming that the input ID is username:
$(document).ready(function(){
$("#username").on('input', function(){
$(this).val( $(this).val().toLowerCase() );
})
});

Related

Validate phone number on blur using pattern

I have a form and on blur I would like to check if the phone number is in the right format, but it seems to fail every time.
$('.form-control').blur(function(){
if(!this.validity.valid){
$(this).addClass('emptyField');
}
else{
$(this).removeClass('emptyField');
}
})
.emptyField { background:red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" class="form-control" name="fill_phone" placeholder="xxx-xxx-xxxx" required>
Valid phone numbers should be XXX-XXX-XXXX but it just seems to fail every time. I use the same code on a email field and that will validate just fine.
Is the Content being dynamically rendered ? When I was rendering dynamic content I had to change the syntax to get this to work. here is the syntax you can try. if its not static then j query does not find it with the above syntax. this is what worked for me. This tells jquery to check the page for dynamic content.
S(document).on("blur", ".form-control", event => {
if (!this.validity.valid) {
$(this).addClass("emptyField");
} else {
$(this).removeClass("emptyField");
}
});
OK, So I figured it out and the problem was caused by something unexpected. The form was being included with php. the form had template variables in it like this, value="{fill_phone}".
Before presenting the form to the visitor the template variables were being replace using str_replace, like this, $form = str_replace('{fill_phone}', '', $form); , I would dynamically run through all the variables on the form.
Once I manually removed all the template variables from the form everything worked fine. I would love for someone to explain this to me as I am to a loss why this would break the form validation. Remember the email validation worked fine but the phone number validation was not working for me.
All is working now. Thank you for all your help.
So you need to use a reg ex with JS or HTML5 Validate Pattern. Let me show you two examples.
1
function phonenumber(inputnumber) {
var phone = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if(inputnumber.value.match(phone)) {
return true;
}
else {
alert("message");
return false;
}
}
HTML5 Validate
In HTML5 you can use <input type='tel'>
<input type='tel'
pattern='[\+]\d{2}[\(]\d{2}[\)]\d{4}[\-]\d{4}'
title='Phone Number
(Format: +99(99)9999-9999)'/>
OR
<label for="phone">Enter your phone number:</label>
<input type="tel" id="phone" name="phone"
pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
required>
<small>Format: 123-456-7890</small>
`
Link To MDN HTML5 Phone Input

HTML Form Field - How to require an input format

What I want to do here is require that phone numbers be entered into my HTML form as (XXX) XXX-XXXX and that SS Numbers are entered as XXX-XX-XXXX. Thats it.
The only reason I am doing this is so that the form submission results are consistent and easy exported to Excel.
I have been told to use Javascript to do this but perhaps I am not advanced enough to understand all the steps in doing that.
Can someone please point me in the right direction here keeping in mind that I am a beginner?
Wow thank you so much Ethan and #suman-bogati! I am ALMOST there now! The field now pops an error stating to use the correct format of 555-55-5555. Thats great. But no matter what I enter enter into that field the popup persists. I tried 555-55-5555 and also 555555555 and neither are accepted. Here is the HTML for that field:
<label>
Social Security Number:
<input id="ssn" required pattern="^d{3}-d{2}-d{4}$"
title="Expected pattern is ###-##-####" />
</label>
</div>
<script>$('form').on('submit', function(){
$(this).find('input[name="SocialSecurity"]').each(function(){
$(this).val() = $(this).val().replace(/-/g, '');
});
$(this).find('input[name="ssn"]').each(function(){
$(this).val() = $(this).val().replace(/-/g, '');
});
});</script>
<br />
The easiest way to do that is by simply using multiple fields:
<div>
Phone:
(<input type="text" name="phone-1" maxlength="3">)
<input type="text" name="phone-2" maxlength="3">-
<input type="text" name="phone-3" maxlength="4">
</div>
<div>
SSN:
<input type="text" name="ssn-1">-
<input type="text" name="ssn-2">-
<input type="text" name="ssn-3">
</div>
While this approach is certainly easy, it's not great. The user has to press tab or click on each field to enter the data, and there's nothing (other than common sense) from preventing them from entering things other than digits.
I always feel that, when it comes to validation, the less you can get in the user's way, the better. Let them enter their phone number in whatever format they like, then you scrub it, removing everything but digits. That way the user can enter "5555551212" or "(555) 555-1212", but the database will always hold "5555551212".
The other thing to consider is that HTML5 offers some nice specific types for phone numbers (but not SSNs). A modern browser will take care of all the input validation and, even better, mobile devices will show the numeric keypad instead of the whole keypad.
Given that, the best way to display your form is this:
<div>
<label for="fieldPhone">Phone: </label>
<input type="tel" id="fieldPhone" placeholder="(555) 555-1212">
</div>
<div>
<label for="fieldSsn">SSN: </label>
<input type="text" id="fieldSsn" name="ssn" placeholder="555-55-5555" pattern="\d{3}-?\d{2}-?\d{4}">
</div>
If the user has a modern browser, this will handle the user side of the input validation for you. If they don't, you'll have to use a validation library or polyfill. There's a whole list of HTMl5 form validation polyfills here:
https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills#wiki-web-forms
So all that remains is now to normalize your data when you save it to the database.
The ideal place to do that would be the back end; it doesn't say where your form is going, though, so maybe you don't have any say on how things are processed on the back end. So you can do this in the front end instead. For example, using jQuery:
$('form').on('submit', function(){
$(this).find('input[type="tel"]').each(function(){
$(this).val() = $(this).val().replace(/[\s().+-]/g, '');
});
$(this).find('input[name="ssn"]').each(function(){
$(this).val() = $(this).val().replace(/-/g, '');
});
});
This is not a perfect approach either: if you do validation in this function, and the validation fails, the user will see his or her input replaced by the normalized versions, which can be disconcerting.
The best approach would be to use AJAX and .serialize; not only can you have better control over the UI, but you can do all the validation you want. But that's probably a little beyond what you need to do right now.
Note that phone validation is the trickiest. The HTML5 phone validation is very permissive, allowing people to enter international phone numbers, which can have pretty complicated formats. Even people in the US will sometimes enter phone numbers like "+1 (555) 555-1212", and then you have 8 digits instead of 7. If you really want to restrict them to 7 digits, you'll have to add your own custom validation:
/^\(?\d{3}\)?[.\s-]?\d{3}[.\s-]\d{4}$/
This will cover all the common variations people use (periods, spaces, dashes, parentheses), and still allow only 7-digit US phone numbers.
Here's a jsfiddle demonstrating the HTML5 validation and normalization:
http://jsfiddle.net/Cj7UG/1/
I hope this helps!
Use this patterns if you want two patterns should be matched as asked in question.
//for (XXX)-XXX-XXXX
var pattern = /^\(\d{3}\)\-\d{3}\-\d{4}$/;
//for XXX-XXX-XXXX
var pattern2 = /^\d{3}\-\d{3}\-\d{4}$/;
DEMO
Here is a complete solution using jquery and jquery tools validator:
regex pattern that would handle both cases is :
^(\d{3}-|(\d{3})\s)\d{2}-\d{4}$
HTML:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript"></script>
<script src="http://cdn.jquerytools.org/1.2.7/full/jquery.tools.min.js" type="text/javascript"></script>
<link href="http://jquerytools.org/media/css/validator/form.css" type="text/css" rel="stylesheet">
<script>
$(function() {
$("#myform").validator();
});
</script>
</head>
<body>
<form id="myform">
<input type="text" name="name" pattern="^(\d{3}-|\(\d{3}\)\s)\d{2}-\d{4}$" maxlength="30" />
<br>
<input type="submit" name="submit" value="submit" />
</form>
</body>
Click here for demo on jsfiddle
use can use sth like this:
<html>
<head>
</head>
<body>
<input type="text" id="ok">
<script>
document.getElementById("ok").onkeypress = function(e){
var keycodes = new Array(0,48,49,50,51,52,53,54,55,56,57);
var was = false;
for(x in keycodes){
if(keycodes[x] == e.charCode){
was = true;
break;
}
else{
was = false;
};
};
var val = this.value;
if(was === true){
switch(val.length){
case 3:
if(e.charCode !== 0){
this.value += "-";
}
break;
case 6:
if(e.charCode !== 0){
this.value += "-";
}
break;
default:
if(val.length > 10 && e.charCode !== 0){return false;};
break;
};
val += e.charCode;
}
else{
return false;
};
};
</script>
</body>
I tested it in ff

html & js text field data (DD-MM-YYYY) validation

In my form I have a text field in which user type date. Good habit tells me to not let user to put anything other then dgit and '-' symbol in the field. However i have a bit problem with implementing such feature. So far I Have a field which accept only digits. If user try to put in field letter, this letter is being removed. But the point is to create (DD-MM-YYYY)format so field have to accept '-' symbol. Here is my code:
<input type="text" name="test3" placeholder='DD-MM-YYYY' onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')"/>
i tried put |\- into regex but with no success. Can anyone point me where I am doing mistake?
use thie regex
/^\d{4}-\d{2}-\d{2}$|[^\d-]|-\d{2}-\d*-/
you can also
**/^\d{4}-\d{2}-\d{2}$|[^\d-]|-\d{2}-\d*-/.test(input.value)**
HTML5 has another approach for you:
<input type="date" name="test3">
The browser is responsible for the formatting of the date presentation, though.
You can try something like
<input type="text" name="test3" placeholder='DD-MM-YYYY' onkeyup="if (/[^\d-]/g.test(this.value)) this.value = this.value.replace(/[^\d-]/g,'')" onchange="validate(this)"/>
function validate(el){
var regex = /^(0?[1-9]|[12][0-9]|3[01])-(0?[1-9]|1[012])-\d{4}$/;
if(!regex.test(el.value)){
alert('invalid date');
el.value = '';
}
}
Demo: Fiddle
You can do this with HTML5
see my jsfidle: http://jsfiddle.net/H7tMZ/2/
<form>
<input type="text" name="date" pattern="\d{1,2}-\d{1,2}-\d{4}" placeholder="dd-mm-jjjj"/>
<button type="submit"/>
</form>

Adding value to an Input field on click

I have this structure on form,
<input type="test" value="" id="username" />
<span class="input-value">John Smith</span>
Fill Input
when user click on the Fill Input ,
the data from span which has class input-value will be added to value, after clicking a tag the code should be look like this,
<input type="test" value="john Smith" id="username" />
<span class="input-value">John Smith</span>
Fill Input
there are many forms element/input on the single page.
You can do it like this:
$('a.fill-input').click(function() {
$(this).prevAll("input:first").val($(this).prev(".input-value").text());
});
Instead of looking only for the classes, this looks for the span and input just before the button you clicked...this means it works no matter how many of these you have on the page.
Unlike your example though, the value will be John Smith, with the same casing as it has in the span, if you actually want lower case, change .text() to .text().toLowerCase().
$('a.fill-input').click(function() {
$('#username').val($('.input-value.').text());
});
This should suffice for all inputs that you have so structured. It doesn't depend on the names of the elements. Note that prevAll returns the elements in reverse order so you need to look for the first input, not the last in the preceding inputs.
$('.fill-input').click( function() {
var $input = $(this).prevAll('input[type=test]:first');
var $value = $(this).prev('span.input-value');
$input.val($value.text());
});
try:
$('a.fill-input').click(function(e){
$('#username').val($('span.input-value').text());
e.preventDefault();
return false;
});

How do I make an HTML text box show a hint when empty?

I want the search box on my web page to display the word "Search" in gray italics. When the box receives focus, it should look just like an empty text box. If there is already text in it, it should display the text normally (black, non-italics). This will help me avoid clutter by removing the label.
BTW, this is an on-page Ajax search, so it has no button.
Another option, if you're happy to have this feature only for newer browsers, is to use the support offered by HTML 5's placeholder attribute:
<input name="email" placeholder="Email Address">
In the absence of any styles, in Chrome this looks like:
You can try demos out here and in HTML5 Placeholder Styling with CSS.
Be sure to check the browser compatibility of this feature. Support in Firefox was added in 3.7. Chrome is fine. Internet Explorer only added support in 10. If you target a browser that does not support input placeholders, you can use a jQuery plugin called jQuery HTML5 Placeholder, and then just add the following JavaScript code to enable it.
$('input[placeholder], textarea[placeholder]').placeholder();
That is known as a textbox watermark, and it is done via JavaScript.
http://naspinski.net/post/Text-Input-Watermarks-using-Javascript-(IE-Compatible).aspx
or if you use jQuery, a much better approach:
http://digitalbush.com/projects/watermark-input-plugin/
or code.google.com/p/jquery-watermark
You can set the placeholder using the placeholder attribute in HTML (browser support). The font-style and color can be changed with CSS (although browser support is limited).
input[type=search]::-webkit-input-placeholder { /* Safari, Chrome(, Opera?) */
color:gray;
font-style:italic;
}
input[type=search]:-moz-placeholder { /* Firefox 18- */
color:gray;
font-style:italic;
}
input[type=search]::-moz-placeholder { /* Firefox 19+ */
color:gray;
font-style:italic;
}
input[type=search]:-ms-input-placeholder { /* IE (10+?) */
color:gray;
font-style:italic;
}
<input placeholder="Search" type="search" name="q">
You can add and remove a special CSS class and modify the input value onfocus/onblur with JavaScript:
<input type="text" class="hint" value="Search..."
onfocus="if (this.className=='hint') { this.className = ''; this.value = ''; }"
onblur="if (this.value == '') { this.className = 'hint'; this.value = 'Search...'; }">
Then specify a hint class with the styling you want in your CSS for example:
input.hint {
color: grey;
}
The best way is to wire up your JavaScript events using some kind of JavaScript library like jQuery or YUI and put your code in an external .js-file.
But if you want a quick-and-dirty solution this is your inline HTML-solution:
<input type="text" id="textbox" value="Search"
onclick="if(this.value=='Search'){this.value=''; this.style.color='#000'}"
onblur="if(this.value==''){this.value='Search'; this.style.color='#555'}" />
Updated: Added the requested coloring-stuff.
I posted a solution for this on my website some time ago. To use it, import a single .js file:
<script type="text/javascript" src="/hint-textbox.js"></script>
Then annotate whatever inputs you want to have hints with the CSS class hintTextbox:
<input type="text" name="email" value="enter email" class="hintTextbox" />
More information and example are available here.
Here's a functional example with Google Ajax library cache and some jQuery magic.
This would be the CSS:
<style type="text/stylesheet" media="screen">
.inputblank { color:gray; } /* Class to use for blank input */
</style>
This would would be the JavaScript code:
<script language="javascript"
type="text/javascript"
src="http://www.google.com/jsapi">
</script>
<script>
// Load jQuery
google.load("jquery", "1");
google.setOnLoadCallback(function() {
$("#search_form")
.submit(function() {
alert("Submitted. Value= " + $("input:first").val());
return false;
});
$("#keywords")
.focus(function() {
if ($(this).val() == 'Search') {
$(this)
.removeClass('inputblank')
.val('');
}
})
.blur(function() {
if ($(this).val() == '') {
$(this)
.addClass('inputblank')
.val('Search');
}
});
});
</script>
And this would be the HTML:
<form id="search_form">
<fieldset>
<legend>Search the site</legend>
<label for="keywords">Keywords:</label>
<input id="keywords" type="text" class="inputblank" value="Search"/>
</fieldset>
</form>
I hope it's enough to make you interested in both the GAJAXLibs and in jQuery.
Now it become very easy.
In html we can give the placeholder attribute for input elements.
e.g.
<input type="text" name="fst_name" placeholder="First Name"/>
check for more details :http://www.w3schools.com/tags/att_input_placeholder.asp
For jQuery users: naspinski's jQuery link seems broken, but try this one:
http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints/
You get a free jQuery plugin tutorial as a bonus. :)
I found the jQuery plugin jQuery Watermark to be better than the one listed in the top answer. Why better? Because it supports password input fields. Also, setting the color of the watermark (or other attributes) is as easy as creating a .watermark reference in your CSS file.
This is called "watermark".
I found the jQuery plugin jQuery watermark which, unlike the first answer, does not require extra setup (the original answer also needs a special call to before the form is submitted).
Use jQuery Form Notifier - it is one of the most popular jQuery plugins and doesn't suffer from the bugs some of the other jQuery suggestions here do (for example, you can freely style the watermark, without worrying if it will get saved to the database).
jQuery Watermark uses a single CSS style directly on the form elements (I noticed that CSS font-size properties applied to the watermark also affected the text boxes -- not what I wanted). The plus with jQuery Watermark is you can drag-drop text into fields (jQuery Form Notifier doesn't allow this).
Another one suggested by some others (the one at digitalbrush.com), will accidentally submit the watermark value to your form, so I strongly recommend against it.
Use a background image to render the text:
input.foo { }
input.fooempty { background-image: url("blah.png"); }
Then all you have to do is detect value == 0 and apply the right class:
<input class="foo fooempty" value="" type="text" name="bar" />
And the jQuery JavaScript code looks like this:
jQuery(function($)
{
var target = $("input.foo");
target.bind("change", function()
{
if( target.val().length > 1 )
{
target.addClass("fooempty");
}
else
{
target.removeClass("fooempty");
}
});
});
You could easily have a box read "Search" then when the focus is changed to it have the text be removed. Something like this:
<input onfocus="this.value=''" type="text" value="Search" />
Of course if you do that the user's own text will disappear when they click. So you probably want to use something more robust:
<input name="keyword_" type="text" size="25" style="color:#999;" maxlength="128" id="keyword_"
onblur="this.value = this.value || this.defaultValue; this.style.color = '#999';"
onfocus="this.value=''; this.style.color = '#000';"
value="Search Term">
When the page first loads, have Search appear in the text box, colored gray if you want it to be.
When the input box receives focus, select all of the text in the search box so that the user can just start typing, which will delete the selected text in the process. This will also work nicely if the user wants to use the search box a second time since they won't have to manually highlight the previous text to delete it.
<input type="text" value="Search" onfocus="this.select();" />
I like the solution of "Knowledge Chikuse" - simple and clear. Only need to add a call to blur when the page load is ready which will set the initial state:
$('input[value="text"]').blur();
You want to assign something like this to onfocus:
if (this.value == this.defaultValue)
this.value = ''
this.className = ''
and this to onblur:
if (this.value == '')
this.value = this.defaultValue
this.className = 'placeholder'
(You can use something a bit cleverer, like a framework function, to do the classname switching if you want.)
With some CSS like this:
input.placeholder{
color: gray;
font-style: italic;
}
I'm using a simple, one line javascript solution which works great. Here is an example both for textbox and for textarea:
<textarea onfocus="if (this.value == 'Text') { this.value = ''; }" onblur="if (this.value == '') { this.value = 'Text'; }">Text</textarea>
<input type="text" value="Text" onfocus="if (this.value == 'Text') { this.value = ''; }" onblur="if (this.value == '') { this.value = 'Text'; }">
only "downside" is to validate at $_POST or in Javascript validation before doing anything with the value of the field. Meaning, checking that the field's value isn't "Text".
You can use a attribute called placeholder=""
Here's a demo:
<html>
<body>
// try this out!
<input placeholder="This is my placeholder"/>
</body>
</html>
$('input[value="text"]').focus(function(){
if ($(this).attr('class')=='hint')
{
$(this).removeClass('hint');
$(this).val('');
}
});
$('input[value="text"]').blur(function(){
if($(this).val() == '')
{
$(this).addClass('hint');
$(this).val($(this).attr('title'));
}
});
<input type="text" value="" title="Default Watermark Text">
Simple Html 'required' tag is useful.
<form>
<input type="text" name="test" id="test" required>
<input type="submit" value="enter">
</form>
It specifies that an input field must be filled out before submitting the form or press the button submit.
Here is example
User AJAXToolkit from http://asp.net

Categories