Detect the error message in the input field - javascript

How can I show the message if the user types a restricted symbol?
For example, if the user types * in the input field, the error message can show A filename cannot contain any of the following characters: \/:*?"<>|. I hope someone can guide me how to do it. Thanks.
<!DOCTYPE html>
<html>
<body>
<h1>How to show error message</h1>
<input type="text" class="form-control blank" id="function_code" name="function_code" title="function_code" onpaste="return false">
</body>
</html>
<script>
document.getElementById("function_code").onkeypress = function(e) {
var chr = String.fromCharCode(e.which);
if ("></\":*?|".indexOf(chr) >= 0)
return false;
};
</script>
My expected result is like below the picture if the user types the restrict symbol in the input field:

Use the input event along with a regular expression, like so:
const input = document.getElementById("function_code");
const error = document.getElementById('error');
const regex = /[\\\/:*?"<>|]+/;
input.addEventListener('input', (e) => {
const value = e.target.value;
if (regex.test(value)) {
input.value = value.slice(0, value.length - 1);
error.textContent = 'A filename cannot contain any of the following characters: \/:*?"<>|';
} else {
error.textContent = '';
}
});
input {
padding: 8px 10px;
border-radius: 5px;
font-size: 1.2rem;
}
#error {
display: block;
color: red;
margin: 5px 0 0 0;
}
<input type="text" id="function_code" name="function_code">
<span id="error"></span>

Firstly I would wrap the input in a form.
After that you can use the setCustomValidity function for the input field to set a custom message if the condition is true. When you hit enter, or submit the form, you will see the error message.
This way you can give any custom message for your input.
Pay attention to the else block for handling no error cases.
Reference: https://developer.mozilla.org/en-US/docs/Web/API/HTMLObjectElement/setCustomValidity
<!DOCTYPE html>
<html>
<body>
<h1>How to show error message</h1>
<form>
<input type="text" class="form-control blank" id="function_code" name="function_code" title="function_code" onpaste="return false">
<button type="submit">Submit</button>
</form>
<script>
document.getElementById("function_code").onkeypress = function(e) {
var chr = String.fromCharCode(e.which);
if ("></\":*?|".indexOf(chr) >= 0) {
this.setCustomValidity('A filename cannot contain any of the following characters: \/:*?"<>|');
} else {
this.setCustomValidity('');
}
};
</script>
</body>
</html>

Use HTML5 Pattern Match, below I have used the pattern ([a-zA-Z0-9]+) which simply means characters only latin alphabet and numbers 0-9. You can include the space character with
([a-zA-Z0-9]+\s{1}[a-zA-Z0-9]+)
You can learn more about regex here
This will not prevent author from entering wrong keypresses, it will only validate input. I will Include another approach to show custom error.
<form >
<input type="text" class="form-control blank" id="function_code" name="Option an" title="A name cannot contain irregular characters" pattern='([a-zA-Z0-9]+)' onpaste="return false">
<button >Submit</button>
</form>
Second approach. Use Javascript and write error to a div tag.
<!DOCTYPE html>
<html>
<body>
<h1>How to show error message</h1>
<input type="text" class="form-control blank" id="function_code" name="function_code" title="function_code" onpaste="return false">
<div id="error-box"></div>
</body>
</html>
<script>
function showError (key) {
var errBox = document.querySelector("#error-box");
errBox.textContent = "The character " + key.toString() + " is not allowed!";
//Dismiss the error
window.setTimeout(function () {
errBox.textContent = "";
}, 10000)
}
document.getElementById("function_code").onkeypress = function(e) {
var chr = String.fromCharCode(e.which);
if ("></\":*?|".indexOf(chr) >= 0)
showError(chr)
return false;
};
</script>

Related

HTML check user input in form for letters

