How can I validate the following textarea using a pure Javascript not Jquery? Can anyone help me please.
<script>
function val()
{
// 1. only allowed alphanumeric characters, dash(-), comma(,) and no space
// 2. alert if person is trying to input not allowed chars as in 1.
}
</script>
<form>
<textarea name="pt_text" rows="8" cols="8" class="input" onkeydown="return val();"></textarea>
</form>
Try something like:
document.querySelector('.input').onkeypress = function validate(e) {
if (String.fromCharCode(e.keyCode).match(/[\w,-]/) == null) {
alert('not allowed');
e.preventDefault();
}
};
DEMO
Edit: As pointed out by tenub, \w also allows _, so modify the regex to: /[A-Za-z0-9,-]/
DEMO
This regex will match only valid strings:
/^[\w,-]*$/
Use + instead of * if you don't allow empty strings.
Related
I have a form where you must enter a username, but the username cannot start or end with a period (.). This is what I have so far, I feel like I'm close. I think I am making an error in the .value[0] parts.
//Checking Username
if (document.getElementById("uName").value[0] == "." || document.getElementById("uName").value[-1]) {
document.getElementById("notification4").innterHTML ="Cannot have period at start or end.";
submitForm = false;
} else {
document.getElementById("notification4").innerHTML="";
}
My second question is how would I be able to stop the same character from repeating twice in a row? For example you can't have (--) , (//), (%%), (**) etc. I would prefer a similar method to use like above or with regex.
This is the forms HTML:
<label for="uName"> Username: </label><br>
<input type="text" id="uName" name="uName"> <br>
<div class= "error" id="notification4"></div><br>
You can use regular expression and the RegExp.prototype.test() function:
const regex = /^[.]|[.]$|[^a-zA-Z0-9]{2}/g;
if(regex.test(str)) {
//code when it matches
} else {
//code when it doesn't match
}
This checks if the first or last character is a dot (^[.]|[.]$) and if there is any character repeated twice that is not a letter or number ([^a-zA-Z0-9]{2}).
I am finding a way to make all the text boxes in the website only accept roman characters. Is there any easy way to do it globally.
Thanks in advance.
In modern browsers <input> accepts an attribute called pattern. This allows to restrict the valid characters in a given field.
input:invalid {
background-color:red;
}
<form>
<input type="text" pattern="[a-zA-Z\s\.\-_]+" />
<button type="submit">Submit</button>
</form>
For all other browsers you can find all form field via jQuery, check if a pattern-attribute exists, and check it against the value of a given field. You may also replace disallowed characters:
$('form').on('keyup blur','input',function() {
if ($(this).val() && $(this).attr('pattern')) {
//var pattern = new RegExp('^'+$(this).attr('pattern')+'$', 'g');
//$(this).toggleClass('invalid', pattern.match(!$(this).val()));
var pattern = new RegExp($(this).attr('pattern').replace(/\[/,'[^'), 'g');
$(this).val($(this).val().replace(pattern,''));
}
});
input:invalid {
background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<form>
<input type="text" pattern="[a-zA-Z\s\.\-_]+" />
<button type="submit">Submit</button>
</form>
Oh, you still want to validate form inputs on the server-side. All HTML- or Javascript-stuff does not prevent all visitors of your site to submit broken stuff.
I will refer to the marked answer for the following question for the regex which filters out non-roman characters:
How to detect non-roman characters in JS?
Spoiler: the regex is /[^\u0000-\u024F\u1E00-\u1EFF\u2C60-\u2C7F\uA720-\uA7FF]/g
Now all you need is a little bit of tinkering with jQuery:
var myInputId = "#foo"; // Or whatever you wish to use.
var input = $(myInputId);
var exp = /[^\u0000-\u024F\u1E00-\u1EFF\u2C60-\u2C7F\uA720-\uA7FF]/g;
input.blur(function() {
input.value = input.value.replace(exp, "");
});
Include this snippet into your master page for example:
<script>
$(function(){
$('input[type=text],textarea').keypress(function(e){
var char = String.fromCharCode(e.which || e.charCode);
var rgx = /[\u0000-\u007F]/;
if (rgx.test(char) == false)
return false;
})
})
</script>
Here is my idea based on #fboes answer.
I also needed to show user whats wrong, so there is error message showing but with no redundancy when typing couple of forbidden characters in a row.
//I wanted first to assign pattern attr to every input in form but when it's happening, all "\" chars are removed from regex therefore - it doesn't work, so I had to add it in templates for every input.
let isIncorrect = false;
scope.checkPattern = function(e) {
// I don't want to allow Chineese, cyrylic chars but some other special - yes
var pattern = new RegExp('[a-zA-Z\s\.\-_äÄöÖüÜßąćęłńóśźżĄĆĘŁŃÓŚŹŻ]+', "g");
if ($(e).is(':valid')){
return true
} else {
$(e).val($(e).val().replace(pattern,''));
return false
}
};
scope.removeAlert = function (e){
$(e).parent().find('.text-danger').remove();
isIncorrect = false;
}
// unallowed characters in order inputs
$('.my-form').on('keyup blur','input',function(e) {
if (!scope.checkPattern($(this))) {
if (!isIncorrect){
// show this error message but only once (!) and for specified period of time
$(this).parent().append('<p class="text-danger">Only latin characters allowed</p>');
isIncorrect = true;
}
setTimeout(scope.removeAlert, 3000, $(this));
}
});
I have a form in which is a field (#domain).
Here I want the customer to add their own domain name. Often I see that they input wrong, even thought the instructions are short and clear.
To make it more user friendly, and to avoid errors - I'd like to add a validator or auto corrector.
This is a jquery and bootstrap environment.
This is the solution I have made for now:
http://jsfiddle.net/Preben/ew1qoky9/1/
<form>
<input placeholder="input your domain (WITHOUT http:// and www.)" class="form-control" name="domain" type="text" autocomplete="off" id="domain" style="max-width:320px">
</form>
and the javascript:
$('#domain').keypress(function (e) {
var regex = new RegExp("^[a-zA-Z0-9\-_.]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
});
This removes all special caracters and spaces on the fly. However without telling the customer.
Customers still input http:// and http://www. - and I'd like to auto-remove these too.
Can I add something in the regex or js to make this happen? - Or what is a suggested working solution?
Is there a way to show a message/ alert if the customer enters a special caracter? Like "Please use only a-z, 0-9 and dots. If your domain has special caracters, please enter the ACE-version of your domain name." - Either a bootstrap alarm, or a standard js alert?
PS: I found this: Regex for dropping http:// and www. from URLs about removing the above from urls, but I don't understand how to use this in my code. I am very thankful for suggestions. Please play with the fiddle :-)
Per your code, user cannot type special characters like :// but user can paste it. To handle such cases, you can validate it on blur event. Following is the fiddle depicting same. Also I have added a simple check for"http", and will show error if http is entered. You can configure per your requirement.
Code
(function() {
var regex = new RegExp("^[a-zA-Z0-9\-_.]+$");
$('#domain').keypress(function(e) {
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
$("#lblError").text("Please use only a-z, 0-9 and dots.").fadeIn();
e.preventDefault();
return false;
});
$("#domain").on("blur", function(e) {
var str = $(this).val();
if (regex.test(str)) {
if (str.indexOf("http") >= 0) {
$("#lblError").text("Domain name cannot have HTTP in it.").fadeIn();
return false;
}
$("#lblError").fadeOut();
} else {
$("#lblError").text("Please use only a-z, 0-9 and dots.").fadeIn();
return false
}
});
})()
.error {
color: red;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<input placeholder="input your domain (WITHOUT http:// and www.)" class="form-control" name="domain" type="text" autocomplete="off" id="domain" style="max-width:320px">
<p class="error" id="lblError"></p>
</form>
Here you go:
$('#domain').on('input', function() {
rawInput = $(this).val();
console.log(rawInput);
cleanInput = rawInput.replace('www.', '');
cleanInput = cleanInput.replace('http://', '');
cleanInput = cleanInput.replace('https://', '');
console.log(cleanInput);
$(this).val(cleanInput);
});
See it in action here:
https://jsbin.com/birunuyeso/edit?html,js,console,output
Look at your JavaScript console and you'll see what it's doing. In production you can obviously remove any of the lines that use console.log().
I need a validation for address that can have Numbers, alphabets, space in two words should be able .. but no space in the beginning of the address.
The only symbol should be #
EX: #55 Bernahrd Gym
Address:<input type="text" required="required" name="baguio_add"><br>
You can use regular expressions for this: /[a-z0-9\s\#]+/i
Instead of testing for spaces at the start, just use trim (or ltrim).
Edit: You changed your tag to Javascript, you can still use regular expressions for this using the regex above.
You can use this regex if you want only one #, and any number of alpha numeric plus spaces.
/#?[a-zA-Z\s\d]+/
If it always starts with # then:
/^(#?)[a-zA-Z\s\d]+$/
Here is how you use it:
HTML:
<input name="address" id="address" type="text" />
Javascript:
document.getElementById('address').onblur = function (e) {
console.log(this.value);
var isValid = /^(#?)[a-zA-Z\s\d]+$/.exec(this.value);
if (isValid){
// do any action on valid
this.className = 'valid';
} else {
this.className = 'invalid';
}
}
Here is a working example in jsfiddle: https://jsfiddle.net/uua6pp1q/
Would like to know how to only accept number to be entered into inputbox from 1 to 9 and if entered for example 0 give alert message, sorry not a valid number.
please check my function that i have done so far, but not working.. thank you
<input name="number1" type="text" size="1" id="number1"onkeyup="doKeyUpValidation(this)/>
doKeyUpValidation(text){
var validationRegex = RegExp(/[-0-9]+/, "g");
if(!validationRegex.match(text.value)
{
alert('Please enter only numbers.');
}
You're missing a closing quote at the end of your onkeyup attribute, and as David mentions, you need to change your regex string to /[1-9]/
You were pretty close. Try this:
function doKeyUpValidation(text) {
var validationRegex = RegExp(/[1-9]+/, "g"); // The regex was wrong
if( !validationRegex.match(text.value) )
{
alert('Please enter only numbers.');
}
} // this was missing before
Your HTML is slightly wrong, it should be:
<input name="number1" type="text" size="1" id="number1" onkeyup="doKeyUpValidation(this)"/>
You need a space between each attribute, and each attribute needs to be quoted.
Also, your JavaScript has a few errors. It should be:
function doKeyUpValidation(text) {
var validationRegex = /[1-9]/g;
if (!validationRegex.test(text.value)) {
alert('Please enter only numbers.');
}
}
You need the function keyword to make doKeyUpValidation a function. Also, your regex was a little off.
Demo: http://jsfiddle.net/EqhSS/10/