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>
Related
I've decided to use a textbox for getting the users date of birth, I'm trying to make this textbox so it restricts the users input into DD/MM/YYYY, What i'm trying to get is to that the slash(/) is fixed within the textbox. The user won't want to have the type the "/" so I'm trying to get it fixed in the textbox
This is what I'm trying to achieve
|____/____/___|
my code so far is just a basic textbox but here it is anyway
<label for="title">Date of Birth</label>
<input type="text" name="dateofbirth" id="dateofbirth">
</div>
With HTML5 you could simply use the date input type:
<input type="date" name="dateofbirth" id="dateofbirth">
Here's the MDN reference: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date
I think this is what you're looking for:
How to do date masking using javascript (without JQuery)?
If you check the Pratik Shah answer there's the format you were looking for and it seems to work.
Code:
<input
type="text"
name="date"
placeholder="dd/mm/yyyy"
onkeyup="
var v = this.value;
if (v.match(/^\d{2}$/) !== null) {
this.value = v + '/';
} else if (v.match(/^\d{2}\/\d{2}$/) !== null) {
this.value = v + '/';
}"
maxlength="10"
>
It works on my Firefox 52.0.2
Hope it helps.
This may be what you're looking for.
<input type="date" name="dateofbirth" id="dateofbirth">
Bear in mind that this won't work in certain browsers -- Firefox and older IE versions.
You can try maskedInput plugin for jQuery. It is basically what you are looking for. https://github.com/digitalBush/jquery.maskedinput
Now I have something like this:
<input type="text" ng-model="cell.location">
What I want is while you put 'ABC' in this field, this field will become disabled status, I know I can put a boolean param to control it via its controller.
However what I expect is something like this:
<input type="text" ng-disabled="{{cell.location = 'ABC'}}" ng-model="cell.location">
Which is clearer and simpler, unfortunately this approach doesn't work as expected, it will assign 'ABC' to this field rather than disable it. is that possible to implement in this kind of way?
Thanks.
Use this with ==:
<input type="text" ng-disabled="cell.location == 'ABC'" ng-model="cell.location" />
Instead of:
<input type="text" ng-disabled="{{cell.location = 'ABC'}}" ng-model="cell.location">
Angular doc
Use this without {{}}:
<input type="text" ng-disabled="cell.location == 'ABC'" ng-model="cell.location" />
Instead of:
<input type="text" ng-disabled="{{cell.location = 'ABC'}}" ng-model="cell.location">
form code:
<form class="form" name ="custRegistration" id="custRegistration" onsubmit="return submitAlbum(this)" action="download.jsp" method="post" >
<p class="email">
<label for="budget">Expected Budget :</label>
<input type="text" name="budget" id="budget"/>
</p>
<p class="submit">
<label for="download" id="freetrail">Download 30 day free trial</label>
<input type="submit" value="Submit" />
</p>
</form>
i want to validate email-ids with the extension which are checked in the above image and block rest of the email-id extensions using javascript..any help would be appreciated??
(\w+\.)*\w+#(\w+\.)+[A-Za-z]+
this regex is email check basic.
you may use regex for this case, follow regex:
((\w+\.)*\w+)#(\w+\.)+(com|kr|net|us|info|biz)
okay , get all the values of checked items in an array (at least this much you should have been able to do by now)
now let the array be ["com","net"]
var arr = ["com","net"];
var str = arr.join("|")
var re = new RegExp("^\w+#\w+\.("+str+")$");
console.log(re);
the regex I have used is the most basic of all, you can change it according to your needs. Another answer on SO suggests "^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$" to be a more complete email validator. So you can change your second last line to :
var re = new RegExp("^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.("+str+")$");
this code will give you the regex you need to validate your email.
Now you can simply do regex test to see which emails pass your validation.
happy coding!
You can also use above regex ( aelor's )as
[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.(COM|ORG|BIZ|CO)
include your all extentions using pipe separator .
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
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() );
})
});