Validate input field and block characters - javascript

Hello guys i have an input field and i want to validate in real time the insterted characters.
I want that this input field accept only letters, number and one blank space. If is inserted for example *, script delete this characters.
Regards
On input filed:
onkeyup="check(this,'onlyletter')" onblur="check(this,'onlyletter')
On JS:
var r={
'onlyletter': // i need correct regular expression
}
function check(o,w){
// i need function
}
I have: Abc123' 123* but i accept Abc123 123

with raw JS:
the clue is in the method transform
<html>
<head>
<script>
function transform(elem) {
var v = elem.value;
var n = "";
//loop it to cut of more than 1 -- e.g. on copy & paste
if(v.length) {
n = v.slice(-1);
if( !isNaN(parseFloat(n)) && isFinite(n) ) {
elem.value = v.substring(0, v.length - 1);
}
}
}
</script>
</head>
<body>
<input
type="text"
name="date"
placeholder="Text only!"
onkeyup="transform(this);"
maxlength="10"
>
</body>
</html>
alternate way using jquery
MASK the textfield to only accept letters. now that can be done a number of ways. one is the query mask plugin
you only need query, query-mask and then it is 1 line of code ;)
demo:
<html>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.mask.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//masked input for alphabets only
//constrained to 20 characters in length without spaces
$("#myTextField").mask("SSSSSSSSSSSSSSSSSSSS");
});
</script>
<body>
<br><input type = "text" id="myTextField" name="Text Field"></br>
</body>
</html>

Related

How to input phone no in this 'xxx-xxx-xxxx' format in number input field

