How do I allow the user to only input a string? - javascript

function EnterCandidates() {
var candidateNameInputs = document.querySelectorAll('input[id^=C]'),
names = document.querySelectorAll('label[for^=V][id^=L_V]');
Array.prototype.forEach.call(names, function(label, index) {
if (candidateNameInputs[index].value !== candidateNameInputs[index].defaultValue) {
label.textContent = candidateNameInputs[index].value;
}
});
}
I have this code which gets the users input and changes the label with it but i want to add some code which only allows the user to enter letters of the alphabet. How would I go about this using this code?

If you are using modern browsers then user html5 validation -
<input type="text" name="name" class="field" pattern="[a-zA-Z ]+" />
It accepts a-z and A-Z plus space

listen to keyDown event and match with this regex:
/[a-zA-Z]+/
if you're targeting modern browsers only, you can try this:
<input type="text" pattern="[a-zA-Z]" title="Only letters" />

you can't avoid that the user types non alphabetic characters. But you can:
- control the input fields (onkeydown) and check if there are some characters you don't want Stackoverflow - force input to only alpha-letters
- do the same before the
label.textContent = candidateNameInputs[index].value;
line and filter/replace the characters you don't want

var val = document.getElementById('id').value;
if (!val.match(/^[a-zA-Z]+$/))
{
alert('Only alphabets are allowed');
return false;
}
full script
function EnterCandidates() {
console.log('woo');
var candidateNameInputs = document.querySelectorAll('input[id^=C]'),
names = document.querySelectorAll('label[for^=V][id^=L_V]');
Array.prototype.forEach.call(names, function (label, index) {
if (!candidateNameInputs[index].value.match(/^[a-zA-Z]+$/))
{
alert('Only alphabets are allowed');
}
else
{
if (candidateNameInputs[index].value !== candidateNameInputs[index].defaultValue) {
label.textContent = candidateNameInputs[index].value;
}
}
});
}

Here is one way to do it using Javascript.
http://jsfiddle.net/q60gm0ra/
var input = document.getElementById('alpha');
input.addEventListener('keypress',function(e) {
var str = String.fromCharCode(e.charCode);
if (!(/[A-Z]|\s/i).test(str)) {
e.preventDefault();
}
});

Related

Remove characters from a string that are not firstname/surname characters

