Make Textbox with Value of All Spaces Invalid [duplicate] - javascript

This question already has answers here:
Trim string in JavaScript
(20 answers)
Closed 8 years ago.
I have these scripts...
Name: <input type="text" id="inputName" onblur="verifyName(this.value)">
<script type="text/javascript">
function verifyName(nameInput)
{
if(nameInput=="")
{
// error
alert('please enter your name');
}
else
{
// accepted
}
}
</script>
This will display an error if the user don't want to enter his/her name on the textbox.
What if the user is lazy and he/she will enter " " (a space or more) as a name? This can be accepted by the JavaScript. It will return false on the if condition.
But I want the user not to enter only spaces. Is there any way to do that?
Note: Any number of spaces (without any letters) inputted are invalid.
If the user inputs one of the texts below, JavaScript should accepts/rejects the input as follows...
"John" --> valid
"" --> invalid
"John Doe" --> valid
" " --> invalid
"John Doe" --> valid (can be edited to remove too many spaces)
" Kim" --> valid (can be edited to remove too many spaces)
" " --> invalid

function verifyName(nameInput)
{
nameInput = nameInput.trim();
if(nameInput=="")
{
// error
alert('please enter your name');
}
else
{
// accepted
}
}
The trim() function will remove all spaces. If there are only spaces in the var, trim() with return "".

Trim the string before you do the checking. See below
if(nameInput.trim()=="")
{
// error
alert('please enter your name');
}
else
{
// accepted
}

One (of quite a few) possible implementation of your function uses regular expressions:
function verifyName(nameInput) {
return input.match(/\w{1,12}/) === null ? false : true;
// ^^
// Or some other sensible limitation to the length of a name.
}