I want that whenever I type a number in the number input field in XXXXXXXXXX format it takes as XXX-XXX-XXXX using HTML, CSS and javascript.
Just like this snippet but without using the mask script.
$('.phone_us').mask('000-000-0000');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://igorescobar.github.io/jQuery-Mask-Plugin/js/jquery.mask.min.js" type="text/javascript"></script>
<!--mask script-->
<input type="text" class="phone_us" />
There are some working answers here, but this solution is more stable.
Using the oninput event for instant replace and ...
Applying regex on the full string, to allow copy/paste, and finally ...
This code is shorter as well:
$('.phone_us').on('input', function() { //Using input event for instant effect
let text=$(this).val() //Get the value
text=text.replace(/\D/g,'') //Remove illegal characters
if(text.length>3) text=text.replace(/.{3}/,'$&-') //Add hyphen at pos.4
if(text.length>7) text=text.replace(/.{7}/,'$&-') //Add hyphen at pos.8
$(this).val(text); //Set the new text
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="phone_us" maxlength="12">
Or even without jQuery:
document.querySelector('.phone_us').addEventListener('input', function() { //Using input event for instant effect
let text=this.value //Get the value
text=text.replace(/\D/g,'') //Remove illegal characters
if(text.length>3) text=text.replace(/.{3}/,'$&-') //Add hyphen at pos.4
if(text.length>7) text=text.replace(/.{7}/,'$&-') //Add hyphen at pos.8
this.value=text; //Set the new text
});
<input class="phone_us" maxlength="12">
you could try like this
$(document).ready(function () {
$(".phone_us").keyup(function (e) {
var value = $(".phone_us").val();
if (e.key.match(/[0-9]/) == null) {
value = value.replace(e.key, "");
$(".phone_us").val(value);
return;
}
if (value.length == 3) {
$(".phone_us").val(value + "-")
}
if (value.length == 7) {
$(".phone_us").val(value + "-")
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://igorescobar.github.io/jQuery-Mask-Plugin/js/jquery.mask.min.js" type="text/javascript"></script>
<!--mask script-->
<form id="form1" runat="server">
<input type="text" maxlength="12" class="phone_us"/>
</form>
You can implement like this
document.getElementById('txtphone').addEventListener('blur', function (e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{3})(\d{3})(\d{4})/);
e.target.value = '(' + x[1] + ') ' + x[2] + '-' + x[3];
});txtphone
<input type="text" class="phone_us" id="txtphone" placeholder = "(000) 000-0000"/>
<input type="tel" id="phone" name="phone"
pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
required>
Use HTML5 input type=tel to get phone number, and pattern attribute to specify any pattern.
[0-9]{3} represent the 0-9 numeric and 3 digits.
Then, add a hyphen (-), and use the numerics pattern again.
You can use own pattern and your country wise pattern like
[1-9]{4}-[1-9]{6} for the format 1234-567890.
Use the min-length and max-length in HTML5 to set limit.
Note that these patterns won't automatically add the hyphens, but will only allow correctly formatted input.
If you want get more patterns, search on web or see HTML5pattern.com
Pure javascript.
Enter 10 digits in the input field and click anywhere outside the input field.
var myTel = document.getElementById("tel");
myTel.addEventListener("blur", function() {
var str=myTel.value;
var pattern=/[0-9]{10}/;
if (pattern.test(str)) {
newstr=str.slice(0,3)+'-'+str.slice(3,6)+'-'+str.slice(6,10);
myTel.value=newstr;
}
else {
// bad
myTel.value='bad value: only 10 digits';
}
})
<form>
<input type="text" id="tel" name="tel" maxlength='10'>
</form>

How to auto add a hyphen in user input using Javascript?

I am trying to validate and adjust user input for a zip code to match the format: xxxxx OR xxxxx-xxxx
Is there a simple way using javascript to add the hyphen (-) automatically if the user enters more than 5 digits?
Pretty sure there is! Just gotta check how many characters the inputted string has, and if it's 5, add a hyphen to the string :)
var input = document.getElementById("ELEMENT-ID");
input.addEventListener("input", function() {
if(input.value.length === 5) {
input.value += "-";
}
}
Try the following.
function add_hyphen() {
var input = document.getElementById("myinput");
var str = input.value;
str = str.replace("-","");
if (str.length > 5) {
str = str.substring(0,5) + "-" + str.substring(5);
}
input.value = str
}
<input type="text" id="myinput" value="a" OnInput="add_hyphen()"></input>
Anna,
The best way to do it would be to use a regular expression. The one you'll need is:
^[0-9]{5}(?:-[0-9]{4})?$
You would ten use something like:
function IsValidZipCode(zip) {
var isValid = /^[0-9]{5}(?:-[0-9]{4})?$/.test(zip);
if (isValid)
alert('Valid ZipCode');
else {
alert('Invalid ZipCode');
}
}
In your HTML call it like this:
<input id="txtZip" name="zip" type="text" /><br />
<input id="Button1" type="submit" value="Validate"
onclick="IsValidZipCode(this.form.zip.value)" />
For more on Regular Expressions this is a good article:
Regular Expressions on Mozilla Developers Network
You can try using simple javascript function as follows
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<script>
function FN_HYPEN(){
var input = document.getElementById("USER");
if(input.value.length === 5) {
input.value += "-";
}
}
</script>
</head>
<body>
<INPUT ID="USER" TYPE="TEXT" onKeypress="FN_HYPEN();"/>
</body>
</html>

How to select and run this function onload?

So I have this working codeblock in my script to replace the decimal seperator from comma "," into period "." ,when editing a form. Because in this region the decimal seperator comma is normal I also want the values to be displayed like this 1,99€ so I reverted the working function. The selected fields should change on load. When the form gets submitted I will cange it back again. For this example I show you only one of the fields.
The value="1.5" gets loaded from the Magento-Backend the wrong way, which is another story:
I included onload:"function(event)"
and window.onload = function(); to show two my attempts to adress this function from jQuery: jQuery('form').on('change', '#price', function(event) I also need to know how to remove the .on('change' part. First time using Js und jQuery. I really tried everything.
<html>
<body onload="function(event)">
<form>
<input id="price" value="1.5">
</form>
</body>
</html>
<script>
window.onload = function();
jQuery('form').on('change', '#price', function(event) {
event.preventDefault();
if (jQuery('#price').val().includes('.')) {
var varwithpoint = jQuery('#price').val();
varwithcomma = varwithcomma.replace(",",".");
jQuery('#price').val(varwithpoint);
}
else {
console.log('no dot to replace');
}
});
</script>
There were a few parts of the code which didn't seem to be working as intended, so below is a basic example of code that will convert the "," to a "." if stored in the input "price", and check this after each change of the value;
function convert_price(){
var this_price = $("#price").val();
if (this_price.includes(',')) {
this_price = this_price.replace(",",".");
$('#price').val(this_price);
} else {
console.dir('no dot to replace');
}
}
convert_price();
$("#price").on("change",convert_price);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<html>
<body>
<form>
<input id="price" value="1,5">
</form>
</body>
</html>
I have called "init" the function that attaches the change event to the input file, I also changed the parameters passed to the on function
function init(){
var input = jQuery('#price');
input.on('change', function(event) {
event.preventDefault();
var valueInInput = input.val();
if (valueInInput.includes('.')) {
var varwithcomma = valueInInput.replace(",",".");
input.val(varwithcomma);
} else {
console.log('no dot to replace');
}
});
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body onload="init()">
<form>
<input id="price" value="1.5">
</form>
</body>
</html>

check text box value is according to a prefix

I have text box.
Users can enter Student Id into that.
Student id is in this format DIP0001.
First three letters should be DIP and the remaining 4 digits should be numeric and can only upto 4 characters.
So how can I check whether entered data is in this format using javascript.
Please help.....
You could build a regular expression pattern and test it against that value to see if it matches that exact pattern.
HTML FILE:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Title</title>
</head>
<body>
<label for="studentId">Student ID</label>
<input id="studentId" type="text">
<button id="btn" type="button">Validate</button>
// Embedded script so that you don't have to load an external file
<script>
var input = document.getElementById('studentId');
var btn = document.getElementById('btn');
var pattern = /DIP+\d{1,3}/g;
btn.addEventListener('click', function(){
if(pattern.test(input.value)) {
alert('It enter code here`atches!');
}else {
alert('It does not match!');
}
});
</script>
</body>
</html>
JS FILE:
// This pattern looks something like this: DIP0000
var pattern = /DIP+\d{1,3}/g;
// studentId is the ID of the input field that contains the Student ID
var studentIdInput = document.getElementById('studentId');
// Check the pattern against the provided Student ID
if(pattern.test(studentIdInput.value)) {
alert('It matches the pattern!');
}
EDIT 1: I have built the functionality in the following JSFiddle: http://jsfiddle.net/vldzamfirescu/QBNrW/
Hope it helps!
EDIT2: I have updated the JSFiddle to match any other combinations up to 4 digits; check it out: http://jsfiddle.net/vldzamfirescu/QBNrW/1/ Let me know if it solved your problem!
try this code
<html>
<head>
<script>
function validate(val) {
if (val.value != "") {
var filter = /^[DIP]|[dip]+[\d]{1,4}$/
if (filter.test(val.value)) { return (true); }
else { alert("Please enter currect Student Id"); }
val.focus();
return false;
}
}
</script>
</head>
<body>
<input id="Text1" type="text" onblur="return validate(this);" />
</body>
</html>
Use Regular Expresions.
If found a valid Student ID, the pattern will return true:
function validateStudentId(id) {
var re = /DIP[0-9]{4}/;
return re.test(id);
}
// Edited for use with a click event:
document.getElementById('button').addEventListener('click', function(){
if( validateStudentId(document.getElementById('textBox').value) ){
alert('correct');
}else{
alert('invalid ID');
}
});

If length is less than 0 alert in javascript

Hi i have here a script for two text fields.
If the current length is 0 character... I want to alert that no characters left!
<html>
<head>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<title></title>
</head>
<body>
<span id="limit">10</span><br/>
<input type="text" class="text_question_1"><br>
<input type="text" class="text_question_1">
</body>
<script type="text/javascript">
$(document).ready(function(){
//alert("test!!");
var combined_text_length = 0;
var limit = 10;
$("input.text_question_1").live('keyup', function (e){
current_length = 0;
$.each($("input.text_question_1"), function(index, value){
current_length += value.value.length
$(this).attr("#limit")
})
$("span#limit").html(limit - current_length)
})
})
</script>
</html>
I tried to put...
if (limit < 0){
alert("EXCEEDED!");
}
But not working.
current_length += value.value.length seems wrong. Use jQuery's own val() to retrieve the input field value as a string
Try
if (current_length > limit){
alert("EXCEEDED!");
}
As you are never modifying the limit variable itself, it can not get lower than zero.
Note that an alert is not particularly user-friendly. Lookup the jQuery plugin "lightBox".
Also, it seems you are trying to use a <input>s where a <textarea> might be more appropriate.

Categories

Resources