Hi I am new to HTML and JavaScript. I want to check the users phone number input for any letters, and print out those letters within the error message.
I'm a bit lost at the moment, can I save input as a string (as shown by the pseudo code saving input as InsertLetter). As well as put any string characters that are letters into an error message?
<form onsubmit="return isnumb()">
<label for="ph"> Enter Phone: </label>
<input type="text" id="phnumb"> <span
id="message"></span>
//InsertLetter = phnumb output
</form>
<script>
function isnumb() {
if (document.getElementById("phnumb").match =([a-z]))
{document.getElementById("message").innerHTML =
"<em> Number includes letter" + InsertLetter + "</em>";
return false;}
else return true;
It is far better to use <input type="tel"> in this situation. On that occasion user input should follow the given pattern which you can check with. Use Form Validation for the rest of the work, for example:
const phone = document.getElementById("phone");
const button = document.getElementsByTagName('button')[0];
const errorMessage = document.querySelector('p.error');
button.addEventListener('click', (e) => {
if (!phone.validity.valid) {
showError();
e.preventDefault();
}
});
phone.addEventListener('keyup', (e) => {
if (phone.validity.valid) {
errorMessage.innerHTML = '';
} else {
showError();
}
});
function showError() {
if (phone.validity.valueMissing) {
errorMessage.textContent = "Phone is required";
}
if (phone.validity.patternMismatch) {
errorMessage.textContent = "You are not supposed to use characters like this one: " + phone.value;
}
if (phone.validity.valid) {
phone.setCustomValidity("");
}
}
.error {
color: red;
}
<form>
<label for="phone">Phone Number (Format: +99 999 999 9999)</label>
<input type="tel" id="phone" name="phone" pattern="[\+]\d{2}[\s]\d{3}[\s]\d{3}[\s]\d{4}" required>
<p class="error"></p>
<button>Submit</button>
</form>
First of all i want to give u an answer of user should insert only number :`
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function submitForm() {
var phonenumber = document.forms["myForm"]["notanumber"].value;
if (isNaN(phonenumber)) {
alert("only number required");
} else {
alert("submit");
}
}
</script>
</head>
<body>
<form id="myForm">
<input type="text" id="notanumber" />
<input type="submit" onclick="submitForm()" />
</form>
</body>
</html>
-> isNaN() is an inbuilt function in js, if variable is not a number, it return true, else return false.
the simple code :
restric the user from clicking any key, Only numbers allowed.
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function submit() {
alert("submited");
}
function noAlphabets(e) {
var phonenumber = document.forms["myForm"]["notanumber"].value;
var x = e.which || e.keycode;
if (x >= 48 && x <= 57) {
return submit();
} else {
alert("insert only numbers");
return false;
}
}
</script>
</head>
<body>
<form id="myForm">
<input
type="text"
id="notanumber"
onkeypress="return noAlphabets(event)"
/>
<button type="button" onclick="submit()">Submit</button>
</form>
</body>
</html>

Form submits even when there is an invalid input

I am trying to validate the text input in my html. I only want alphabets and spaces. In the beginning, the validation worked but now it is not and I cannot seem to find the problem. It still submits the form with the invalid field. Please see the code below
index.html
<div class="full-form">
<form class=form-info action="cv.html" onsubmit="return handlesubmit()" >
<div class="f-header">
SIGN UP
</div>
<div class="bdetails">
<label for="fname">First Name</label><br>
<input type="text" name="fname" id="f_name" placeholder="First Name" onfocus="checkFName()" onblur="BlurFName()" required><br>
<p class="error_message" id="First_em">Name must contain only alphabets(A-Z)</p>
</div>
<script type="text/javascript" src="test.js"></script>
</form>
test.js
function checkData(){
if(BlurFName()){
}
return false;
}
function handlesubmit(){
checkData();
passvalue();
}
/*
Function to check if the name inputted is valid when the input is focused
*/
function checkFName(){
let name_len=/^[A-Za-z]+$/;
let fname= document.getElementById("f_name");
if(!fname.value.match(name_len)){
document.getElementById("First_em").style.display = "inline";
return true;
}
};
/*
Function to check if the name inputted is valid when the input is blurred
*/
function BlurFName(){
let name_len=/^[A-Za-z]+$/;
let fname= document.getElementById("f_name");
if(fname.value.match(name_len)){
document.getElementById("First_em").style.display = "none";
return false;
}
};
With function handlesubmit you need to return false or true.
I suggest use
e.preventDefault();
to easier handle Form submiting
You are not returning anything from your validation method. You need to do something like this:
function validateName () {
const inp = document.getElementById("fname");
const isValid = inp.value.trim().length > 0;
inp.classList.toggle('error', !isValid);
return isValid;
}
function validateGuess () {
const inp = document.getElementById("guess");
const isValid = +inp.value.trim() > 10;
inp.classList.toggle('error', !isValid);
return isValid;
}
function validate () {
const isNameValid = validateName();
const isGuessValid = validateGuess();
return isNameValid && isGuessValid;
}
.error { border-color: red; }
<form onsubmit="return validate()">
<label for="fname">name</label> <input type="text" name="fname" id="fname" /><br/>
<label for="guess">guess</label> <input type="number" name="guess" id="guess" />
<button>Submit</button>
</form>

Error message beside textbox onkeyup event

I have textboxes that I want to show the error prompt beside it onkeyup event, but with no luck, it doesn't work. I have this as my reference: I want to show error message beside my textbox rather than alert in onkeyup event
$(function() {
$("#name").next('span').hide();
$("#name").keyup(function() {
var input = $(this).val();
var span = $(this).next('span');
if (name == "") {
span.text("Please enter your name").show();
return;
}
span.text('').hide();
});
$("#age").next('span').hide();
$("#age").keyup(function() {
var input = $(this).val();
var span = $(this).next('span');
if (age == "") {
span.text("Please enter your age").show();
return;
}
span.text('').hide();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="name" name="name" />
<hr>
<span></span>
<input type="text" id="age" name="age" />
<span></span>
You are using wrong variable names to check the values of the name field and age field.
Also, the span for the name field is after the hr it should be right next to the input field.
Check the snippet below, see the comments added;
Notice the Regex .replace(/\s/g,'') for removing all whitespace in the if condition.
$(function() {
$("#name").next('span').hide();
$("#name").keyup(function() {
var input = $(this).val();
var span = $(this).next('span');
if (input.replace(/\s/g,'') == "") { // wrong variable, name is undefined, should be input, also the regex is for removing all whitespaces;
span.text("Please enter your name").show();
return;
}
span.text('').hide();
});
$("#age").next('span').hide();
$("#age").keyup(function() {
var input = $(this).val();
var span = $(this).next('span');
if (input.replace(/\s/g,'') == "") { // same here
span.text("Please enter your age").show();
return;
}
span.text('').hide();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="name" name="name" />
<span></span> <!-- span should be here, before the hr line break -->
<hr>
<input type="text" id="age" name="age" />
<span></span>

Jquery/Form - check input field is at least 5 characters long - and also doesn't match certain words

I have a very simple form. Full Name/Email. What I want to do is check with jquery to make sure that they entered AT LEAST 5 characters in the name field. And if they did not, then I don't want the form to be submitted, instead I want to print some HTML below the form showing a warning/error message. How can I accomplish this?
Also Can I add words manually to the script to make sure they were not entered in the name field? And if they were to make sure it prints errors again... For example, if they entered the word "bobby" or "stephanie" I don't want the form to be submitted if those EXACT words are entered. It is only like 5 or 6 words I want blocked, so I can enter them manually no problem in the script without bloating anything.
Thank you so much in advance.
Here is my HTML
<div id="div1">
<label id="name-label" for="full_name">Name</label>
<input id="full_name" type="text" name="name" tabindex="1" autofocus="1">
</div>
<div id="div2">
<label id="email-label" for="email_address">Email</label>
<input id="email_address" type="email" tabindex="2" name="email">
</div>
And this is the added HTML I want printed if the jquery check is false
<div id="error">
<span class="error_message">Please enter your full name</span>
</div>
Let's assume your form has an id of myForm.
var words = ["bobby", "stephanie"];
jQuery('#myForm').on('submit', function(evt) {
var form = $(this);
var full_name = form.find('#full_name');
var name_length = full_name.val().length;
if( name_length < 5 ) {
jQuery('#error').show();
evt.preventDefault();
}
if( jQuery.inArray(full_name.val(), words) ) {
evt.preventDefault();
}
});
Here is my answer: there are two if statements that we can construct:
Test if length of input exceeds 5 characters, and
Test if the input matches a list of banned words (stored in an array for convenience and verbosity)
It is a little complicated with the second conditional statement, since we want an exact match (therefore, using 'bobby' will raise a flag, but not 'bobby123'. This involves the use of word boundaries, \b.
You can view the code in action in this fiddle: http://jsfiddle.net/teddyrised/kmMcC/
$('form').submit(function(e) {
var errorFlag = 0,
bannedWords = [
'bobby',
'stephanie'
],
bannedObj = new RegExp('\\b'+bannedWords.join('|')+'\\b', 'i');
if($('#full_name').val().length <= 5) {
errorFlag = 1;
}
if(bannedObj.test($('#full_name').val())) {
errorFlag = 1;
}
// Act on error flag, prevent form submission when one or more error flags are raised
if(errorFlag) e.preventDefault();
});
Assuming you put this all in a form element, and add an input type='submit' element to it, I would suggest setting the form's onsubmit attribute to "return Validate();", and add the below validation function.
First you'll want to hide the message on ready using: $('error').hide();
function Validate(){
var minLength = 5;
var blockedNames = ["bobby","stephanie"];
var fName = $('#full_name').val();
if(fName.length < minLength){
$('#error').show();
$('#full_name').focus();
return false;
}
for(var i = 0;i < blockedNames.length;i++){
if(fName == blockedNames[i]){
$('#error').show();
$('#full_name').focus();
return false;
}
}
return true;
}
JSFIDDLE DEMO: http://jsfiddle.net/softvar/hv6yB/2/
UPDATE:
HTML
<form onsubmit="return check()">
<div id="div1">
<label id="name-label" for="full_name">Name</label>
<input id="full_name" type="text" name="name" tabindex="1" autofocus="1" />
</div>
<div id="div2">
<label id="email-label" for="email_address">Email</label>
<input id="email_address" type="email" tabindex="2" name="email" />
</div>
<input type="submit" value="Submit"/>
</form>
<div id="error" >
<span class="error_message">Please enter your full name</span>
</div>
CSS
#error {
color:red;
display: none;
border: 1px solid #D9534F;
background: #FDF7F7;
width: 80%;
height: 25px;
padding: 5px;
}
JS
function check() {
var bannedWords = ['bobby','stephen'];
var name= $('#full_name').val();
if(name){
if(name.length>5){
for(var i=0;i<bannedWords.length;i++) {
if(bannedWords[i] ==name){
$('#error').text('Its a banned word');
$('#error').css('display','inline-block');
return false;
}
}
alert('form is going to be submitted');
return true;
}
else{
$('#error').text('Name is shorter');
$('#error').css('display','inline-block');
return false;
}
}
$('#error').text('Name cant be blank');
$('#error').css('display','inline-block');
return false;
}

Stopping action if requirements are not met

I want to check the validation of two text boxs if either one is empty. It showed show an error as an innerHTML and if they are both filled in. It will then continue to action. Here is my code:
function go()
{
var toCheck = document.getElementById('myAnchor');
if (toCheck != '') {
return true;
}
else
{
document.getElementById('myAnchor').innerHTML = 'Fred Flinstone';
}
}
this does set the innerHTML but still continues with the action. How can I stop it from continuing?
Thank you!
You should check the value of text box,
Change the code to
function go()
{
var toCheck = document.getElementById('myAnchor').value;
if (toCheck != '') {
return true;
}
else
{
document.getElementById('myAnchor').innerHTML = 'Fred Flinstone';
}
}
add the onsubmit on the form:
<form onsubmit="return true;">
...
</form>
if the return is false it will stop from submitting an opposite scenario if it's true. you could also call your functions on that attribute and do the same thing then if it doesn't fit the condition it will stop from submitting your form and do the other process you desire to happen.
Textfields use the value attribute.
document.getElementById('myAnchor').value = 'Fred Flinstone';
An empty textfield would have a value of "".
function go()
{
var toCheck = document.getElementById('myAnchor');
if (toCheck.value != "") {
return true;
}
else
{
toCheck.value = 'Fred Flinstone';
}
}
Here's a working example.
<!DOCTYPE html>
<html>
<body>
<form name="form" action="data.php">
<label style="float:left">
<font face="Comic Sans MS">* username &nbsp
</label></font>
<input type="text" id='textfield' name="name" size="40" style="float: left;">
<label id='myAnchor' style="display: inline; padding-left: 20px;"></label> <br/> <br/>
<label style="float:left"><font face="Comic Sans MS">* password &nbsp</label></font>
<input type="text" name="pwd" size="40" style="float: left;">
<label id="myAnchor2" style="display: inline; padding-left: 20px;">
</label> <br/> </p> <input type="button" value="LogIn" onClick="return go();"> </form>
</body>
<script>
function go()
{
var toCheck = document.getElementById('textfield');
if (toCheck.value != "") {
return true;
}
else
{
toCheck.value = 'Fred Flinstone';
}
}
</script>
</html>
In your question you said that
I want to check the validation of two text boxs
In that case you should be checking the value of textboxes, not the myAnchor.
I would change your html code like this:
<input type="text" name="name" id="name" size="40" style="float: left;">
<input type="text" name="pwd" id="pwd" size="40" style="float: left;">
<input type="submit" value="LogIn" onSubmit="go();">
adding id to the input boxes
then change the onClick event to onSubmit. that way you can perform javascript validation in the function, then submit the form if all goes well, otherwise display the error.
Then your script will be like...
function go() {
var name = document.getElementById('name').value,
pwd = document.getElementById('pwd').value;
if (name != '' && pwd != '') {
document.forms["form"].submit();
}
else {
document.getElementById('myAnchor').innerHTML = 'Fred Flinstone';
}
}

Categories

Resources