I have this sample:
function ssnFormat() {
$("#ssn").on('blur change', function() {
text = $(this).val().replace(/(\d{3})(\d{2})(\d{4})/, "$3-$2-$4");
if ($(this).val() == '' || $(this).val().match(text) || $(this).val().length == 0) {
$(this).removeClass('valid').addClass('invalid');
} else {
$(this).removeClass('invalid').addClass('valid');
}
});
}
$("#ssn").on('blur change', function() {
ssnFormat();
});
.valid {
border: 1px solid blue;
}
.invalid {
border: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="required-input" id="ssn" maxlength="9" type="text" name="ssn" placeholder="123-45-6789">
What I want to do these things are:
If I write the following text I want to validate this format 123-12-1234
If I write 123456789 I want to transform when click outside input in this format
123-12-1234
I tried to do this by using the function below but don't work
$("#ssn").on("click", function() {
var thisVal = $(this).val();
var value = thisVal.replace(/[^\/\d]/g,''); //here is a problem
$(this).val(value);
});
Can you please help me solve this problem?
Thanks in advance!
Try this
function myFunc() {
var patt = new RegExp("\d{3}[\-]\d{2}[\-]\d{4}");
var x = document.getElementById("ssn");
var res = patt.test(x.value);
if(!res){
x.value = x.value
.match(/\d*/g).join('')
.match(/(\d{0,3})(\d{0,2})(\d{0,4})/).slice(1).join('-')
.replace(/-*$/g, '');
}
}
.valid{
border:1px solid blue;
}
.invalid{
border:1px solid red;
}
<input class="required-input" id="ssn" type="text" name="ssn" placeholder="123-45-6789" onBlur = "myFunc()">
Also there is another way to enforce user always enters that pattern -
<input class="required-input" id="ssn" type="text" name="ssn" placeholder="123-45-6789" onBlur = "myFunc()" required pattern="\d{3}[\-]\d{2}[\-]\d{4}">
function myFunc() {
var patt = new RegExp("\d{3}[\-]\d{2}[\-]\d{4}");
var x = document.getElementById("ssn");
var res = patt.test(x.value);
if(!res){
x.value = x.value
.match(/\d*/g).join('')
.match(/(\d{0,3})(\d{0,2})(\d{0,4})/).slice(1).join('-')
.replace(/-*$/g, '');
}
}
.valid{
border:1px solid blue;
}
.invalid{
border:1px solid red;
}
<input class="required-input" id="ssn" type="text" name="ssn" placeholder="123-45-6789" onBlur = "myFunc()">
Related
I want to change width of a textfield when user enters more than 17 characters in that textfield using Javascript (if possible) otherwise by any other means.
I wrote a code to do the same, but it only changes width when user click outside the textfield after entering more than 17 characters. I want it to change width automatically when user enters more than 17 characters :
function widen() {
var value = nametf.value;
if (value.length > 17) {
nametf.style.width = '300px';
} else {
nametf.style.width = '200px';
}
}
#nametf {
width: 200px;
height: 20px;
padding: 5px 10px;
}
<title>TEXTFIELD TEST</title>
<form method="get" action="wwhome.php">
<input type="text" name="name1" id="nametf" onchange="widen()" value="" required>
</form>
onchange gets activated when the input looses focus, that's why it works when you click outside. On the other hand oninput will be triggered immediately when the value changes:
const nametf = document.getElementById('nametf');
function widen() {
var value = nametf.value;
if (value.length > 17) {
nametf.style.width = '300px';
} else {
nametf.style.width = '200px';
}
}
#nametf {
width: 200px;
height: 20px;
padding: 5px 10px;
}
<html>
<form method="get" action="wwhome.php">
<input type="text" name="name1" id="nametf" oninput="widen()" value="" required>
</form>
</html>
You need to pass a self-reference to the function using this. I would also change on-change to on-key-up, because on-change waits for you to move focus away from the field.
onkeyup="widen(this)"
Then you need to parameterize the function with your variable "nametf"
function widen(nametf) {
// ...
}
Example
function widen(nametf) {
var value = nametf.value;
if (value.length > 17) {
nametf.style.width = '300px';
} else {
nametf.style.width = '200px';
}
}
#nametf {
width: 200px;
height: 20px;
padding: 5px 10px;
}
<title>TEXTFIELD TEST</title>
<form method="get" action="wwhome.php">
<input type="text" name="name1" id="nametf" onkeyup="widen(this)" value="" required>
</form>
A better approach would be to use em units to expand the text are based on the current value.
initExpandingFields();
function initExpandingFields() {
Array.from(document.querySelectorAll('.expanding-field')).forEach(field => {
field.addEventListener('keyup', onFieldChange);
});
}
function onFieldChange(e) {
let field = e.target,
len = field.value.length;
field.style.width = (len * 0.667) + 'em';
}
#nametf {
width: 200px;
height: 20px;
padding: 5px 10px;
}
<title>TEXTFIELD TEST</title>
<form method="get" action="wwhome.php">
<input type="text" class="expanding-field" name="name1" id="nametf" value="" required>
</form>
Try this:
var nametf = document.getElementById("nametf");
nametf.addEventListener("input", function(){
if(nametf.value.length > 17) {
nametf.size = "30";
} else {
nametf.size = "20";
}
});
#nametf {
height: 20px;
padding: 5px 10px;
}
<title>TEXTFIELD TEST</title>
<form method="get" action="wwhome.php">
<input type="text" name="name1" id="nametf" size="20" value="" required>
</form>
I am trying to create a custom error message when a number which is too high or low is entered in the "size" element. However, I am unable to make this work. I am a beginner so a solution which involves the least changes to my existing code would be most appreciated.
function autoFillcost() {
var size = document.getElementById("size").value;
if (size <= 25)
document.getElementById("cost").value = "£100";
else if (size >= 26 && size <= 50)
document.getElementById("cost").value = "£200";
else
document.getElementById("cost").value = "£300";
}
function sizeValidate() {
var size = document.getElementById("size");
if (!size.checkValidity()) {
size.setCustomValidity("ERROR!");
} else {
size.setCustomValidity("");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<form>
Group Size:<input type="number" min="6" max="200" id="size" onblur="autoFillcost();sizeValidate();" required>
<p>Cost:<input type="text" id="cost"></p>
<p id="demo"></p>
</form>
</body>
</html>
Sorry for digging, but it is possible, just report it after you set it.
Hopefully this helps others.
if (!size.checkValidity()) {
size.setCustomValidity("ERROR!");
size.reportValidity();
}
The problem with setCustomValidity is, that it does only work once you submit the form.
function autoFillcost() {
var size = document.getElementById("size").value;
if (size <= 25)
document.getElementById("cost").value = "£100";
else if (size >= 26 && size <= 50)
document.getElementById("cost").value = "£200";
else
document.getElementById("cost").value = "£300";
}
function sizeValidate() {
var size = document.getElementById("size");
if (!size.checkValidity()) {
size.setCustomValidity("ERROR!");
} else {
size.setCustomValidity("");
}
}
button {
padding:6px;
cursor:pointer;
}
input {
padding:5px;
border:1px solid #aaa;
box-shadow: 0px 0px 3px #ccc, 0 10px 15px #eee inset;
border-radius:2px;
}
input:valid {
background-color: white;
}
input:invalid {
background-color: lightpink;
}
<form>
Group Size:<input type="number" min="6" max="200" id="size" onblur="autoFillcost();sizeValidate();" required />
<p>Cost:<input type="text" id="cost"></p>
<p id="demo"></p>
<button type="submit">Submit</button>
</form>
I have this input text:
<div class="form-group">
<label for="newPrice">New Price</label>
<input type="text" class="form-control" id="newPrice" name="newPrice" placeholder="New price">
</div>
I would like to change the border of the input dynamically as the user is typing depending what the value is.
This value will be a percent based on an earlier defined amount that will change depending on the value the user is adding.
So if the value is under 5% it's red between 5-10% it's amber and over 10% is green etc.
Any JavaScript whizzes out there know the best way to do this?
I'll go with 2 events. The first is input, but contenteditable elements won't fire an input event on IE11, so I'll go for keypress with a timeout too.
input will be fired right after a user inputs something and the value is changed. keypress will fire after a user inputs something but right before the value is changed, in between.
This way you will keep all modern and older browsers covered (to a limit, because of addEventListener):
var tim = null;
var el = document.getElementById("newPrice");
el.addEventListener("keypress", function() {
tim = setTimeout(input, 0);
});
el.addEventListener("input", function input() {
clearTimeout(tim);
// do whatever you want with el.value
if (el.value == "BLAH") {
el.style.backgroundColor = "red";
} else if (parseInt(el.value) > 10) {
el.style.backgroundColor = "green";
} else if (parseInt(el.value) < -12) {
el.style.backgroundColor = "whizzeblue";
}
});
<input id="txt" type="number" onkeyup="changeborder(this.id, this.value)" />
<script type="text/javascript">
function changeborder(id, value){
if(value < 5){
document.getElementById(id).style.border = "2px solid red";
}
else if(value > 5 && value < 10 ){
document.getElementById(id).style.border = "2px solid yellow";
}
}
</script>
Use focusout . In snippet validation is not applied.
$("#newPrice")
.focusout(function() {
var price = $(this).val();
if (parseInt(price) <= 5) {
$(this).removeClass('green');
$(this).removeClass('blue');
$(this).addClass('red');
}
if (parseInt(price) > 5 && parseInt(price) <= 10) {
$(this).removeClass('red');
$(this).removeClass('blue');
$(this).addClass('green');
}
if (parseInt(price) > 10) {
$(this).removeClass('green');
$(this).removeClass('red');
$(this).addClass('blue');
}
});
.red {
border: solid 2px red;
}
.green {
border: solid 2px green;
}
.blue {
border: solid 2px blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label for="newPrice">New Price</label>
<input type="text" class="form-control" id="newPrice" name="newPrice" placeholder="New price">
</div>
I am using jQuery for min and maxlength. I want here to prevent button if minlength is not correct. I mean if user not entered minimum 8 digit, then prevent button.
jQuery:
var minLength = '8';
var maxLength = '13';
$("input[name=354]").keypress(function(){
if(this.value.length > maxLength) {
this.value = this.value.slice(0, maxLength);
}
if(this.value.length < minLength) {
$(this).css('border','1px solid #f00');
} else {
$(this).css('border-color','#cfdadd');
}
});
HTML button code:
<button type="button" class="btn next">Next</button>
You can add disabled attribute to button if length of input isn't valid.
var minLength = "5";
var maxLength = "10";
$("input").on("keydown change", function(){
var value = $(this).val();
// length is short
if (minLength > value.length){
$("button").attr("disabled", true);
$(this).addClass("error");
} else {
$("button").attr("disabled", false);
$(this).removeClass("error");
}
// length is long
if (value.length > maxLength)
this.value = value.slice(0, maxLength);
});
.error {
border: 2px solid rgba(255, 0, 0, 0.48);
box-shadow: 0px 0px 2px -1px red;
outline: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="number" class="error" />
<button type="submit" disabled>Submit</button>
</form>
I think you need to use disabled.
And it would be better to use input instead of keypress.
var minLength = '8';
var maxLength = '13';
$('input[name=354]').on('input', function() {
if (this.value.length > maxLength) {
this.value = this.value.slice(0, maxLength);
}
if (this.value.length < minLength) {
if (!$(this).hasClass('invalid')) {
$(this).addClass('invalid');
}
$('.btn').attr('disabled', true);
} else {
$(this).removeClass('invalid');
$('.btn').attr('disabled', false);
}
});
.invalid {
border:1px solid #f00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="invalid" name="354" type="text">
<button type="button" class="btn next" disabled>Next</button>
Here's a fiddle
I am trying to use some code from a form validation example and tailor it to my own form but it doesn't seem to be working. There is a message that is supposed to appear when a user enters a name,phone number or email incorrectly e.g 'please enter a valid name'.I don't understand javascript that well so am struggling to try and find the problem. There aren't any console problems if that helps it is probably a naming issue?
jsFiddle
HTML
<form>
<div class="formColumn2">
<label for="name">
<span class="textStyle">Full Name*</span><input type="text" id="name"><br>
<span id="nameMessage" class="message">You must have a valid name</span>
</label>
<label for="email"><span class="textStyle">Email*</span>
<input type="text" id="email"><br>
<span id="emailMessage" class="message">You must have a valid email</span>
</label>
<label for="phoneNumber">
<span class="textStyle">Phone Number*</span>
<input type="text" id="phoneNumber"><br>
<span id="phoneMessage" class="message">You must have a valid phone number</span>
</label>
<input type="submit" id="submit" value="Submit">
</div>
</form>
CSS
.textStyle {
width: 150px;
display: inline-block;
}
.formColumn2 {
margin-top:-80px;
margin-left: 50px;
}
select{
width:200px;
margin:10px 0;
}
input[type=text],
input[type=password]{
width:200px;
margin:10px 0;
}
.message{
display: none;
}
input[type=submit]{
background: #fff;
border: 1px solid black;
cursor: pointer;
}
input[type=text].error,
input[type=password].error{
border: 3px solid red;
color: red;
}
Javascript
var nameInput = document.querySelector('#name');
var emailInput = document.querySelector('#email');
var phoneInput = document.querySelector ('#phoneNumber');
function displayError(fieldname, message) {
var input_field = document.querySelector('#' + fieldname);
var error_box = document.querySelector('#' + fieldname + 'Message');
addClass (input_field, 'error');
error_box.style.display = 'block';
error_box.innerHTML = message;
}
function hideError(fieldname){
var input_field = document.querySelector('#'+fieldname);
var error_box = document.querySelector('#'+fieldname+'Message');
removeClass (input_field, 'error');
error_box.style.display = 'none';
}
function addClass(html_element,class_str) {
if(html_element.className.indexOf(class_str) == -1){
html_element.className += ' '+class_str;
}
}
function removeClass(html_element, class_str){
if(html_element.className.indexOf(class_str) != -1){
html_element.className = html_element.className.replace(class_str, '');
}
}
nameInput.onblur = function(){
if(!nameInput.value){
valid = false;
displayError('name', 'Please enter your name');
}else if(!isValidName(nameInput.value)){
valid = false;
displayError('name', 'That name has invalid characters');
}else{
hideError('name');
}
emailInput.onblur = function(){
if(!emailInput.value){
valid = false;
displayError('email', 'Please enter your email');
}else if(!isValidEmail(emailInput.value)){
valid = false;
displayError('email', 'The email field is invalid');
}else{
hideError('email');
}
}
phoneInput.onblur = function(){
if(!emailInput.value){
valid = false;
displayError('phone', 'Please enter your number');
}else if(!isValidEmail(emailInput.value)){
valid = false;
displayError('email', 'The phone number field is invalid');
}else{
hideError('phone');
}
}
submitButton.onclick = function(){
var valid = true;
return valid;
}
function isValidName(str){
var namePattern = new RegExp('^[a-zA-Z \s\'-]{1,}$');
return namePattern.test(str);
}
function isValidEmail(str) {
var emailPattern = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return emailPattern.test(str);
}
if you will use jQuery, it will be less complicated.
if that you need to use
$('.formClass').validate();
and in html
just put required in text fields, whom you want they not to be empty.
<form class="formCLass">
<input type="text" name="username" required/>
<input type="email" name="email" required/>
</form>