You can make use of regular expression to replace all the spaces from the string and then check its length. If there is at least one character remaining after removing all the spaces - that's your valid case right?
testInput = function(){
var inpStr = $('#txtInp').val();
var teststr = inpStr.replace(/\s/g, "");
//$('#testStrDiv').text(teststr);
if((teststr.length)&&(teststr.length>0))
{
$('#divOutp').html('<b>Valid! </b>');
}
else{
$('#divOutp').html('<b>Invalid! </b>');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="txtInp" />
<input type="button" onclick="testInput()" value="test" />
<div id="testStrDiv" />
<div id="divOutp" />

Related

Why HTML5 input type email doesn't allow empty space?

I use input type=email in my application. Prior to that in the old system developers user input type=text. Recently I was asked to fix the 'issue' in my code. The problem was reported by user when entering email address in the input field, accidentally empty space was entered on the end. Then user tried to Save the form, and error message was displayed under the email field This field is mistyped. I'm wondering if this is the way type=email should work and prevent empty space in the email address fields?
I tested this problem in Chrome and empty space will not be detected, but in Firefox will be and error message will show up.
$("#save").on("click", function() {
console.log(verifyFields('my-form'));
if (verifyFields('my-form')) {
alert('Saved!');
}
});
function verifyFields(containerID, includeInvisible) {
includeInvisible = includeInvisible || false;
let isValid = true;
const hdlMap = {
//'valueMissing': "This field is required",
//'patternMismatch': "This field is invalid",
'tooLong': "This field is too long",
'rangeOverflow': "This field is greater than allowed maximum",
'rangeUnderflow': "This field is less than allowed minimum",
'typeMismatch': "This field is mistyped"
};
const arrV = Object.keys(hdlMap);
const invalidInputs = [];
$("#" + containerID).find("input,textarea,select").each(function() {
var curItem$ = $(this);
var errMsg = [];
var dispfld = curItem$.data("dispfld");
var label = curItem$.data("label");
if (includeInvisible || curItem$.is(":visible")) {
if (curItem$[0].validity.valid) {
curItem$.removeClass("is-invalid");
return;
}
if (curItem$[0].validity['valueMissing']) {
var reqMsg = label ? label + " field is required" : "This field is required";
errMsg.push(reqMsg);
}
if (curItem$[0].validity['customError'] && dispfld) {
errMsg.push(dispfld);
}
if (curItem$[0].validity['patternMismatch'] && dispfld) {
errMsg.push(dispfld);
}
arrV.forEach(function(prop) {
if (curItem$[0].validity[prop]) {
errMsg.push(hdlMap[prop]);
}
});
if (errMsg.length) {
if (!curItem$.next().is(".invalid-feedback")) {
curItem$.after('<div class="invalid-feedback"></div>');
}
curItem$.addClass("is-invalid").next().text(errMsg.join(' and '));
invalidInputs.push(curItem$);
isValid = false;
} else {
curItem$.removeClass("is-invalid");
}
}
});
if (invalidInputs.length) {
invalidInputs[0].focus();
}
return isValid;
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="my-form" id="my-form">
<input type="email" name="user-email" id="user-email" required>
<button type="button" id="save">Save</button>
</form>
a space isn't a valid character for an input type="email" because we can't have email addresses with spaces in them (A).
So in this case you have an unfortunate scenario where the space isn't in the middle of the email address, but at the beginning or end. But if you look at the validation that the browser follows for this input type, it still won't be allowed.
You have two options:
Set it back to input type="text", but set the same validation pattern that applies for emails: <input type="text" pattern="/^[a-zA-Z0-9.!#$%&'*+\/=?^_{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$" /> and then modify that regex to allow for ending spaces (though you need to check on the back-end to make sure it will allow them, or otherwise you need to do a .trim() to remove those surrounding spaces.
Do a .trim() on your input after the user exits the input; removing whitespaces at the start or end.
(A) According to this answer:
space and "(),:;<>#[] characters are allowed with restrictions (they are only allowed inside a quoted string...

Regex disallow accented characters [duplicate]

This question already has answers here:
Match exact string
(3 answers)
Closed 4 years ago.
I want the user to only be able to enter English characters, the code below works but on a mac if you hold the letter "a" for example you can insert accented characters such as "á". I've tried a few different approaches with keydown, keyup etc but even on the release of the key it thinks the value that was entered is "A" so it gets past the regex. Anyone know whats going wrong or a better way on how to do this please?
$('.monogram-letters').on("keypress", function(e) {
var englishAlphabet = /[A-Za-z]/g;
var key = String.fromCharCode(e.which);
if (englishAlphabet.test(key)) {
console.log('true');
return true;
} else {
console.log('false');
}
return false;
});
$('.monogram-letters').on("paste", function(e) {
e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" value="" class="monogram-letters valid" maxlength="3" id="options-41-container" name="options[41]" data-category="41" data-val="type your letters (up to 3)" required="" aria-required="true" aria-invalid="false">
You can instruct an input text to accept only english characters doing so:
<input pattern="[a-z]" />
You will want to validate server-side as well obviously.
The solution I ended up going for was to check the final string and then just emptying the input if it had an accented character
var $monogramInput = $('.monogram-letters');
var englishAlphabet = /^[a-z]+$/i;
$monogramInput.on("keypress", function(e) {
var key = String.fromCharCode(e.which);
if(englishAlphabet.test(key)) {
return true;
}
return false;
}).blur(function() {
var enteredValue = $(this).val();
if(!enteredValue.match(englishAlphabet)) {
$(this).val('');
}
});

How to delete extra spaces in an input type="text"? [duplicate]

This question already has answers here:
How to remove the extra spaces in a string?
(12 answers)
Strip white spaces on input
(4 answers)
Closed 5 years ago.
I got this input type="text" and this button which shows the users input, but if the input have extra spaces, them will be showed too.How to remove these extra spaces form the input value?
var nameInput = $('#name');
function showName() {
if (nameInput.val() === "") {
alert('You must provide a Name');
}
else {
alert('¡Hello' + ' ' + nameInput.val() + '!')
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="name" />
<button type="button" onclick="showName()"> Show Name </button>
Use .trim() to remove extra spaces to remove trailing and preceding spaces.
To remove any multiple occurrence of space then use .replace(/\s+/g,' ').trim();
var _name = nameInput.val().trim();
if (_name === "") {
alert('You must provide a Name');
}
else {
alert('¡Hello' + ' ' + _name + '!')
}
You can call trim(), as in nameInput.val().trim()
Edit: Odd that i was downvoted 1 second after posting the answer. Somebody is spiteful

Check if input field contains # [duplicate]

This question already has answers here:
checking whether textfield contains letters in javascript
(2 answers)
Closed 7 years ago.
I'm very new to JavaScript, and I am a little confused. How do I check if my input field:
<form name='formular' method='post' onsubmit='return atcheck()'>
E-mail <input type='text' name='email' id='em'>
<input type='submit' value='Submit'>
</form>
contains the symbol "#"? I'm not looking for a full good e-mail validation, I just wanna check if the field contains that symbol in particular when submitted (in the atcheck() function).
<script language="Javascript">
function atcheck(){
if(document.getElementById('em').value.indexOf('#') === -1) {
// No # in string
return false;
} else {
// # in string
return true;
}
}
</script>
Here's one way to accomplish that:
function atcheck() {
var has_at_char = document.getElementById("em").value.indexOf("#") > -1;
if (has_at_char) {
return false;
}
// your previously exisiting implementation of atcheck() could follow here
}
use indexOf() function
indexOf() documentation
to get the text on your function, you need to use document.getElementById("em").value

In JavaScript, how do I detect whether or not the input contains letters?

My code is below, it outputs what the user is typing in the text box. It should output an error message if the user puts anything other than a number. I'm confused as to how to do this, though. Quite frankly, I'd settle with it being able to detect whether or not the first letter of input is a B, but I can't quite figure that out either and the former option is preferred.
HTML
<label for="bannerID">Banner ID: B</label><input type="text" name="bannerID" id="bannerID" onkeyup="showBannerID()" value="" /><br />
<p id="bannerOutput"></p>
JavaScript
function showBannerID() {
var textInput = document.getElementById('bannerID').value;
if (textInput.length == 0) {
document.getElementById('bannerOutput').innerHTML = "<strong class=\"error\">Field can't be empty!</strong>";
}
else if (textInput.charAt(0) == "B") {
document.getElementById('bannerOutput').innerHTML = "<strong class=\"error\">Please omit the B! It's not necessary.</strong>
}
else {
document.getElementById('bannerOutput').innerHTML = "Your Banner ID is: <strong>B" + textInput + "</strong>.";
}
}
You can use regular expressions to search for anything other than numbers:
if (/[^\d]/.test(textInput)) {
/* error stuff */
}
You can use isNaN() (Not a Number) as a condition.
isNaN(123) would give false, isNaN("hello") would give true.

Categories