I want to restrict users from
inserting special characters except ' _ ' underscore
inserting Capitol Letters
inserting first value as number
inserting first value as special character
inserting spaces
in the textbox of <input>
I tried the below snippet but it didn't give me results for 1 & 4.
$(function() {
$('.alphaonly').on('input', function() {
$(this).val(function(i, val) {
return val.replace(/^\d|[A-Z\s]+/g, '');
});
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="lorem" class="alphaonly">
$(function() {
var haveFirst = false;
$('.alphaonly').on('keypress', function (event) {
if( $(this).val().length === 0 ) {
haveFirst = false;
}
var regex = new RegExp("^[a-z0-9_]+$");
var first = new RegExp("^[a-z]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if(!first.test(key) && haveFirst == false){
event.preventDefault();
return false;
}else if(regex.test(key)){
haveFirst = true;
}
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 name="lorem" class="alphaonly">
Try this
https://regex101.com/r/3mtS4t/1
This regex ^[A-Za-z0-9_]+$ will allow only name with underscores.
Here this i use this for some kind for utf-8
$("YourClassorIdOfInputOrTextField").bind("keypress", function (event) {
if (event.charCode!=0) {
var regex = new RegExp("^[A-Za-z0-9 _]");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
}
});
This will achieve what you seek stranger
Here's a simple replacement for your function based on regular expressions:
function blockSpecialChar(e) {
return /[^A-Za-z0-9._]/.test(e);
}
https://jsfiddle.net/RajKumarDubey/ko29twoh/
Related
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 a JavaScript function to Validate only decimal value.I use the JavaScript onkeyup event.
function onlyNumeric(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
var exclusions = [8, 46];
if (exclusions.indexOf(key) > -1) {
return;
}
key = String.fromCharCode(key);
var regex = /[0-9]|\./;
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault) {
theEvent.preventDefault();
}
return false;
}
return true;
}
<input type="text" onkeyup="onlyNumeric(event)" class="form-control" id="ColumnName" name="ColumnName">
It's working fine when I put value not from the number pad. But when I put value by number pad it's not working. So how can i fixed it?
Also I need fix it at two decimal point. But how can I do it?
Is onkeyup event Ok for this purpose?
Below is the code to help you out:
function onlyNumeric(evt) {
var pattern = /^\d{0,4}(\.\d{0,2})?$/i;
var element = document.getElementById("ColumnName");
if(pattern.test(element.value)) {
console.log("Vadid number:" + element.value);
} else {
console.log("Invadid number:" + element.value);
}
}
<input type="text" onkeyup="onlyNumeric(event)" class="form-control" id="ColumnName" name="ColumnName">
You can use this Regex pattern :
/^\d+(?:\.\d{1,2})?$/
Explanation :
\d match a digit...
+ one or more times
( begin group...
?: but do not capture anything
\. match literal dot
\d match a digit...
{1,2} one or two times
) end group
? make the entire group optional
<input type="text" onkeyup="onlyNumeric(event)" class="form-control" id="ColumnName" name="ColumnName">
<script>
function onlyNumeric(evt) {
var rx = /^\d+(?:\.\d{1,2})?$/;
var ele = document.getElementById("ColumnName");
if(rx.test(ele.value)) {
console.log("true");
}else{
console.log("false");
}
}
</script>
Another solution using addEventListener() instead of onkeyup:
<input type="text" class="form-control" id="ColumnName" name="ColumnName">
<script>
function onlyNumeric(evt) {
var rx = /^\d+(?:\.\d{1,2})?$/;
var ele = document.getElementById("ColumnName");
if(rx.test(ele.value)) {
console.log("true");
}else{
console.log("false");
}
}
var el = document.getElementById("ColumnName");
el.addEventListener("input", onlyNumeric, false);
</script>
Use this jquery plugin it validate decimal behaviour while typing and mouse click
https://github.com/sarkfoundation/Decimal-Behavior
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type='text/javascript' src="https://rawgit.com/sarkfoundation/Decimal-Behavior/master/sark-decimal/sark-decimal.js"></script>
<input type="text" data-behaviour="decimal">
I'm trying to prevent user from entering anything except numbers and letters, but my code doesn't even allow them itself. What could be the reason? Here's my code snippet:
$(document).ready(function(){
$("#txtuname").keypress(function(e){
var validExp = /^[0-9a-z]+$/gi;
var val = $(this).val();
if(val.match(validExp))
{
$("#errmsg").html("");
return true;
}
else
{
$("#errmsg").html("Number and letters Only");
return false;
}
});
});
<input type="text" name="txtuname" id="txtuname" />
<span id="errmsg"></span>
JSFiddle
$(document).ready(function () {
$("#txtuname").keypress(function (e) {
var validExp = /^[0-9a-z]+$/gi;
if (validExp.test(e.key)) {
$("#errmsg").html("");
return true;
}
else {
$("#errmsg").html("Number and letters Only");
return false;
}
});
});
You can use keyup not keypress
$(document).ready(function(){
$("#txtuname").keyup(function(e){
var validExp = /^[0-9a-z]+$/gi;
var val = $(this).val();
if(val.match(validExp))
{
$("#errmsg").html("");
return true;
}
else
{
$("#errmsg").html("Number and letters Only");
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<input type="text" name="txtuname" id="txtuname" />
<span id="errmsg"></span>
You can substitute input event for keypress event; adjust RegExp to /[0-9a-z]/i, use .split() with parameter "", Array.prototype.every(), RegExp.prototype.test() to check each character of input value at if condition; if each character is a digit or a letter condition is true, else false replace invalid characters of value using .replace() with RegExp /[^0-9a-z]/ig
$(document).ready(function() {
var validExp = /[0-9a-z]/i;
$("#txtuname").on("input", function(e) {
var val = this.value;
var check = val.split("").every(function(value) {
return validExp.test(value)
});
if (check) {
$("#errmsg").html("");
return check;
} else {
this.value = val.replace(/[^0-9a-z]/ig, "");
$("#errmsg").html("Number and letters Only");
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<input type="text" name="txtuname" id="txtuname" />
<span id="errmsg"></span>
You issue is you are not getting the value of the key that is being pressed. If you set the val variable like so, it will work as expected.
var val = String.fromCharCode(e.keyCode)
This gets the ASCII code of the key pressed, and then converting to the letter or number it represents. Then you can check against your regex.
This is because keypress events are fired before the new character is added to the value of the element (so the first keypress event is fired before the first character is added, while the value is still empty). You should use keyup instead, which is fired after the character has been added reference.
Here is the code
html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<input type="text" name="txtuname" id="txtuname" />
<span id="errmsg"></span>
js
$(document).ready(function(){
$("#txtuname").keyup(function(e){
var validExp = /^[0-9a-z]+$/gi;
var val = $(this).val();
if(val.match(validExp))
{
$("#errmsg").html("");
return true;
}
else
{
$("#errmsg").html("Number and letters Only");
return false;
}
});
});
$(document).ready(function(){
$("#txtuname").keyup(function(e){
var validExp = /^[0-9a-z]+$/gi;
var val = $(this).val();
if(validExp.test(val))
{
$("#errmsg").html("");
return true;
}
else
{
// fix the value of input field here
$(this).val("");
$("#errmsg").html("Number and letters Only");
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="txtuname" id="txtuname" />
<span id="errmsg"></span>
You need to use keyup so that the character is "added" already to the value if you're going to use this given technique.
Since String.prototype.match actually returns an array of the match, it won't work in the way you want it to. Not to mention that it is much more expensive than RegEx.prototype.test.
Bonus
You can use the technique of finding carret position in an input field shown in Get cursor position (in characters) within a text Input field
To actually fix the input field on keyup.
alright, whats wrong with my script, JShint is throwing three lines of red code saying i have issues in my variable and my if/else statement. I am trying to validate if the phone number is a valid USA phone format
$( "#phone" ).focusout(function telephone() {
if( this.value === "" || this.value === null ) {
$( "#error_messages" ).text("");
return false;
} else {
var re = \d{3}[\-]\d{3}[\-]\d{4};
if(re.test(document.getElementById("phone").value)) {
$( "#error_messages" ).text("");
return true;
} else {
$( "#error_messages" ).text("Phone Number* not a valid format xxx-xxx-xxxx");
return false;
}
}
});
Firstly, you don't need a name for closure function. Secondly you have not enclosed regex with /..../.
var re = /\d{3}[\-]\d{3}[\-]\d{4}/;
You Should try this.
$(function(){
$("#phone").change(function telephone() {
if (this.value === "" || this.value === null) {
$("#error_messages").text("");
return false;
} else {
if (/\d{3}[\-]\d{3}[\-]\d{4}/.test($(this).val())) {
$("#error_messages").text("");
return true;
} else {
$("#error_messages").text("Phone Number* not a valid format xxx-xxx-xxxx");
return false;
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type="text" id="phone" />
<span id="error_messages"></span>
This is an expression tested on http://tools.netshiftmedia.com/regexlibrary/# for numbers. change it to /^\d{3}[\-]\d{3}[\-]\d{4}$/ in your JS code and apply regex code within /..../ in that tools
I applied
^\d{3}[\-]\d{3}[\-]\d{4}$
It's ok with your numbers :
I want to see if it's possible to block the enter key and replace it with a space. I'm also using form validation to only allow letters, numbers and some other specific characters like the dollar sign,minus, and period and so on.
Here is that code, I would like to see if I can combine them into one and be able to check for the validation and replace the key press with a space all in one code/call.
<script type="text/javascript">
function ValidateForm(form)
{
var str
str=document.getElementById('limitedtextarea').value
str=str.replace(/[^A-Za-z0-9.-:/$ ]/g, "");
document.getElementById('limitedtextarea').value=str
//return true;
}
</script>
<FORM action="sms_SendMessage.asp" method=post onsubmit="javascript:return ValidateForm(this)" target=_blank>
Thanks for the help...
In javascript, the line-break character is represented by \n. You could replace them by spaces in your validation function like this :
function ValidateForm(form)
{
var str
str=document.getElementById('limitedtextarea').value
str=str.replace(/[^A-Za-z0-9.-:/$ ]/g, "");
str=str.replace(/\n/g, " ");
document.getElementById('limitedtextarea').value=str
//return true;
}
If you remove the onsubmit and do not have a submit button, typing enter will not submit it.
<body>
<form>
<textarea></textarea>
</form>
<script>
(function(){
var txt = document.getElementsByTagName('TEXTAREA')[0];
txt.onkeypress = function(ev){
ev = ev || window.event;
if ( ev.keyCode === 13 ){
if (window.event) {
window.event.returnValue = false;
}
if (ev && ev.preventDefault) {
ev.preventDefault();
}
txt.value += ' ';
}
};
})();
</script>
</body>