javascript validation for home address. Ex: #55 Bernahrd Gym - javascript

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/

Related

How can I use javascript to index input from a HTML form?

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}).

Regex to prevent accented letters in the input

I want to block the entry of accented letters (any language) in input, preferably I would like this block to be done with regex through the attribute pattern
I tried something but I did not succeed...
<form>
<label for="username">Name <i>(only letters without accent)</i></label>
<br>
<input name="username" id="username" type="text" pattern="[A-Za-z]+" oninvalid="this.setCustomValidity('Only letters without accent')">
</form>
Accepts: Joao Silva, Pedro, Fabio Duarte...
Rejects: João Silva, Pedro Camões, Fábio Duarte ...
<input name="username" id="username" type="text"
pattern="[A-Za-z ]*" title="Latin letters and space characters only"> />
Test this code here.
Alternatively, you can control what characters are allowed during typing.
<input name="username" id="username" type="text" onCopy="return false"
onDrag="return false" onDrop="return false" onPaste="return false"
autocomplete=off />
jQuery:
$(document).ready(function() {
$("#username").keypress(function(event) {
var inputValue = event.which;
if(!((inputValue >= 65 && inputValue <= 90) || // A-Z
(inputValue >= 97 && inputValue <= 122) || // a-z
(inputValue == 32))) { // space
event.preventDefault();
}
});
});
Test this code here.
Original Answer
As specified in the question, it sounds like you want to block anything other than basic Latin alphabet letters and spaces, which is doable with a pattern attribute - the regex is ^[a-zA-Z ]+$.
Edit 2020-08-19
The question asks specifically about "accented letters", not non-Latin-alphabet characters or non-ASCII characters. As of 2020, and assuming you don't need to support Internet Explorer, this is actually fairly simple to check for in JavaScript.
Explanation
NFD normalization splits apart all diacritics from their base characters. The regex /\p{M}/u matches anything in the Unicode "Mark" category, such as all those diacritics we just split apart.
const hasDiacritics = str =>
/\p{M}/u.test(str.normalize('NFD'))
// tests
;[
'Joao Silva',
'Pedro',
'Fabio Duarte',
'João Silva',
'Pedro Camões',
'Fábio Duarte',
'Αρσένιος',
'Αρσενιος',
'Александра',
'李晓华',
].forEach(str => {
console.log(str, hasDiacritics(str))
})
You could use a similar method to strip diacritics:
const stripDiacritics = str =>
str.normalize('NFD').replace(/\p{M}+/gu, '')
stripDiacritics('ZA̡͊͠͝LGΌ ISͮ̂҉̯͈͕̹̘̱ TO͇̹̺ͅƝ̴ȳ̳ TH̘Ë͖́̉ ͠P̯͍̭O̚​N̐Y̡ H̸̡̪̯ͨ͊̽̅̾̎Ȩ̬̩̾͛ͪ̈́̀́͘ ̶̧̨̱̹̭̯ͧ̾ͬC̷̙̲̝͖ͭ̏ͥͮ͟Oͮ͏̮̪̝͍M̲̖͊̒ͪͩͬ̚̚͜Ȇ̴̟̟͙̞ͩ͌͝S̨̥̫͎̭ͯ̿̔̀ͅ')
// => "ZALGΟ IS TOƝy THE PO​NY HE COMES"
Caveats
As pointed out in the article #Stephen P links to in the comment below, this is probably a bad idea. It's worth thinking carefully about whether you want to risk annoying or even offending your users by forcing them to enter something that isn't their real name.

Remove http:// and www from form field while customer is typing, and show alert?

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().

Textarea with javascript validation

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.

Only accept number from 1 to 9 Using JavaScript

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/

Categories

Resources