Please see the code below:
#HostListener('paste', ['$event'])
onPaste(event) {
var test = event.clipboardData.getData('text');
var removedNumbers = test.replace(/[0-9]/g, '');
}
Numbers are removed from the pasted text. It is a surname field, so should also exclude characters like {[}] etc.
How can I remove characters that are not valid for a name? I have read lots of simlar questions today like this one: how do i block or restrict special characters from input fields with jquery?. However, I have not found an answer to my specific question.
[^ ] matches anything(including space) that is not enclosed in the brackets, so you could place all characters you don't want to be removed inside the bracket. Note, however, that you have to escape special characters if they are part of the match. Also note that
you can specify a range of characters by using a hyphen, but if the
hyphen appears as the first or last character enclosed in the square
brackets it is taken as a literal hyphen to be included in the
character set as a normal character.
const regex = /[^a-z,' -]/gi;
console.log("Conan O'Brien".replace(regex, ''));
You may also use Unicode character ranges for non-English names, for example
for Chines 4e00 to 9fa5,
for most of Latin 0061 to 007A & 00DF to 00F6 & 00F8 to 01BF & 01C4 to 024F
for Geʽez 1200 to 135A
const regexLatin = /[^\u0061-\u007A\u00DF-\u00F6\u00F8-\u01BF\u01C4-\u024F ]/gui;
const regexChina = /[^\u4e00-\u9fa5 ]/gui;
const regexGeez = /[^\u1200-\u137F ]/gui;
console.log("Björk Guðmundsdóttir".replace(regexLatin, ''));
console.log("陳港生".replace(regexChina, ''));
console.log("ምኒልክ".replace(regexGeez, ''));
However, this is not an exhaustive list, you may refer to the List_of_Unicode_characters to make adjustments for your specific need.
Trying to match all names from 'all' languages could be very hard. The good news, however, is that Unicode_Property_Escapes are part of the ECMAScript 2020 Specification( currently on draft stage ) which will simplify the process a lot.
For example to match for Latin characters, you would use: /\p{Script=Latin}/u,
and to match for letters from 'all' languages, you would use: /\p{Letter}/gu or the short form /\p{L}/gu
Try this.
Vanilla Javascript
document.addEventListener("paste", event => {
event.preventDefault();
let clipboardData = event.clipboardData.getData("Text");
clipboardData = clipboardData.replace(/[0-9_!¡?÷?¿/\\+=##$%\ˆ&*(){}|~<>;:[\]]/g, "");
let allowedPasteTarget = ['textarea', 'text']
if (allowedPasteTarget.includes(document.activeElement.type)) {
let prevText = document.activeElement.value;
document.activeElement.value = prevText + clipboardData;
}
});
//To handle the copy button, [Optional]
document
.getElementById("copy-text")
.addEventListener("click", function(e) {
e.preventDefault();
document.getElementById("text-to-copy").select();
var copied;
try {
copied = document.execCommand("copy");
} catch (ex) {
copied = false;
}
if (copied) {
document.getElementById("copied-text").style.display = "block";
}
});
<div>
<input type="text" id="text-to-copy" placeholder="Enter text" />
<button id="copy-text">Copy</button>
<span id="copied-text" style="display: none;">Copied!</span>
</div>
<div>
<textarea name="paste-area" id="paste-area" cols="30" rows="10" placeholder="Paste it here"></textarea>
</div>
Angular
#HostListener('paste', ['$event'])
onPaste(event) {
var test = event.clipboardData.getData('text');
var removedNumbers = test.replace(/[0-9_!¡?÷?¿/\\+=##$%\ˆ&*(){}|~<>;:[\]]/g, '');
let allowedPasteTarget = ['textarea', 'text']
if (allowedPasteTaeget.includes(document.activeElement.type)) {
let prevText = document.activeElement.value;
document.activeElement.value = prevText + clipboardData;
}
}

Allow space in textbox only if any existing characters or number in that

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 with JavaScript form validation?

I have created a validate function using JavaScript. I need a validation that tests that password field in a form to make sure it is:
At least 8 characters.
Contains a numeric value.
Contains an alphabetic value.
I just need an If statement inside my validate function
function Validate()
{
with(document.memberInfo) {
evt = new userInfo(username.value, password.value, email.value, firstname.value, lastname.value, age.value, description.value);
}
with(evt)
{
if((email.indexOf("#",0)==-1))
{
alert("The email must contain the # symbol.");
return false;
}
evt.printEvent();
}
return true;
}
using regx function you can validate ur form . here is the code .
var xstr="^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$";
var str=Document.getElementById("id").value;
var ck=xstr.exec(str);
if(!ck || ck[0]!=str){
//code
}
you can use regex "/^(?=.*[0-9])(?=.*[a-zA-Z]).{8,}$/" refer this link stackoverflow
JsFiddle
var regex = /^(?=.*[0-9])(?=.*[a-zA-Z]).{8,}$/;
function getValue() {
return document.getElementById("myinput").value;
}
function test() {
alert(regex.test(getValue()));
}
function match() {
alert(getValue().match(regex));
}
<input type="text" id="myinput" value="vexillology"/>
<button id="testBtn" onclick=test()>test</button>
<button id="matchBtn" onclick=match()>match</button>
Using regex is the way to go, but the more readable solution is probably:
function isValid(pass) {
return pass.length >= 8 && // at least 8 characters
/\d/.test(pass) && // contains a digit
/[A-Za-z]/.test(pass); // contains a letter
}
function isValid(pass) {
return pass.length >= 8 &&
/\d/.test(pass) &&
/[A-Za-z]/.test(pass);
}
var field = document.getElementById("password");
var output = document.getElementById("output");
field.onkeyup = function() {
output.innerHTML = isValid(field.value) ? "Valid" : "Not Valid";
}
<input type="text" id="password" placeholder="Enter password" />
<span id="output"></span>
Alternatively, you can put it all in one regex:
function isValid(pass) {
return /^(?=.*[A-Za-z])(?=.*\d).{8,}$/.test(pass);
}
JSFiddle

How to add a validation error message next to a field using jQuery

Hi have a form with a few fields. Amongst them:
<div>
<label for="phoneNumber" class="label">Phone Number</label>
<input name="phoneNumber" type="text" id="phoneNumber" size="13" style="float:left;margin-right:10px;">
</div>
<div>
<input type="checkbox" name="activePN" id="activePN" checked >
<label for="activePN">Active</label>
</div>
The, when the form is submited, I want to validate the input and write next to each field for whichever field didn't validate. Like this:
$('#submit').click(function () {
var proceed = true;
var strippedPN = $('#phoneNumber').val().replace(/[^\d\.]/g, '').toString(); //strips non-digits from the string
if (strippedPN.length !== 10) {
$('#phoneNumber').text('<p>Phone number has to be 10 digits long.</p>')
proceed = false;
}
...
...
...
});
I was hopping that adding those <p> </p> tags would do it. But they don't...
Note: I also tried with html() instead of text() and with activePN instead of phoneNumber.
Use .after().
$('#phoneNumber').after('<p>Phone number has to be 10 digits long.</p>')
It might be wise to add a class to your p tag too, so you can remove them when the number is edited to be correct.
Try:
$('#submit').click(function(){
var proceed = true;
var strippedPN = $('#phoneNumber').val().replace(/[^\d\.]/g, ''); //strips non-digits from the string - already a String
if(strippedPN.length !== 10){
$('#phoneNumber').after('<p>Phone number has to be 10 digits long.</p>')
proceed = false;
}
}
Its best to use jqueryvalidation plugin.
But in some scenario may be you need to show validation message using custom code, then below may help.
Code
var errorSeen = false;
$('#txtname').keyup(function (e) {
var validInput = false; // TODO set your validation here
if (!validInput) {
var errorMessageVisible = $(".validationMessage").is(":visible");
if (errorSeen === false && errorMessageVisible === false) {
$('#txtname').style.borderColor = "red";
$('#txtname').after("<span class='validationMessage' style='color:red;'>
Name is required.</span>");
errorSeen = true;
}
}
else {
$('#txtname').style.borderColor = "";
var errorMessageVisible = $(".validationMessage").is(":visible");
if (errorMessageVisible)
$(".validationMessage").remove();
errorSeen = false;
}
});

Javascript - validation, numbers only

I'm trying to get my login form to only validate if only numbers were inputted. I can it to work if the input is only digits, but when i type any characters after a number, it will still validate etc. 12akf will work. 1am will work. How can i get past this?
Part of the Login
<form name="myForm">
<label for="firstname">Age: </label>
<input name="num" type="text" id="username" size="1">
<input type="submit" value="Login" onclick="return validateForm()">
function validateForm()
{
var z = document.forms["myForm"]["num"].value;
if(!z.match(/^\d+/))
{
alert("Please only enter numeric characters only for your Age! (Allowed input:0-9)")
}
}
Match against /^\d+$/. $ means "end of line", so any non-digit characters after the initial run of digits will cause the match to fail.
Edit:
RobG wisely suggests the more succinct /\D/.test(z). This operation tests the inverse of what you want. It returns true if the input has any non-numeric characters.
Simply omit the negating ! and use if(/\D/.test(z)).
here is how to validate the input to only accept numbers this will accept numbers like 123123123.41212313
<input type="text"
onkeypress="if ( isNaN(this.value + String.fromCharCode(event.keyCode) )) return false;"
/>
and this will not accept entering the dot (.), so it will only accept integers
<input type="text"
onkeypress="if ( isNaN( String.fromCharCode(event.keyCode) )) return false;"
/>
this way you will not permit the user to input anything but numbers
This one worked for me :
function validateForm(){
var z = document.forms["myForm"]["num"].value;
if(!/^[0-9]+$/.test(z)){
alert("Please only enter numeric characters only for your Age! (Allowed input:0-9)")
}
}
Late answer,but may be this will help someone
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Use will be like
nn=document.forms["myForm"]["num"].value;
ans=isNumber(nn);
if(ans)
{
//only numbers
}
This ans was found from here with huge vote
Validate numbers in JavaScript - IsNumeric()
function validateNumber(e) {
const pattern = /^[0-9]$/;
return pattern.test(e.key )
}
<input name="username" id="username" onkeypress="return validateNumber(event)">
This approach doesn't lock numlock numbers, arrows, home, end buttons and etc
The simplest solution.
Thanks to my partner that gave me this answer.
You can set an onkeypress event on the input textbox like this:
onkeypress="validate(event)"
and then use regular expressions like this:
function validate(evt){
evt.value = evt.value.replace(/[^0-9]/g,"");
}
It will scan and remove any letter or sign different from number in the field.
No need for the long code for number input restriction just try this code.
It also accepts valid int & float both values.
Javascript Approach
onload =function(){
var ele = document.querySelectorAll('.number-only')[0];
ele.onkeypress = function(e) {
if(isNaN(this.value+""+String.fromCharCode(e.charCode)))
return false;
}
ele.onpaste = function(e){
e.preventDefault();
}
}
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
jQuery Approach
$(function(){
$('.number-only').keypress(function(e) {
if(isNaN(this.value+""+String.fromCharCode(e.charCode))) return false;
})
.on("cut copy paste",function(e){
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
The above answers are for most common use case - validating input as a number.
But to allow few special cases like
negative numbers & showing the invalid keystrokes to user before
removing it, so below is the code snippet for such special use cases.
$(function(){
$('.number-only').keyup(function(e) {
if(this.value!='-')
while(isNaN(this.value))
this.value = this.value.split('').reverse().join('').replace(/[\D]/i,'')
.split('').reverse().join('');
})
.on("cut copy paste",function(e){
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
Regular expressions are great, but why not just make sure it's a number before trying to do something with it?
function addemup() {
var n1 = document.getElementById("num1");
var n2 = document.getElementById("num2");
sum = Number(n1.value) + Number(n2.value);
if(Number(sum)) {
alert(sum);
} else {
alert("Numbers only, please!");
};
};
function ValidateNumberOnly()
{
if ((event.keyCode < 48 || event.keyCode > 57))
{
event.returnValue = false;
}
}
this function will allow only numbers in the textfield.
I think we do not accept long structure programming we will add everytime shot code see below answer.
<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" >
Using the form you already have:
var input = document.querySelector('form[name=myForm] #username');
input.onkeyup = function() {
var patterns = /[^0-9]/g;
var caretPos = this.selectionStart;
this.value = input.value.replace(patterns, '');
this.setSelectionRange(caretPos, caretPos);
}
This will delete all non-digits after the key is released.
var elem = document.getElementsByClassName("number-validation"); //use the CLASS in your input field.
for (i = 0; i < elem.length; i++) {
elem[i].addEventListener('keypress', function(event){
var keys = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0];
var validIndex = keys.indexOf(event.charCode);
if(validIndex == -1){
event.preventDefault();
}
});
}
If you are using React, just do:
<input
value={this.state.input}
placeholder="Enter a number"
onChange={e => this.setState({ input: e.target.value.replace(/[^0-9]/g, '') })}
/>
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<script type="text/babel">
class Demo extends React.Component {
state = {
input: '',
}
onChange = e => {
let input = e.target.value.replace(/[^0-9]/g, '');
this.setState({ input });
}
render() {
return (
<div>
<input
value={this.state.input}
placeholder="Enter a number"
onChange={this.onChange}
/>
<br />
<h1>{this.state.input}</h1>
</div>
);
}
}
ReactDOM.render(<Demo />, document.getElementById('root'));
</script>
// I use this jquery it works perfect, just add class nosonly to any textbox that should be numbers only:
$(document).ready(function () {
$(".nosonly").keydown(function (event) {
// Allow only backspace and delete
if (event.keyCode == 46 || event.keyCode == 8) {
// let it happen, don't do anything
}
else {
// Ensure that it is a number and stop the keypress
if (event.keyCode < 48 || event.keyCode > 57) {
alert("Only Numbers Allowed"),event.preventDefault();
}
}
});
});
Avoid symbols like "." "," "+" "-". I tried it and it works fine.
$('#example').keypress(function (evt) {
if (evt != null && evt.originalEvent != null && /\D/.test(evt.originalEvent.key)) {
evt.preventDefault();
evt.stopImmediatePropagation();
return false;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="example" id="example">

Categories

Resources