I am trying to restrict alphabets in javascript. Here is the code I am using and I am able to show alert to users "Enter numbers only" if they enter alphabets.
But issue is after entering values in the textbox, if I try to backspace the values, it shows alert("Enter numbers only"
How to not show alert if I press backspace key.
Here is my code,
PasswordCheck(event)
{
var allowedRegex = /^[0-9]+$/ && event.keyCode === 8;
if (!event.key.match(allowedRegex)) {
alert("Enter Numbers only")
event.preventDefault();
}
<form (keyup)="PasscodeCheck($event)" autocomplete="off">
......
</form>
PasswordCheck(event) {
var allowedRegex = /^[0-9]+$/;
if (!event.key.match(allowedRegex) && event.keyCode !== 8) {
alert("Enter Numbers only");
}
}
Related
I tried the piece of code to restrict user if the address is wrongly entered as shown below
sample address: #23 78/54, A-31 Nand Jyot Indl Estate, Andheri- Kurla Road, Saki Naka (allowed)
14/18, Loha Bhavan, P D Mello Rd, Chinch Bunder, mumbai (allowed)
only ".....", ",,,,", "----" (not allowed)
$("#" + (idOfElement)).on("keypress keyup", function (e) {
this.value = this.value
//.replace(/[^\..]/g,'')
.replace(/(^[\d#\w]+)/g, '$1')
.replace(/(\s[1-9A-Za-z\/#-]*)./g, '$1');
});
I want the user allowed to enter numbers, '#', '/', '-', space, and alphabets only, and if they enter any other special characters it shouldn't allow them to do so.
code given below is working fine for number with decimal upto two position. similarly i want to do the same for address.
below code allows 12345.67
it doesn't allow 23.4565, 23289.499999
//for numbers with decimal point upto two position
$("#" + (idOfElement)).on("keypress keyup blur", function (e) {
this.value = this.value
.replace(/[^\d.]/g, '')
.replace(/(^[\d]+)([\d]*)/g, '$1')
.replace(/(\..*)\./g, '$1')
.replace(/(\.[\d]{2})./g, '$1');
if ((e.which != 46 || $(this).val().indexOf('.') != -1) && (e.which < 48 || e.which > 57)) {
e.preventDefault();
}
I also want the user to enter only alphabets with space and numbers only.
sample data: toothpaste 200g (allowed)
shampoo..(not allowed)
shampoo (with any other special character like !,?,_,~)(not allowed)
Use below code sample. Also please find fiddle for same in comment.
<input type="text" id="addressID">
$(document).ready(function(){
$("input").bind('input', function(e) {
var str = $("#addressID").val();
var re = new RegExp(/^[ A-Za-z0-9\/#-]*$/g);
if (re.test(str)) {
//alert('valid');
} else {
alert("Invalid address, only alphanumeric values and '/','#','-' allowed");
$("#addressID").val($("#addressID").val().slice(0, -1));
}
});
});
I have a input type URL and client want to only accept ENGLISH characters on input
Keypress and Blur function is what I have but in blur it still accept this likr inout "建築家test.com"
<input type="url" id="url" required pattern="https?://.+" placeholder="http://example.com">
$("#url").on("keypress", function(event) {
var englishAlphabetDigitsAndWhiteSpace = /[a-zA-Z0-9!##$%^*_|:/.]/g;
var key = String.fromCharCode(event.which);
if (event.keyCode == 8 || event.keyCode == 37 || event.keyCode == 39 || englishAlphabetDigitsAndWhiteSpace.test(key)) {
return true;
}
return false;
});
$("#url").blur(function(e){
var input = $(this).val();
var regex = /[a-zA-Z0-9!##$%^*_|:/.]/g;
if(regex.test(input)) {
alert("OK");
}
else {
alert("no Japanese allowed");
return false;
}
});
Could you try with the following regex:
^([a-zA-Z0-9!##$%^*_|:/.])*$
or that one, depending on if you accept empty string or not as valid entry.
^([a-zA-Z0-9!##$%^*_|:/.])+$
Last but not least, if you want to check that your input is a well-formed UR, have a look at the following link:
What is the best regular expression to check if a string is a valid URL?
I have one amount field in that i want to restrict user after decimal they can not use more than two values:
After decimal there should be only two values that are option.
User can not type more than one decimal in the field.
I am using following regix for that its not working can any one help.
function validate(evt) {
if (evt.keyCode == 8) { return true; }// for backspace problem in mozilla
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = /[0-9 ]|\,\d{1,2}/;
if (!regex.test(key))
{
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
}
This can actually be accomplished using HTML only by setting the STEP and MAX of your numeric field such as
<form>
<input type="number" name="myNumber" required=true step=".01">
<button>send</button>
</form>
please let me know if this is what your looking for but this will mean that any value entered must be numeric(thus only 1 decimal point) it must be less than or equal to 1 (you can set to .99 if you dont want to include 1) and it must be an increment of .01(so it can only have 2 decimal places.
Just re-read your question you can remove the max(i thought i read no more than 1.0)
var previousValue;
function numberChanged(element){
if(validateMe(element)==false){
element.value=previousValue;
}else{
previousValue=element.value;
}
function validateMe(element){
wholeNumber=element.value.split(".")[0];
if(element.value.split(".").length==1){
if(wholeNumber<-1 || > 999999999){
return false;
}
}else if(element.value.split(".").length==2){
decimalValue=element.value.split(".")[1];
if(decimalValue>-1 && decimalValue<100){
if(wholeNumber<-1 || > 999999999){
return false;
}
}else{
return false;
}
}else{
return false;
}
}
<input type="text" id="myNumber" onChange="numberChanged(this)" />
I have a form and currently I have a javascript code to validate my form to make sure that the user fills out every input. my form action includes:
onsubmit="return validateForm();"
Which is the javascript to make sure every field is filled out. If it makes any difference, here is my javascript code:
<script type="text/javascript">//
<![CDATA[function validateForm() {
var a=document.forms["myform"]["inf_field_FirstName"].value;
var b=document.forms["myform"]["inf_field_Email"].value;
var c=document.forms["myform"]["inf_field_Phone1"].value;
if (a==null || a=="" || a=="First Name Here")
{ alert("Please enter your First Name!");
return false; }
if (c==null || c==''|| c=="Enter Your Phone Here")
{ alert("Please insert your phone number!");
return false; }
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (document.myform.inf_field_Email.value.search(emailRegEx) == -1)
{ alert("Please enter a valid email address.");
return false; } }
// ]]>
</script>
However on the phone number field, defined at c, I want to add another script that will pop up if the user doesn't enter a phone number at least 9 digits long. I was thinking of adding a code like this
<script type="text/javascript">
function validate(){
var c=document.forms["myform"]
if (input.length<9){
alert("Please enter a real phone number")
return false
}else {
return true
}
}
</script>
However I don't know how to run both functions on submit. I am extremely new to javascript so excuse me if there's already a simple solution to this.
Thanks
Everything in quotes after onsubmit= is just javascript. You can make sure both functions return true by doing:
onsubmit="return validateForm() && validate();"
You could add it as another rule in that conditional. For example:
if (c==null || c==''|| c=="Enter Your Phone Here" || c.length < 9) {
alert("Please insert your phone number!");
return false;
}
It's probably best to refactor this code, but that's probably the fastest way to do what you need.
JS:
validate document.forms();
if (document.forms[0].userAge.value == "") {
alert("Age field cannot be empty.");
return false;
}
if (document.forms[0].userAge.value < 5) {
alert("Your age input is not correct.");
return false;
}
if (userage == isNumber) {
alert("Your age input is not correct.");
return false;
}
alert("Name and Age are valid.");
return true;
HTML:
<label for="userAge">Age:</label>
<input type="text" name="userAge" id="userAge" />
</div>
If this is the code I have, how would I make it so that if someone were to enter a non number in the age text box an alert would come up saying " Your input is not correct"?
Edit: I originally suggested using parseInt with isNaN() to test if the input was non-numeric. Well, it seems that using a regex is preferrable not only formatching cases like "4a" correctly, but it's actually faster in many cases (surprise!).
I mocked up some HTML with a button to illustrate.
HTML:
<form>
<label for="userAge">Age:</label>
<input type="text" name="userAge" id="userAge" />
<input type="button" id="test" name="test" value="Test" />
</form>
JavaScript:
function validateForm() {
// get the input value once and use a variable
// this makes the rest of the code more readable
// and has a small performance benefit in retrieving
// the input value once
var userAge = document.forms[0].userAge.value;
// is it blank?
if (userAge === "") {
alert("Age field cannot be empty.")
return false;
}
// is it a valid number? testing for positive integers
if (!userAge.match(/^\d+$/)) {
alert("Your age input is not correct.")
return false;
}
// you could also test parseInt(userAge, 10) < 5
if (userAge < 5) {
alert("Your age input is not correct.")
return false;
}
alert("Name and Age are valid.");
return true;
}
// trigger validateForm() however you want, I did this as an example
document.getElementById("test").onclick = validateForm;
Here is a jsFiddle to demonstrate: http://jsfiddle.net/willslab/m2spX/6/
About the regex: userAge.match(/^\d+$/) returns true if userAge only contains a positive integer. The beginning / and ending / indicate a regular expression literal. \d indicates ASCII digits only. + matches one or more occurrences of the previous pattern (digits in this case). ^ indicates match from the beginning, and $ indicates match until the end. So /^\d+$/ is a regex literal matching only ASCII digits from beginning to end!
Also note that you can combine the last two if statements using an OR operator (||). I left these isolated in case you want to give each one a unique validation message.
It would look like this:
if (!userAge.match(/^\d+$/) || userAge < 5) {
alert("Your age input is not correct.")
return false;
}
Feel free to ask any questions about the code and I will explain. I hope that helps!
I recommend you to use the following Javascript which will not allow non-numeric characters in the text field.
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57))
{
return false;
}
return true;
}
<input type="text" id="userAge" name="userAge" onkeypress="return isNumberKey(event);">
Try this solution
<script language="javascript">
function validate(){
alert("validate ..."+document.forms[0].userAge.value);
if (document.forms[0].userAge.value == ""){
alert("Age field cannot be empty.");
return false;
}
if (document.forms[0].userAge.value<5){
alert("Your age input is not correct.");
return false;
}
//provide a way to validate if its numeric number..maybe using regexp
//if (isNumeric(userAge)){
// alert("Your age input is not correct.");
// return false;
//}
//alert"Name and Age are valid."
return true;
}
</script>
The HTML should be
<form>
<div><label for="userAge">Age:</label>
<input type="text" name="userAge" id="userAge" onblur="validate()"/>
</div>
</form>
use the code below
if(isNaN(document.forms[0].userAge.value)){
alert('This is not a number');
}