I am trying to check only alphabet in textbox(like XYZ) and any alphanumeric or special character value not entered. But my function only check numeric value and one more condition applied, if i pass alphanumeric value or special character in the textbox with alphabet or without alphabet then it will be not accept the textbox value. So please help me..
<script>
function Enable() {
var txt = document.getElementById("textbox");
if (!isNaN(txt.value) || txt.value == "") {
alert("Blank or numeric value");
}
else
alert("Not numeric value");
}
</script>
<input type="button" onclick="Enable();" value="Add" />
<input type="text" id="textbox" />
You can try this regex to validate the input in the input box:
/^a-zA-Z$/i
You can bind the keyup event. When the event triggers, validate the value of the input box against the above mentioned regex, and replace with the desired value. Something like this:
$(this).val($(this).val().replace(/[^a-zA-Z]/g, ''));
Related
I want to create a script function which will validate if the user input contains more than one decimal i.e 2.434 should be the correct number but if the user tries to input a NUMBER LIKE 2.4.5.6 it will not take the input in the field. It will take only number after a decimal point but not another single decimal point. no 2.2.2. but 2.2222. Will use it in a .net page.
tried different patterns like ^-{0,1}\d+.{0,1}\d*$ but could not get result. added the function i am already using. need to add the decimal part in the given code.
function isNumberKey(evt) {
var first;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode == 46) {
return true;
}
if (charCode == 46 || charCode > 31 && (charCode < 48 ||
charCode > 57))
return false;
return true;
}
text box will take input when 2.22 or 3.455654 but won't take 2.3.34.4. when the user writes something like this the cursor won't change the position or take the input number.
The code provided does not validate the entire string. It just checks that the key pressed is a digit, which does not help much. There are many ways to do what you want:
1- Browser validation using type="number":
You can use an input with type "number"; then the browser will do a validation on its own before the form submits (this also accepts integers though):
<input type="number" name="decimal" />
2- Browser validation using the patternattribute:
A handy property you can set for inputs is the pattern attribute. You can set it to the desired regex, and the browser will make sure the user's input matches the regex before submitting the form.
<input type="text" name="decimal" pattern="^-?\d+\.?\d*$" />
3- Custom validation with Javascript:
This approach definitely gives you more flexibility, and allows you to validate once the user typed the input, instead of validating on form submit.
Assuming you have a text input, you can listen to the onchange event to validate the entire string, after the user has finished typing their input.
Edit: As for the regular expression, you need to escape the dot, so replace (. by \.). Plus, {0, 1} is equivalent to ?, as pointed out by #CodeManiac in the comments.
var input = document.getElementById("decimal-input");
input.onchange = function() {
var text = this.value;
if(!text.match(/^-?\d+\.?\d*$/)) {
this.value = ""; //clear input
console.log("Please enter a valid decimal.");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" id="decimal-input" placeholder="Enter a decimal..."/>
</form>
in the event target is the reference to the input element. So you are able to obtain the whole string
function isNumberKey(evt) {
s=evt.target.value;
console.log(s);
if (s.length !==0){
arr=s.split(".");
if (arr.length>0){
return false;
}
///... other checks...
}
there might be also a dirty way to check the whole number
try {
x=eval(s*1) ;
} catch (ex){
return false
}
or just do it on the enter key to implement a tiny calculator in your input ;)
Funtion setupField is called with the id of an input field to be initialized with an onkeyup event that will only allow valid input to be entered into the field. The regular expression it uses allows an optional + or - sign. The number itself can be of the format: 123, 123., 123.45, or .45
To allow an initial entry of the +, -, or . characters, the regular expression must also consider these characters to be legal input. When the form is submitted, there is always the possibility that only one of these 3 characters or no characters at all have been entered. It is easy enough to test for a valid decimal number by testing isNan(parseFloat(input)) against the input.
^(([+-]?\d+(\.\d*)?)|[+-]?(\.\d+)|[\+-\.])$
<!doctype html>
<html>
<head>
<meta name=viewport content="width=device-width,initial-scale=1">
<meta charset="utf-8">
<script>
function setupField(field)
{
let re = /^(([+-]?\d+(\.\d*)?)|[+-]?(\.\d+)|[\+-\.])$/;
field.autocomplete = "off";
field.saveValue = field.value;
field.onkeyup = function() {
var v = field.value;
if (v === '' || re.test(v)) {
field.saveValue = v;
}
else {
field.value = field.saveValue;
}
};
field.onchange = function() {
var v = field.value;
if (isNaN(parseFloat(v)))
console.log('You entered invalid input.');
};
}
function init()
{
setupField(document.getElementById('x'));
}
</script>
<body onload="init();">
<input type="input" id="x" size="10">
</body>
</html>
In my angular project, I had input type number I need to add a dash after three characters. if add input type number is not working for me if add input type text its working fine.
<input type="number" id="bank-code" (keyup)="onKey($event.target.value)" [value]='value' maxlength="7" required />
onKey(event){
var ele = event.split('-').join('');
if(ele.length > 0){
ele = ele.match(new RegExp('.{1,3}', 'g')).join("-");
}
this.value = ele;
}
Input type number does not allow non-numeric characters (because it's type=number). Notice you can input e character - it's because e is a valid number.
Try to use input type tel with pattern attribute, e.x.:
<input id='phone-num' type='tel' pattern="[0-9\-]+">
I have textbox in which I need validation in such way that it should not allow spaces if textbox is empty. If any values are there in textbox then only it should allow spaces. I am trying below code but not working
var letters = /^[0-9a-zA-Z]+$/;
$("#input1").on("blur ", function() {
function alphanumeric(username) {
if (username.value.match(letters)) {
return true;
} else {
$('#input1').on('keypress', function(e) {
if (e.which == 32)
return false;
});
return false;
}
}
})
if you are using form, you do not need any javascript
<form action='/'>
<input pattern="\s*\S+.*" title="space only is not allowed" required/>
<input type="submit">
</form>
why not just trim?
username.trim()
after that you can just return the result of match.
Add a function on your blur event that will trim the values which will remove preceding and succeeding whitespace. If the value is empty it will result in '' .
$("#input1").on("blur", function () {
if($(this).val().trim() === ''){
alert('empty value');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='input1' />
Your Regex seems wrong.
You're not allowing spaces characters.
Try this one instead: /\S/
\S is any non whitespace character.
If you want to start by a character, it will become /^\S/.
^ is when you want to start by the following character
$ is when you want to finish by the previous character
You can do it like this:
$(function() {
$('#input1').on('keypress', function(e) {
if ($(this).val() == "")
if (e.which == 32)
return false;
});
});
Online Demo (jsFiddle)
Can anyone help me to allow only special characters and numbers using jquery please. I have a text field where alphabet should not be entered.
function Validate(event) {
var regex = new RegExp("^[0-9-!##$%&*?]");
var key = String.fromCharCode(event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input ID="txtcheck" onkeypress="return Validate(event);" />
In the latter part of your question you mentioned
I have a text field where alphabet should not be entered.
Incase if you use HTML5, i suggest you could try below approach
<input type="text" name="specialfield" pattern="[^a-zA-Z]*" title="Alphabets not allowed">
I have input field which contains number and special characters e.g. comma and dot
while calulating the maxLength of the field i want to skip special characters .
I dont want to restrict the special character.
Expected Output should be :- 1,234 (Total Length :- 4)
<form action="/action_page.php">
Username: <input type="text" maxlength="3" id="myId"/>
<input type="submit" value="Submit">
</form>
jsfiddle link here
Try adding this javascript:
window.onload = function() {
var textInput = document.getElementById("myId");
textInput.oninput = function() {
var temp;
temp = this.value.replace(/[^\w\s]/gi,'');
if (temp.length > 3) {
alert("Invalid"); // Or other stuff you want to do
}
};
};
Note that this code checks input on real time
This should be done with javascript:
var input = document.getElementById('myId');
input.addEventListener('keyup', function () {
// Checking length of string ignoring all non-digit and non-letter characters
if (this.value.replace(/[^\d|[^a-zA-Z]]*/g, '').length == 3) {
console.log('stop and do whatever you need')
}
})
You can try to use HTML5 pattern attribute. Just instead of maxlength type pattern and give it some regex. Could do something like this:
<form action="/action_page.php">
Username: <input type="text" pattern="(?(?=^.\d{1,3},\d{1,3}$)^.{5}$|^.{4}$)" id="myId"/>
<input type="submit" value="Submit">
</form>